<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by M Rastegar on Medium]]></title>
        <description><![CDATA[Stories by M Rastegar on Medium]]></description>
        <link>https://medium.com/@m.rastegar991?source=rss-23d49b6d6b51------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*HDiX5DdkVqM-kt1y.jpg</url>
            <title>Stories by M Rastegar on Medium</title>
            <link>https://medium.com/@m.rastegar991?source=rss-23d49b6d6b51------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 15:13:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@m.rastegar991/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[ React-ConStore: The State Management Revolution is Here!]]></title>
            <link>https://medium.com/@m.rastegar991/react-constore-the-state-management-revolution-is-here-1f4706a6579a?source=rss-23d49b6d6b51------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f4706a6579a</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[zustand]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[state-management]]></category>
            <category><![CDATA[typescript-with-react]]></category>
            <dc:creator><![CDATA[M Rastegar]]></dc:creator>
            <pubDate>Thu, 22 May 2025 09:36:41 GMT</pubDate>
            <atom:updated>2025-05-22T09:58:43.000Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PCKjmw7nIL9LJQu2tC_-VA.png" /></figure><h3>Stop Wrestling with Heavy State Libraries — Meet Your New Best Friend! ⚡</h3><p><strong>Tired of bloated Redux setups? Fed up with complex Zustand configurations?</strong><br> <strong>Welcome to React-ConStore — the ultra-lightweight state management solution that actually makes sense!</strong></p><h4>🎯 Why Developers Are Going Crazy for React-ConStore</h4><h4>⚡ ULTRA-LIGHTWEIGHT → Less than 1KB gzipped!</h4><p><em>While others burden your app with 2–3KB+, we keep it lean and mean</em></p><h4>🚀 FUTURE-READY → React 18 &amp; 19 Compatible</h4><p><em>Built for modern React with full concurrent features support</em></p><h4>🎯 SMART RENDERING → Zero Unnecessary Re-renders</h4><p><em>Components update ONLY when their data actually changes</em></p><h4>🪝 FAMILIAR API → Uses React Hooks You Already Know</h4><p><em>No new concepts to learn — if you know hooks, you know ConStore</em></p><h3>💥 See the Magic in Action</h3><pre>// Create store in seconds<br>const store = createStore({<br>  count: 0,<br>  user: { name: &#39;Guest&#39; }<br>});<br><br>// Use anywhere with familiar hooks<br>function Counter() {<br>  const [count, setCount] = store.useStoreKey(&#39;count&#39;);<br>  <br>  return (<br>    &lt;button onClick={() =&gt; setCount(count + 1)}&gt;<br>      Count: {count}<br>    &lt;/button&gt;<br>  );<br>}</pre><p><strong>That’s it!</strong> No providers, no reducers, no middleware hell!</p><h3>🔥 What Developers Are Saying</h3><p><em>“Finally, a state library that doesn’t make me want to pull my hair out!”</em></p><p><em>“Migrated from Redux in 10 minutes. My bundle size dropped by 60%!”</em></p><p><em>“Perfect for Next.js 13+ App Router. Just works!”</em></p><h3>✨ Premium Features That Cost You Nothing</h3><ul><li>🎯 <strong>Selective Subscriptions</strong> → Subscribe to specific keys</li><li>📝 <strong>Full TypeScript Support</strong> → Type safety out of the box</li><li>🌐 <strong>Server Components Ready</strong> → Next.js 13+ compatible</li><li>🔄 <strong>Automatic Batching</strong> → Optimized for React 18/19</li><li>🧠 <strong>Deep Equality Checks</strong> → Prevents unnecessary renders</li><li>🛠️ <strong>DevTools Compatible</strong> → Debug with React DevTools</li></ul><h3>🚀 Get Started in 30 Seconds</h3><pre>npm install react-constore<br># or<br>yarn add react-constore</pre><p><strong>One command. Zero configuration. Infinite possibilities.</strong></p><h3>🎉 Join Thousands of Happy Developers</h3><p><strong>⭐ Star us on GitHub</strong><br> <strong>📦 Install today</strong><br> <strong>🚀 Ship faster apps tomorrow</strong></p><h3>👉 <a href="https://github.com/mostafarastegar/react-constore">GET REACT-CONSTORE NOW</a></h3><p><em>React-ConStore: Because your state management should be simple, not a PhD thesis.</em></p><p><strong>#ReactJS #StateManagement #JavaScript #TypeScript #WebDev #React18 #React19</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f4706a6579a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing MVP Architecture in React with React Query: A Modern Approach]]></title>
            <link>https://medium.com/@m.rastegar991/implementing-mvp-architecture-in-react-with-react-query-a-modern-approach-207afdf475e6?source=rss-23d49b6d6b51------2</link>
            <guid isPermaLink="false">https://medium.com/p/207afdf475e6</guid>
            <category><![CDATA[typescript-with-react]]></category>
            <category><![CDATA[mvp-architecture]]></category>
            <category><![CDATA[mvc-architecture]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[reactjs]]></category>
            <dc:creator><![CDATA[M Rastegar]]></dc:creator>
            <pubDate>Wed, 14 May 2025 07:26:49 GMT</pubDate>
            <atom:updated>2025-05-14T07:26:49.212Z</atom:updated>
            <content:encoded><![CDATA[<h3>Abstract</h3><p>This article examines the implementation of the Model-View-Presenter (MVP) architectural pattern in React applications using React Query as a data management solution. While React’s component-based architecture diverges from traditional MVP patterns, this research demonstrates how MVP principles can be effectively applied to React projects through custom hooks and React Query to achieve better separation of concerns, improved testability, and maintainable codebases. The proposed approach addresses common architectural challenges in complex React applications and provides practical implementation strategies with concrete code examples.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CzWR3lHWdaz7HxOf5xAz7A.jpeg" /><figcaption>MVP Architecture in React with React Query</figcaption></figure><h3>Introduction</h3><p>React has become a leading frontend library, largely due to its component-based structure and virtual DOM. However, as applications become more complex, developers often face architectural challenges in maintaining code quality, ensuring testability, and separating concerns. Traditional patterns like MVC and MVP offer solutions, but they don’t always translate well to React’s unique architecture.</p><p>This article explores how the MVP architectural pattern can be effectively adapted for React applications while leveraging React Query, a modern data-fetching and state management library. The research addresses three primary questions:</p><ol><li>How can MVP be adapted to align with React’s component-based architecture?</li><li>What role does React Query play in implementing the Model layer of MVP?</li><li>How can custom hooks serve as Presenters to mediate between Model and View layers?</li></ol><h3>The MVP Architectural Pattern</h3><p>The Model-View-Presenter (MVP) pattern is a derivative of the Model-View-Controller (MVC) pattern, designed to improve separation of concerns and testability. In MVP:</p><ul><li><strong>Model</strong>: Contains domain data and business logic</li><li><strong>View</strong>: A passive interface that displays data and routes user commands to the Presenter</li><li><strong>Presenter</strong>: Acts as a mediator that retrieves data from the Model, formats it, and updates the View</li></ul><p>A key characteristic of MVP is the passive nature of the View, which, unlike in MVC, does not interact directly with the Model. This creates a clearer separation of concerns and improves testability, as presenters can be tested independently of views.</p><h3>React’s Component Architecture</h3><p>React employs a component-based architecture where UI elements are encapsulated into components that manage their own state and lifecycle. This differs from traditional MVC/MVP patterns where separation typically occurs across distinct files or modules representing different architectural layers.</p><p>React’s architectural philosophy includes:</p><ul><li>Unidirectional data flow</li><li>Component composition</li><li>Local state management</li><li>Hooks for stateful logic and side effects</li></ul><p>These principles don’t inherently contradict MVP but require thoughtful adaptation to align with MVP’s separation of concerns.</p><h3>React Query Overview</h3><p>React Query is a data-fetching and state management library that provides:</p><ul><li>Server state management</li><li>Caching</li><li>Background updates</li><li>Pagination and infinite scrolling support</li><li>Mutation capabilities</li><li>Query invalidation</li></ul><p>As a specialized tool for server-state management, React Query offers a unique opportunity to implement part of the Model layer in MVP architecture.</p><h3>Proposed Architecture: MVP in React with React Query</h3><h3>Architectural Overview</h3><p>Our proposed adaptation of MVP for React applications consists of:</p><p><strong>Model Layer</strong>:</p><ul><li>Data Types/Interfaces (Business Model)</li><li>API Services</li><li>Business Logic Services</li></ul><p><strong>Presenter Layer</strong>:</p><ul><li>Custom Hooks using React Query directly</li><li>Integration of API services with React Query</li><li>State transformations and UI-specific logic</li></ul><p><strong>View Layer</strong>:</p><ul><li>Pure functional React components</li><li>No direct access to the Model layer</li><li>Receives props from Presenters</li></ul><p>The key innovation in this approach is using React Query hooks as Presenters, which aligns naturally with React’s functional paradigm while maintaining MVP’s separation of concerns. Rather than creating a separate Data Access Layer, React Query serves as the core of our Presenter implementation.</p><pre>src/<br>├── models/                      # Model layer<br>│   ├── types/                   # Type definitions<br>│   │   └── ProductTypes.ts<br>│   │<br>│   │<br>│   └── services/                # API and Business Logic services<br>│       ├── api/<br>│       │   └──productApiService.ts<br>│       │<br>│       │<br>│       └── domain/<br>│           └── productBusinessService.ts<br>│<br>├── presenters/                  # Presenter layer (React Query hooks)<br>│   └── useProductsPresenter.ts<br>│<br>│<br>│<br>├── views/                       # View layer (Pure components)<br>│   └── ProductListView.tsx<br>│<br>│<br>│<br>├── pages/                       # Page components that use presenters and views<br>│   └── ProductsPage.tsx<br>│   <br>│<br>│<br>└── App.tsx                      # Application root component</pre><h3>1. The Model Layer in Detail</h3><p>The Model layer in our architecture consists of multiple sublayers:</p><h4>1.1 Business Model</h4><p>The Business Model defines data structures and entity relationships:</p><pre>// models/types/ProductTypes.ts<br>export interface Product {<br>  id: number;<br>  name: string;<br>  price: number;<br>  inStock: boolean;<br>}</pre><h4>1.2 API Services</h4><p>API Services handle communication with backend services:</p><pre>// models/services/productApiService.ts<br>import axios from &#39;axios&#39;;<br>import { Product } from &#39;../types/ProductTypes&#39;;<br><br>export const productApiService = {<br>  getProducts: async () =&gt; {<br>    const response = await axios.get(&#39;/api/products&#39;);<br>    return response.data;<br>  }<br>};</pre><h4>1.3 Business Logic Services</h4><p>Business Logic Services implement domain-specific rules and operations:</p><pre>// models/services/productBusinessService.ts<br>import { Product } from &#39;../types/ProductTypes&#39;;<br><br>export const productBusinessService = {<br>  formatPrice: (price: number): string =&gt; {<br>    return `${price.toFixed(2)}`;<br>  },<br>  <br>  filterAvailableProducts: (products: Product[]): Product[] =&gt; {<br>    return products.filter(product =&gt; product.inStock);<br>  }<br>};</pre><h3>2. Presenter Layer with React Query</h3><p>React Query serves as the foundation of the Presenter layer in our MVP architecture by:</p><p><strong>Directly handling server-state interactions</strong>: React Query provides built-in hooks that handle the complete lifecycle of data fetching, caching, and mutations.</p><p><strong>Mediating between Model and View</strong>: React Query hooks encapsulate the interaction with API services (Model) and prepare data for consumption by View components.</p><p><strong>Providing optimistic updates</strong>: Improves UX while maintaining architectural boundaries between layers.</p><p><strong>Simplifying the architecture</strong>: By using React Query’s hooks directly as Presenters, we eliminate the need for additional abstraction layers, resulting in a cleaner architecture.</p><p><strong>Maintaining separation of concerns</strong>: Though React Query communicates with the API layer, it doesn’t contain business logic itself, preserving the separation between data retrieval and business rules.</p><pre>// presenters/useProductsPresenter.ts<br>import { useQuery } from &#39;react-query&#39;;<br>import { productApiService } from &#39;../models/services/productApiService&#39;;<br>import { productBusinessService } from &#39;../models/services/productBusinessService&#39;;<br>import { useMemo } from &#39;react&#39;;<br><br>export const useProductsPresenter = (showOnlyInStock = false) =&gt; {<br>  // React Query directly acts as the Presenter<br>  const { data: products = [], isLoading, error } = useQuery(<br>    &#39;products&#39;, <br>    productApiService.getProducts<br>  );<br>  <br>  // Transform data for the View<br>  const displayProducts = useMemo(() =&gt; {<br>    // Apply business logic<br>    let result = products;<br>    <br>    if (showOnlyInStock) {<br>      result = productBusinessService.filterAvailableProducts(result);<br>    }<br>    <br>    // Transform data for display<br>    return result.map(product =&gt; ({<br>      ...product,<br>      formattedPrice: productBusinessService.formatPrice(product.price)<br>    }));<br>  }, [products, showOnlyInStock]);<br>  <br>  return {<br>    products: displayProducts,<br>    isLoading,<br>    error<br>  };<br>};</pre><h3>3. View Layer: Pure Components</h3><p>The View layer consists of pure functional components receiving props from Presenters:</p><pre>// views/ProductListView.tsx<br>import React from &#39;react&#39;;<br>import { Product } from &#39;../models/types/ProductTypes&#39;;<br><br>interface ProductListViewProps {<br>  products: (Product &amp; { formattedPrice: string })[];<br>  isLoading: boolean;<br>  error: unknown;<br>}<br><br>const ProductListView: React.FC&lt;ProductListViewProps&gt; = ({ <br>  products, <br>  isLoading, <br>  error <br>}) =&gt; {<br>  if (isLoading) return &lt;div&gt;Loading products...&lt;/div&gt;;<br>  if (error) return &lt;div&gt;Error loading products&lt;/div&gt;;<br>  <br>  return (<br>    &lt;div className=&quot;product-list&quot;&gt;<br>      &lt;h2&gt;Products&lt;/h2&gt;<br>      &lt;ul&gt;<br>        {products.map(product =&gt; (<br>          &lt;li key={product.id} className={!product.inStock ? &#39;out-of-stock&#39; : &#39;&#39;}&gt;<br>            &lt;span className=&quot;product-name&quot;&gt;{product.name}&lt;/span&gt;<br>            &lt;span className=&quot;product-price&quot;&gt;{product.formattedPrice}&lt;/span&gt;<br>            {!product.inStock &amp;&amp; &lt;span className=&quot;stock-label&quot;&gt;Out of stock&lt;/span&gt;}<br>          &lt;/li&gt;<br>        ))}<br>      &lt;/ul&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default ProductListView;</pre><h4>3.1 Connecting Everything</h4><p>Finally, we connect the Presenter and View in the application:</p><pre>// pages/ProductsPage.tsx<br>import React, { useState } from &#39;react&#39;;<br>import { useProductsPresenter } from &#39;../presenters/useProductsPresenter&#39;;<br>import ProductListView from &#39;../views/ProductListView&#39;;<br><br>const ProductsPage: React.FC = () =&gt; {<br>  const [showOnlyInStock, setShowOnlyInStock] = useState(false);<br>  <br>  // Use the Presenter<br>  const productsData = useProductsPresenter(showOnlyInStock);<br>  <br>  return (<br>    &lt;div className=&quot;products-page&quot;&gt;<br>      &lt;div className=&quot;filter-controls&quot;&gt;<br>        &lt;label&gt;<br>          &lt;input<br>            type=&quot;checkbox&quot;<br>            checked={showOnlyInStock}<br>            onChange={() =&gt; setShowOnlyInStock(prev =&gt; !prev)}<br>          /&gt;<br>          Show only in-stock products<br>        &lt;/label&gt;<br>      &lt;/div&gt;<br>      <br>      &lt;ProductListView {...productsData} /&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default ProductsPage;</pre><h3>Advantages of the Proposed Architecture</h3><p><strong>Clear Separation of Concerns</strong>:</p><ul><li>Business Model and Business Logic are isolated from UI components</li><li>Views remain purely presentational</li><li>React Query Presenters mediate all interactions between Models and Views</li></ul><p><strong>Enhanced Testability</strong>:</p><ul><li>React Query Presenter hooks can be tested using @testing-library/react-hooks</li><li>Pure View components can be tested in isolation</li><li>Business Logic services can be unit-tested independently</li></ul><p><strong>Code Reusability</strong>:</p><ul><li>Presenter hooks can be reused across multiple components</li><li>Business Logic services provide centralized, reusable functionality</li><li>React Query handles common data-fetching patterns</li></ul><p><strong>Maintainability</strong>:</p><ul><li>Changes to UI don’t affect business logic</li><li>API changes are isolated to the Model layer</li><li>Clear boundaries reduce unexpected side effects</li></ul><h3>Comparison with Other Approaches</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FthIq441zKkAM0c8489UzQ.png" /></figure><h3>Potential Challenges</h3><ol><li><strong>Learning Curve</strong>: Developers familiar with traditional React patterns may need time to adapt</li><li><strong>Overhead for Simple Applications</strong>: Small applications may not benefit enough to justify the complexity</li><li><strong>Evolution with React</strong>: As React evolves, adjustments to the pattern may be necessary</li></ol><h3>Conclusion</h3><p>This article has presented a practical approach to implementing the Model-View-Presenter (MVP) architectural pattern in React applications using React Query as the Presenter. By combining React’s component-based nature with MVP’s separation of concerns, we’ve demonstrated a clean, testable, and maintainable architecture.</p><p><strong>React Query as Presenter</strong>: React Query effectively serves as the Presenter, mediating between the Model and View by handling data fetching, caching, and state management.</p><p><strong>Clean Separation of Concerns</strong>:</p><ul><li>Model: Data types and business logic</li><li>Presenter: React Query hooks with data transformation</li><li>View: Pure UI components</li></ul><p><strong>Simplicity Through Composition</strong>: Complex Presenters are broken down into smaller, composable hooks for enhanced simplicity and maintainability.</p><p><strong>Improved Developer Experience</strong>: This pattern leads to more testable, readable, and maintainable code.</p><p>This approach offers a powerful and practical alternative to other state management patterns in React, especially for applications with significant server-state requirements.</p><h3>References</h3><ol><li>Fowler, M. (2006). Presentation Model. <em>Patterns of Enterprise Application Architecture</em>.</li><li>Potel, M. (1996). MVP: Model-View-Presenter. The Taligent Programming Model for C++ and Java.</li><li>Abramov, D. (2015). Presentational and Container Components. <em>Medium</em>.</li><li>Dabit, N. (2019). React Custom Hooks: The Complete Guide. <em>Scotch.io</em>.</li><li>Tanner, T. (2021). React Query: React Hooks for Fetching, Caching and Updating Asynchronous Data. <em>GitHub</em>.</li><li>reactjs.org. (2022). Hooks API Reference. <em>React Documentation</em>.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=207afdf475e6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CleanDeadCode: A VS Code Extension for Eliminating Unused Code]]></title>
            <link>https://medium.com/@m.rastegar991/cleandeadcode-a-vs-code-extension-for-eliminating-unused-code-7229fdc78491?source=rss-23d49b6d6b51------2</link>
            <guid isPermaLink="false">https://medium.com/p/7229fdc78491</guid>
            <category><![CDATA[vscode-extension]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[M Rastegar]]></dc:creator>
            <pubDate>Fri, 04 Apr 2025 08:28:11 GMT</pubDate>
            <atom:updated>2025-04-04T08:50:58.798Z</atom:updated>
            <content:encoded><![CDATA[<p>Dead code is the silent productivity killer in software development. Those unused imports, forgotten variables, and abandoned function parameters might seem harmless, but they gradually accumulate, creating confusion, hindering readability, and making maintenance more difficult. As codebases grow, so does the importance of keeping them clean and efficient.</p><p>In this article, I’ll introduce <a href="https://marketplace.visualstudio.com/items?itemName=MostafaRastegar.clean-dead-code"><strong>CleanDeadCode</strong></a>, a specialized VS Code extension I’ve developed to automatically identify and remove unused imports and variables while preserving your code’s structure and intent.</p><h3>The Problem of Dead Code</h3><p>JavaScript and TypeScript projects are particularly susceptible to dead code issues. As components evolve, dependencies change, and features get refactored, it’s easy to leave behind traces of unused code. Consider these common scenarios:</p><ul><li>You import a library function you no longer need</li><li>You add a React hook but end up using an alternative approach</li><li>You define parameters in a function signature but never use them in the implementation</li><li>You create temporary variables for debugging that remain after fixes are implemented</li></ul><p>The built-in VS Code “Organize Imports” feature can help with unused imports, but it also reorders your imports, which can disrupt your preferred organization system. Meanwhile, ESLint warnings about unused variables require manual intervention to fix.</p><h3>Introducing CleanDeadCode</h3><p>CleanDeadCode solves these problems with precision, offering two powerful features:</p><ol><li><strong>Smart Import Cleaning</strong>: Removes unused imports without changing the order of remaining imports</li><li><strong>Intelligent Variable Management</strong>: Comments out unused variables and handles function parameters contextually</li></ol><p>Let’s explore how these features work and the problems they solve.</p><h3>Smart Import Cleaning</h3><p>Unlike VS Code’s built-in “Organize Imports” functionality (which reorders all imports alphabetically), CleanDeadCode preserves your intentional import organization. It removes only what’s unused.</p><h3>Key Capabilities</h3><ul><li>Preserves the order of remaining imports</li><li>Supports all import types:</li><li>Default imports: import React from &#39;react&#39;</li><li>Named imports: import { useState, useEffect } from &#39;react&#39;</li><li>Named imports with aliases: import { useState as useStateHook } from &#39;react&#39;</li><li>Namespace imports: import * as ReactDOM from &#39;react-dom&#39;</li><li>Side-effect imports: import &#39;styles.css&#39;</li></ul><p>Let’s look at a before-and-after example:</p><p><strong>Before Cleaning:</strong></p><pre>import React, { useState, useEffect, useContext } from &#39;react&#39;;<br>import { useNavigate } from &#39;react-router-dom&#39;;<br>import * as utils from &#39;./utils&#39;;<br>function MyComponent() {<br>  const [count, setCount] = useState(0);<br>  // Only useState is used, useEffect and useContext are unused<br>  // Also useNavigate and utils are unused<br>  <br>  return &lt;div&gt;{count}&lt;/div&gt;;<br>}</pre><p><strong>After Cleaning with CleanDeadCode:</strong></p><pre>import React, { useState } from &#39;react&#39;;<br>function MyComponent() {<br>  const [count, setCount] = useState(0);<br>  <br>  return &lt;div&gt;{count}&lt;/div&gt;;<br>}</pre><p>Notice how the extension intelligently:</p><ul><li>Removed unused named imports (useEffect, useContext) while keeping useState</li><li>Completely removed unused imports (useNavigate, utils)</li><li>Preserved the original order of what remains</li></ul><h3>Intelligent Variable Management</h3><p>CleanDeadCode takes a nuanced approach to managing unused variables and function parameters:</p><h3>For Unused Variables:</h3><p>The extension comments them out with a TODO tag, helping you decide whether to remove them entirely or keep them for future use:</p><p><strong>Before:</strong></p><pre>function processData() {<br>  const data = fetchData();<br>  const config = getConfig(); // Unused variable<br>  <br>  console.log(data);<br>  <br>  return data;<br>}</pre><p><strong>After:</strong></p><pre>function processData() {<br>  const data = fetchData();<br>  // TODO: Unused variable<br>  // const config = getConfig();<br>  <br>  console.log(data);<br>  <br>  return data;<br>}</pre><h3>For Function Parameters:</h3><p>The extension applies context-aware transformations:</p><ol><li><strong>Unused parameters needed for position</strong>: Adds an underscore prefix</li><li><strong>Trailing unused parameters</strong>: Removes them completely</li></ol><p><strong>Before:</strong></p><pre>function processUser(userId, userName, userRole, userAge) {<br>  console.log(`Processing ${userName}`);<br>  // Only userName is used, other parameters are unused<br>}</pre><p><strong>After:</strong></p><pre>function processUser(_userId, userName) {<br>  console.log(`Processing ${userName}`);<br>  // Only userName is used, other parameters are unused<br>}</pre><p>In this example:</p><ul><li>userId gets an underscore prefix because it&#39;s needed to maintain the position of userName</li><li>userRole and userAge are removed completely as they come after the last used parameter</li></ul><h3>Implementation Challenges</h3><p>Developing CleanDeadCode presented several interesting technical challenges:</p><h3>Import Analysis</h3><p>Accurately determining which imports are used required deep AST (Abstract Syntax Tree) analysis using TypeScript’s compiler API. Simply using regex patterns would miss many edge cases, especially with aliased imports and object destructuring.</p><h3>Context-Aware Parameter Handling</h3><p>Managing function parameters required considering their positions relative to other parameters. The extension needs to distinguish between:</p><ul><li>Parameters that must remain for positional reasons</li><li>Parameters that can be safely removed</li></ul><h3>Preserving Code Structure</h3><p>Ensuring the extension doesn’t disrupt code formatting or organization required careful manipulation of source positions and character ranges.</p><h3>Using CleanDeadCode</h3><p>CleanDeadCode is designed to fit into your workflow seamlessly, whether you prefer manual cleaning or automatic processing.</p><h3>Manual Cleaning</h3><p>You can invoke the extension through:</p><ul><li>Right-click context menu</li><li>Command palette (Ctrl+Shift+P or Cmd+Shift+P)</li><li>Keyboard shortcuts:</li><li>Ctrl+Alt+U (Win/Linux) or Cmd+Alt+U (Mac) for unused imports</li><li>Ctrl+Alt+V (Win/Linux) or Cmd+Alt+V (Mac) for unused variables</li><li>Ctrl+Alt+C (Win/Linux) or Cmd+Alt+C (Mac) for both operations</li></ul><h3>Automatic Cleaning</h3><p>For a more hands-off approach, enable automatic cleaning on file save:</p><ol><li>Open VS Code settings</li><li>Search for “CleanDeadCode”</li><li>Enable auto options:</li></ol><ul><li>cleanCode.autoRemoveUnusedImports</li><li>cleanCode.autoHandleUnusedVariables</li></ul><h3>Customization Options</h3><p>The extension provides several configuration options:</p><ul><li><strong>Choose how to handle unused variables</strong>: Comment them out, add an underscore prefix, or ignore them</li><li><strong>Control trailing parameter removal</strong>: Choose whether to remove unused parameters at the end of functions</li><li><strong>Configure auto-save behavior</strong>: Enable automatic cleaning for imports, variables, or both</li></ul><h3>Benefits to Your Development Workflow</h3><p>Integrating CleanDeadCode into your workflow provides several advantages:</p><ol><li><strong>Improved Code Readability</strong>: Less clutter means easier-to-read code</li><li><strong>Reduced Cognitive Load</strong>: No need to mentally filter out unused elements</li><li><strong>Better Performance</strong>: Some unused imports can impact bundle size and load times</li><li><strong>Consistent Code Style</strong>: Standardizes how unused parameters are marked</li><li><strong>Time Savings</strong>: Automates what would otherwise be manual cleanup work</li></ol><p>Dead code is an inevitable byproduct of software development, but it doesn’t have to linger in your projects. CleanDeadCode offers a targeted solution that respects your code organization while eliminating unnecessary elements.</p><p>Unlike broader linting tools, CleanDeadCode focuses solely on unused code removal with contextual awareness that balances automation with preservation of intent. Its specialized approach complements existing tools without disrupting your workflow.</p><p>By integrating CleanDeadCode into your development process, you can maintain cleaner, more readable code without the tedious manual effort typically required for housekeeping tasks.</p><p><em>This extension is released under the MIT License and is free for personal and commercial use.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7229fdc78491" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Python for JavaScript Developers: A Comprehensive Guide]]></title>
            <link>https://medium.com/@m.rastegar991/python-for-javascript-developers-a-comprehensive-guide-9ed5f517e2ae?source=rss-23d49b6d6b51------2</link>
            <guid isPermaLink="false">https://medium.com/p/9ed5f517e2ae</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[M Rastegar]]></dc:creator>
            <pubDate>Fri, 21 Mar 2025 03:24:17 GMT</pubDate>
            <atom:updated>2025-03-21T03:54:04.148Z</atom:updated>
            <content:encoded><![CDATA[<p>This guide is to help JavaScript programmers quickly learn Python. It translates JavaScript concepts into their Python equivalents so you can learn more easily. It mainly focuses on the 80% of commonly used Python features, so you can learn quickly and apply it practically.</p><p><a href="https://gist.github.com/MostafaRastegar/f33a1d6229a1567962401ca3ca37da80"><strong>Free link</strong></a></p><p>I originally made this for myself. I thought it turned out pretty cool, so I figured you might find it useful too. If there’s anything wrong with it, please let me know. I’m also just starting to learn Python myself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IvJV2hp5xTETXrL8ax31HA.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2c745596f3195d0a837475ebbce6fe8c/href">https://medium.com/media/2c745596f3195d0a837475ebbce6fe8c/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9ed5f517e2ae" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[You Don’t Know JS Yet: Scope & Closures- Chapter 7: Using Closures]]></title>
            <link>https://medium.com/@m.rastegar991/you-dont-know-js-yet-scope-closures-chapter-7-using-closures-9a497671436b?source=rss-23d49b6d6b51------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a497671436b</guid>
            <category><![CDATA[node-js-development]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[you-dont-know-js]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[M Rastegar]]></dc:creator>
            <pubDate>Tue, 11 Mar 2025 03:12:32 GMT</pubDate>
            <atom:updated>2025-03-11T03:12:32.907Z</atom:updated>
            <content:encoded><![CDATA[<p>Closures are one of JavaScript’s most powerful features, enabling functions to maintain access to variables from their lexical scope long after the outer function has finished execution. Building on the fundamentals of lexical scope discussed in previous chapters, closures empower developers to encapsulate and preserve data, improve efficiency, and write cleaner, modular code. This chapter not only defines what closures are but also demonstrates how they work in practice, discusses common pitfalls, explains their impact on garbage collection, and even presents alternative ways to conceptualize them.</p><p>Reference:<br><a href="https://github.com/getify/You-Dont-Know-JS/blob/2nd-ed/scope-closures/ch7.md">https://github.com/getify/You-Dont-Know-JS/blob/2nd-ed/scope-closures/ch7.md</a></p><h3>Observing Closure in Action</h3><p>At its core, closure is an observable behavior in functions. It occurs when a function, defined within one scope, is invoked in another part of the program yet still “remembers” the environment in which it was created. Consider the following example:</p><pre>// outer/global scope: RED(1)<br><br>function lookupStudent(studentID) {<br>    // function scope: BLUE(2)<br>    var students = [<br>        { id: 14, name: &quot;Kyle&quot; },<br>        { id: 73, name: &quot;Suzy&quot; },<br>        { id: 112, name: &quot;Frank&quot; },<br>        { id: 6, name: &quot;Sarah&quot; }<br>    ];<br>    return function greetStudent(greeting){<br>        // function scope: GREEN(3)<br>        var student = students.find(<br>            student =&gt; student.id == studentID<br>        );<br>        return `${ greeting }, ${ student.name }!`;<br>    };<br>}<br>var chosenStudents = [<br>    lookupStudent(6),<br>    lookupStudent(112)<br>];<br>// accessing the function&#39;s name:<br>chosenStudents[0].name;<br>// greetStudent<br>chosenStudents[0](&quot;Hello&quot;);<br>// Hello, Sarah!<br>chosenStudents[1](&quot;Howdy&quot;);<br>// Howdy, Frank!</pre><h3>Key Observations:</h3><ul><li><strong>Nested Functions:</strong> The lookupStudent function returns an inner function greetStudent that makes reference to variables (students and studentID) from its outer scope.</li><li><strong>Preserved Scope:</strong> Even after lookupStudent finishes executing, greetStudent maintains a “live link” to the students array and the studentID value, demonstrating observable closure.</li><li><strong>Arrow Function Nuance:</strong> Note that the arrow function inside greetStudent creates its own scope (illustrated as ORANGE(4) in the original text), yet still closes over studentID. This detail is critical—even tiny arrow functions participate in the closure mechanism.</li></ul><h3>The Canonical Closure Example: The Adder Function</h3><p>A classic example to understand closures is through an adder function:</p><pre>function adder(num1) {<br>    return function addTo(num2){<br>        return num1 + num2;<br>    };<br>}<br><br>var add10To = adder(10);<br>var add42To = adder(42);<br>add10To(15);    // 25<br>add42To(9);     // 51</pre><h3>Explanation:</h3><ul><li><strong>Function Instances:</strong> Each call to adder creates a new instance of the inner function addTo that closes over its own num1 variable.</li><li><strong>Instance-Specific Closures:</strong> Even though there is one inner function definition, every invocation produces a distinct closure with its own copy of num1.</li><li><strong>Runtime Characteristic:</strong> Closure is observed at runtime as each returned function instance continues to access the variable num1, enabling the proper addition operation.</li></ul><h3>Live Links Versus Snapshots</h3><p>Closures maintain a live link to variables rather than capturing a one-time snapshot. This means the closed-over variable can be updated, and the changes will be reflected in subsequent function invocations. Consider these examples:</p><h3>Incrementing a Counter:</h3><pre>function makeCounter() {<br>    var count = 0;<br>    return function getCurrent() {<br>        count = count + 1;<br>        return count;<br>    };<br>}<br>var hits = makeCounter();<br>hits();     // 1<br>hits();     // 2<br>hits();     // 3</pre><h3>Variable Update Pitfall:</h3><pre>var studentName = &quot;Frank&quot;;<br>var greeting = function hello() {<br>    // Closure over `studentName`, not &quot;Frank&quot;<br>    console.log(`Hello, ${ studentName }!`);<br>}<br>studentName = &quot;Suzy&quot;;<br>greeting();<br>// Hello, Suzy!</pre><h3>Loop Closure Issue:</h3><p>Using var in loops can lead to unexpected behavior:</p><pre>var keeps = [];<br>for (var i = 0; i &lt; 3; i++) {<br>    keeps[i] = function keepI(){<br>        // Closure over shared `i`<br>        return i;<br>    };<br>}<br>keeps[0]();   // 3<br>keeps[1]();   // 3<br>keeps[2]();   // 3</pre><h4>How to Fix It:</h4><ul><li><strong>Using a New Variable:</strong></li></ul><pre>var keeps = [];<br><br>for (var i = 0; i &lt; 3; i++) {<br>    let j = i; // New variable each iteration<br><br>    keeps[i] = function keepEachJ(){<br>        // Closure over `j`, not `i`<br>        return j;<br>    };<br>}<br>keeps[0]();   // 0<br>keeps[1]();   // 1<br>keeps[2]();   // 2</pre><ul><li><strong>Using </strong><strong>let in the Loop:</strong></li></ul><pre>var keeps = [];<br><br>for (let i = 0; i &lt; 3; i++) {<br>    keeps[i] = function keepEachI(){<br>        return i;<br>    };<br>}<br>keeps[0]();   // 0<br>keeps[1]();   // 1<br>keeps[2]();   // 2</pre><h3>Takeaway:</h3><ul><li><strong>Live Variable Links:</strong> Closures keep a reference to the actual variable, meaning its latest value is always used.</li><li><strong>Scope Management:</strong> To capture the intended value per iteration, it is crucial to create a new variable (using let or a separate binding) in each loop iteration.</li></ul><h3>Common Uses of Closures</h3><p>Closures are frequently encountered in JavaScript, particularly with asynchronous operations such as Ajax callbacks and event handling.</p><h3>Ajax Example:</h3><pre>function lookupStudentRecord(studentID) {<br>    ajax(<br>        `https://some.api/student/${ studentID }`,<br>        function onRecord(record) {<br>            console.log(`${ record.name } (${ studentID })`);<br>        }<br>    );<br>}<br>lookupStudentRecord(114);<br>// Output: Frank (114)</pre><p><strong>Observation:</strong> The onRecord callback closes over the studentID variable, ensuring that the correct ID is available when the asynchronous call completes.</p><h3>Event Handler Example:</h3><pre>function listenForClicks(btn, label) {<br>    btn.addEventListener(&quot;click&quot;, function onClick(){<br>        console.log(`The ${ label } button was clicked!`);<br>    });<br>}<br>var submitBtn = document.getElementById(&quot;submit-btn&quot;);<br>listenForClicks(submitBtn, &quot;Checkout&quot;);</pre><p><strong>Observation:</strong> The label variable is closed over by the event handler, ensuring it is accessible when the button is clicked.</p><h3>Closure Lifecycle and Garbage Collection</h3><p>Closures persist as long as there is at least one reference to the function instance. This persistence means that even after an outer function completes, the closed-over variables remain in memory.</p><h3>Example with Event Handlers:</h3><pre>function manageBtnClickEvents(btn) {<br>    var clickHandlers = [];<br>    return function listener(cb){<br>        if (cb) {<br>            let clickHandler = function onClick(evt){<br>                console.log(&quot;clicked!&quot;);<br>                cb(evt);<br>            };<br>            clickHandlers.push(clickHandler);<br>            btn.addEventListener(&quot;click&quot;, clickHandler);<br>        }<br>        else {<br>            // Unsubscribe all click handlers<br>            for (let handler of clickHandlers) {<br>                btn.removeEventListener(&quot;click&quot;, handler);<br>            }<br>            clickHandlers = [];<br>        }<br>    };<br>}<br>var onSubmit = manageBtnClickEvents(mySubmitBtn);<br>onSubmit(function checkout(evt){<br>    // handle checkout<br>});<br>onSubmit(function trackAction(evt){<br>    // log action to analytics<br>});<br>// Later, unsubscribe all handlers:<br>onSubmit();</pre><h3>Key Points:</h3><ul><li><strong>Memory Retention:</strong> Even if multiple functions close over the same variable, the variable remains in memory as long as any one function still references it.</li><li><strong>Garbage Collection:</strong> Once the final reference to a closure is removed, the closed-over variables become eligible for garbage collection.</li></ul><h3>Per Variable Versus Per Scope</h3><p>Closures may be thought to preserve either the specific variables that are referenced (per variable) or the entire scope in which they were defined (per scope). Modern JavaScript engines often optimize closures by stripping out unreferenced variables. However, certain language features like eval(..) can force the entire scope to be retained:</p><pre>function storeStudentInfo(id, name, grade) {<br>    return function getInfo(whichValue){<br>        // Using `eval(..)` forces access to the entire scope<br>        var val = eval(whichValue);<br>        return val;<br>    };<br>}<br><br>var info = storeStudentInfo(73, &quot;Suzy&quot;, 87);<br>info(&quot;name&quot;);<br>// Suzy<br>info(&quot;grade&quot;);<br>// 87</pre><h3>Implications:</h3><ul><li><strong>Optimization Caution:</strong> While modern engines optimize closures to hold only what is necessary, be mindful that older environments may not, which could lead to unintended memory retention.</li></ul><h3>An Alternative Perspective on Closure</h3><p>Beyond the standard view — where closures are seen as functions “remembering” their lexical scope — an alternative model considers that functions remain in place in their original scope. In this view, only a reference to the function is passed around. The function is never physically moved; it simply retains access to its original scope environment. This perspective can be summarized as:</p><ul><li><strong>Observational Model:</strong> Closure is observed when a function accesses outer variables in an unexpected scope.</li><li><strong>Implementational Model:</strong> The function instance, along with its scope chain, remains in place while references to it are passed to other parts of the program.</li></ul><p>Both models yield the same observable behavior but may help deepen one’s understanding of how closures are managed internally.</p><h3>Practical Benefits and Use Cases</h3><p>Closures are not just an academic concept — they offer tangible benefits:</p><ul><li><strong>Efficiency:</strong> They allow functions to “remember” precomputed values or configuration data, reducing repetitive computation.</li><li><strong>Encapsulation:</strong> By limiting variable exposure, closures help keep code organized and prevent unwanted side effects.</li><li><strong>Partial Application &amp; Currying:</strong> Techniques from functional programming use closures to fix some function parameters in advance, creating cleaner and more reusable code.</li></ul><h3>Refactored Button Handler Example:</h3><p>Without closure, an event handler might repeatedly query DOM attributes. With closure:</p><pre>var APIendpoints = {<br>    studentIDs: &quot;https://some.api/register-students&quot;,<br>    // ..<br>};<br><br>var data = {<br>    studentIDs: [ 14, 73, 112, 6 ],<br>    // ..<br>};<br>function setupButtonHandler(btn) {<br>    var recordKind = btn.dataset.kind;<br>    var requestURL = APIendpoints[recordKind];<br>    var requestData = data[recordKind];<br>    btn.addEventListener(&quot;click&quot;, function makeRequest(evt){<br>        ajax(requestURL, requestData);<br>    });<br>}</pre><ul><li><strong>Advantage:</strong> The recordKind, requestURL, and requestData values are captured once during setup. The event handler then accesses these stored values on each click, resulting in cleaner and more performant code.</li></ul><h3>At The End</h3><p>Closures are fundamental to JavaScript — they enable functions to preserve and access their original scope regardless of where they are invoked. Whether you are building counters, managing asynchronous callbacks, or implementing complex patterns like partial application and currying, understanding closures is essential. This chapter has shown that closures are more than just a quirk of the language; they are a deliberate design choice that, when used wisely, can lead to cleaner, more efficient, and more maintainable code.</p><p>By grasping both the observational and alternative perspectives on closure, developers can better appreciate the balance between language design and practical application. Ultimately, mastering closures means gaining the ability to write more robust JavaScript that leverages scope effectively while controlling memory usage and preserving code clarity.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a497671436b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[You Don’t Know JS Yet: Scope & Closures- Chapter 6: Limiting Scope Exposure]]></title>
            <link>https://medium.com/@m.rastegar991/you-dont-know-js-yet-scope-closures-chapter-6-limiting-scope-exposure-277e88d54a61?source=rss-23d49b6d6b51------2</link>
            <guid isPermaLink="false">https://medium.com/p/277e88d54a61</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[you-dont-know-js]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[M Rastegar]]></dc:creator>
            <pubDate>Sun, 09 Mar 2025 02:52:13 GMT</pubDate>
            <atom:updated>2025-03-09T02:52:13.336Z</atom:updated>
            <content:encoded><![CDATA[<p>Below is a comprehensive summary of Chapter 6, “Limiting Scope Exposure,” which focuses on the disciplined organization of variables and functions using JavaScript’s scoping mechanisms. The chapter emphasizes the importance of exposing only what is necessary — a concept derived from the Principle of Least Privilege — and applies it at a finer granularity, often called the Principle of Least Exposure (POLE).</p><p>Reference: <a href="https://github.com/getify/You-Dont-Know-JS/blob/2nd-ed/scope-closures/ch6.md">https://github.com/getify/You-Dont-Know-JS/blob/2nd-ed/scope-closures/ch6.md</a></p><p>In JavaScript programming, organizing code to minimize unintended interactions is key to writing robust, maintainable software. This chapter builds on earlier discussions of how scopes and variables work by introducing patterns and techniques that restrict the exposure of internal details. By following POLE, developers can avoid naming collisions, unexpected behaviors, and unintended dependencies. In short, the chapter argues that variables should be declared in the smallest possible scope needed to support the desired functionality. The techniques discussed range from using block scoping via let/const to leveraging function scopes and Immediately Invoked Function Expressions (IIFEs) for data hiding.</p><h3>Principle of Least Exposure (POLE)</h3><p>POLE is an extension of the Principle of Least Privilege (POLP), which is traditionally used to secure system components by limiting their access to the minimum necessary. When applied to variable scope, POLE suggests that each variable should be accessible only within the minimal block or function in which it is required. The chapter identifies three primary hazards of over-exposing variables:</p><ul><li><strong>Naming Collisions:</strong> Sharing the same identifier across different parts of a program can lead to bugs. For example, if a loop index (i) is used globally, one loop running concurrently may inadvertently interfere with another.</li><li><strong>Unexpected Behavior:</strong> Exposing private details allows other parts of the program — or even malicious actors — to change them. For instance, modifying a supposedly private array could cause functions expecting a homogeneous list of numbers to malfunction.</li><li><strong>Unintended Dependency:</strong> When internal variables are exposed, external code may start relying on them. This tight coupling can complicate future refactoring efforts.</li></ul><p>The key takeaway is to default to a minimal exposure policy, defining variables in the deepest, most nested scope possible.</p><h3>Using Function Scopes for Data Hiding</h3><p>JavaScript’s function scope is a natural mechanism to encapsulate variables that do not need to be accessible globally. Consider the following simple example:</p><pre>function diff(x, y) {<br>    if (x &gt; y) {<br>        let tmp = x;<br>        x = y;<br>        y = tmp;<br>    }<br>    return y - x;<br>}<br>diff(3, 7);      // 4<br>diff(7, 5);      // 2</pre><p>In the diff(..) function, the temporary variable tmp is declared with let inside the if block, ensuring it remains local and does not pollute the function’s outer scope.</p><p>The chapter then moves on to a more complex example involving a recursive factorial function with caching. Initially, a global cache is used:</p><pre>var cache = {};<br><br>function factorial(x) {<br>    if (x &lt; 2) return 1;<br>    if (!(x in cache)) {<br>        cache[x] = x * factorial(x - 1);<br>    }<br>    return cache[x];<br>}<br><br>factorial(6);<br>// 720<br><br>cache;<br>// {<br>//     &quot;2&quot;: 2,<br>//     &quot;3&quot;: 6,<br>//     &quot;4&quot;: 24,<br>//     &quot;5&quot;: 120,<br>//     &quot;6&quot;: 720<br>// }<br><br>factorial(7);<br>// 5040</pre><p>Here, the cache is exposed globally—even though it is only an implementation detail of factorial(..). To hide this detail, the chapter suggests wrapping the logic in a separate function scope:</p><pre>// outer/global scope<br><br>function hideTheCache() {<br>    // &quot;middle scope&quot;, where we hide `cache`<br>    var cache = {};<br><br>    return factorial;<br><br>    // **********************<br><br>    function factorial(x) {<br>        // inner scope<br>        if (x &lt; 2) return 1;<br>        if (!(x in cache)) {<br>            cache[x] = x * factorial(x - 1);<br>        }<br>        return cache[x];<br>    }<br>}<br><br>var factorial = hideTheCache();<br><br>factorial(6);<br>// 720<br><br>factorial(7);<br>// 5040</pre><p>This pattern moves cache to an inner scope that persists between calls to factorial(..) without exposing it to the outer scope.</p><h3>Immediately Invoked Function Expressions (IIFE)</h3><p>To streamline the process of creating a private scope without having to define an extra named function, the chapter introduces the Immediately Invoked Function Expression (IIFE) pattern. An IIFE is defined and immediately executed, allowing you to encapsulate variables and functions in a temporary scope:</p><pre>var factorial = (function hideTheCache() {<br>    var cache = {};<br>   function factorial(x) {<br>        if (x &lt; 2) return 1;<br>        if (!(x in cache)) {<br>            cache[x] = x * factorial(x - 1);<br>        }<br>        return cache[x];<br>    }<br>    return factorial;<br>})();<br><br>factorial(6);<br>// 720<br>factorial(7);<br>// 5040</pre><p>Note that the function expression is wrapped in parentheses and immediately invoked with (). The function’s name (hideTheCache) is local to its own scope, which means you can reuse the same name elsewhere without collision. The chapter also provides an example of a standalone IIFE used solely to create an isolated scope:</p><pre>(function(){<br>    // inner hidden scope<br>})();<br>// more outer scope</pre><p>IIFEs are particularly useful when you need a temporary scope to hide implementation details while still exposing a public interface.</p><h3>Leveraging Block Scoping with let/const</h3><p>With the introduction of ES6, JavaScript gained block-scoped declarations through let and const. A block—defined by { ... }—can act as a scope if it contains block-scoped declarations. Consider this example:</p><pre>{<br>    // not necessarily a scope (yet)<br>    // ..<br>    <br>    // now we know the block needs to be a scope<br>    let thisIsNowAScope = true;<br>    for (let i = 0; i &lt; 5; i++) {<br>        // this is also a scope, activated each iteration<br>        if (i % 2 == 0) {<br>            // this is just a block, not a scope<br>            console.log(i);<br>        }<br>    }<br>}<br>// 0 2 4</pre><p>Even when a block does not initially create a scope, the inclusion of a let or const declaration forces it to become one. The chapter further illustrates the value of explicit block scopes with nested blocks in conditional statements:</p><pre>if (somethingHappened) {<br>    // this is a block, but not a scope{<br>        // this is both a block and an explicit scope<br>        let msg = somethingHappened.message();<br>        notifyOthers(msg);<br>    }<br>    // ..<br>    recoverFromSomething();<br>}</pre><p>A more detailed example is provided in the getNextMonthStart function, where an inner block limits the exposure of the curMonth variable:</p><pre>function getNextMonthStart(dateStr) {<br>    var nextMonth, year;<br><br>    {<br>        let curMonth;<br>        [ , year, curMonth ] = dateStr.match(<br>                /(\d{4})-(\d{2})-\d{2}/<br>            ) || [];<br>        nextMonth = (Number(curMonth) % 12) + 1;<br>    }<br><br>    if (nextMonth == 1) {<br>        year++;<br>    }<br><br>    return `${ year }-${<br>            String(nextMonth).padStart(2,&quot;0&quot;)<br>        }-01`;<br>}<br>getNextMonthStart(&quot;2019-12-25&quot;);   // 2020-01-01</pre><p>Similarly, when sorting names by length, the code uses an explicit block scope to restrict the lifetime of the sortedNames variable to where it is needed:</p><pre>function sortNamesByLength(names) {<br>    var buckets = [];<br><br>    for (let firstName of names) {<br>        if (buckets[firstName.length] == null) {<br>            buckets[firstName.length] = [];<br>        }<br>        buckets[firstName.length].push(firstName);<br>    }<br><br>    // a block to narrow the scope<br>    {<br>        let sortedNames = [];<br><br>        for (let bucket of buckets) {<br>            if (bucket) {<br>                // sort each bucket alphanumerically<br>                bucket.sort();<br><br>                // append the sorted names to our<br>                // running list<br>                sortedNames = [<br>                    ...sortedNames,<br>                    ...bucket<br>                ];<br>            }<br>        }<br><br>        return sortedNames;<br>    }<br>}<br><br>sortNamesByLength([<br>    &quot;Sally&quot;,<br>    &quot;Suzy&quot;,<br>    &quot;Frank&quot;,<br>    &quot;John&quot;,<br>    &quot;Jennifer&quot;,<br>    &quot;Scott&quot;<br>]);<br>// [ &quot;John&quot;, &quot;Suzy&quot;, &quot;Frank&quot;, &quot;Sally&quot;,<br>//   &quot;Scott&quot;, &quot;Jennifer&quot; ]</pre><h3>Considerations When Mixing var and let</h3><p>The chapter advocates for using var only in cases where a variable must be function-scoped, while reserving let for block-scoped variables. For example, in a for-loop the loop iterator should typically be declared with let:</p><pre>for (let i = 0; i &lt; 5; i++) {<br>    // do something<br>}</pre><p>Contrast this with an older pattern that uses var, which inadvertently creates a function-scoped variable that may be accessed outside the loop:</p><pre>for (var i = 0; i &lt; 5; i++) {<br>    if (checkValue(i)) {<br>        break;<br>    }<br>}<br>if (i &lt; 5) {<br>    console.log(&quot;The loop stopped early!&quot;);<br>}</pre><p>To adhere to POLE, the chapter recommends separating concerns by keeping the loop iterator i block-scoped with let and using an outer variable (declared with var) to capture the final value if needed:</p><pre>var lastI;<br>for (let i = 0; i &lt; 5; i++) {<br>    lastI = i;<br>    if (checkValue(i)) {<br>        break;<br>    }<br>}<br>if (lastI &lt; 5) {<br>    console.log(&quot;The loop stopped early!&quot;);<br>}</pre><h3>Pitfalls of Function Declarations in Blocks (FiB)</h3><p>A particularly tricky area is the use of function declarations directly inside blocks — a practice known as FiB. Although the specification states that functions declared in blocks should be block-scoped, legacy browser behaviors (especially in v8-based environments) can lead to unexpected results. For example:</p><pre>if (false) {<br>    function ask() {<br>        console.log(&quot;Does this run?&quot;);<br>    }<br>}<br>ask();</pre><p>Depending on the environment, this code might throw a ReferenceError (if ask is block-scoped) or result in ask being defined but undefined (if it’s hoisted incorrectly). Similarly, conditionally defining functions as in:</p><pre>if (typeof Array.isArray != &quot;undefined&quot;) {<br>    function isArray(a) {<br>        return Array.isArray(a);<br>    }<br>}<br>else {<br>    function isArray(a) {<br>        return Object.prototype.toString.call(a) == &quot;[object Array]&quot;;<br>    }<br>}</pre><p>can create confusion during debugging, especially when multiple implementations of the same function exist. The chapter suggests avoiding direct function declarations in blocks altogether. Instead, it offers two alternatives:</p><ol><li>Define a single function that internally chooses the implementation:</li></ol><pre>function isArray(a) {<br>    if (typeof Array.isArray != &quot;undefined&quot;) { <br>        return Array.isArray(a); <br>    } else { <br>        return Object.prototype.toString.call(a) == &quot;[object Array]&quot;;<br>    }<br> }</pre><p>Use function expressions for conditional assignment:</p><pre>var isArray = function isArray(a) {<br>  return Array.isArray(a);<br>};<br>if (typeof Array.isArray == &quot;undefined&quot;) {<br>  isArray = function isArray(a) {<br>    return Object.prototype.toString.call(a) == &quot;[object Array]&quot;;<br>  };<br>}</pre><p>These approaches prevent the legacy pitfalls of FiB while keeping the code’s intent clear.</p><h3>At The End</h3><p>The chapter reinforces that careful scoping is essential for writing secure, maintainable JavaScript. By applying the Principle of Least Exposure, developers can limit the risk of naming collisions, unexpected behaviors, and unintended dependencies. Using function scopes (and IIFEs) allows critical internal details, like caching mechanisms, to remain hidden. With ES6’s block-scoped declarations (let and const), creating explicit inner scopes becomes even easier, allowing variables to live only as long as they’re needed.</p><p>In summary, whether you’re organizing simple functions like diff(..) or more complex operations such as memoized factorial calculations, the goal is the same: declare variables in the smallest scope that meets the program’s needs. Adopting these practices not only enhances code clarity but also prepares your codebase for easier maintenance and safer refactoring in the future. The insights from this chapter pave the way for a deeper exploration of closures in the following chapter, further strengthening your understanding of JavaScript’s scoping mechanisms.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=277e88d54a61" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[You Don’t Know JS Yet: Scope & Closures — Chapter 5]]></title>
            <link>https://medium.com/@m.rastegar991/you-dont-know-js-yet-scope-closures-chapter-5-e631dc5f9873?source=rss-23d49b6d6b51------2</link>
            <guid isPermaLink="false">https://medium.com/p/e631dc5f9873</guid>
            <category><![CDATA[you-dont-know-js]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[reactjs]]></category>
            <dc:creator><![CDATA[M Rastegar]]></dc:creator>
            <pubDate>Sat, 08 Mar 2025 02:24:19 GMT</pubDate>
            <atom:updated>2025-03-08T02:24:19.152Z</atom:updated>
            <content:encoded><![CDATA[<h3>You Don’t Know JS Yet: Scope &amp; Closures — Chapter 5</h3><h3>The (Not So) Secret Lifecycle of Variables</h3><p>Understanding how and when variables become available is critical for writing predictable and bug‐free JavaScript. This chapter delves into the lifecycle of variables — from the moment their identifiers are registered to when they are fully initialized and usable. It examines the nuances of hoisting, the differences between function and variable declarations, the subtleties of re-declaration with different keywords (var, let, and const), and the concept of the Temporal Dead Zone (TDZ). Throughout, code examples clarify how these behaviors manifest in practice.<br>Reference:<br><a href="https://github.com/getify/You-Dont-Know-JS/blob/2nd-ed/scope-closures/ch5.md">https://github.com/getify/You-Dont-Know-JS/blob/2nd-ed/scope-closures/ch5.md</a></p><h3>When Can I Use a Variable?</h3><p>At first glance, it might seem that a variable is usable only after its declaration. However, JavaScript’s handling of variable declarations is more nuanced. Consider this example:</p><pre>greeting();<br>// Hello!<br>function greeting() {<br>    console.log(&quot;Hello!&quot;);<br>}</pre><p>Even though the greeting() call appears before the function declaration, the code works because JavaScript registers function identifiers at compile time. This process—often called <strong>hoisting</strong>—makes the function available throughout its enclosing scope by auto-initializing the identifier to reference the function. In essence, the engine “sees” the function declaration when the scope is created.</p><p>In contrast, if the same function were assigned via a function expression with var, the behavior would change:</p><pre>greeting();<br>// TypeError<br>var greeting = function greeting() {<br>    console.log(&quot;Hello!&quot;);<br>};</pre><p>Here, the identifier greeting is hoisted as a variable, but it’s automatically initialized to undefined. Therefore, attempting to invoke it before the assignment leads to a TypeError (e.g., &quot;&#39;greeting&#39; is not a function&quot;) rather than a ReferenceError—since the identifier does exist, it just doesn’t hold the function reference yet.</p><h3>Function Hoisting vs. Variable Hoisting</h3><p>The chapter makes an important distinction:</p><ul><li><strong>Function declarations</strong> are hoisted <em>and</em> auto-initialized to their function reference.</li><li><strong>Variable declarations</strong> using var are hoisted but initialized to undefined until the assignment is executed.</li></ul><p>For example:</p><pre>greeting = &quot;Hello!&quot;;<br>console.log(greeting);<br>// Hello!<br>var greeting = &quot;Howdy!&quot;;</pre><p>Even though the assignment appears before the var declaration, the declaration itself is hoisted. The variable is available from the start of its scope with an initial value of undefined. Only after the assignment does its value change to &quot;Howdy!&quot;.</p><h3>Hoisting as a Compile-Time Process</h3><p>Rather than literally “lifting” code around, hoisting is better understood as a compile-time process. During this phase, the JavaScript engine registers all identifiers in a scope — even if their declarations appear later in the code. The popular metaphor imagines all variable and function declarations being moved to the top of the scope, as if the code were re-written like this:</p><pre>var greeting;           // declaration is hoisted<br>greeting = &quot;Hello!&quot;;    // original assignment remains in place<br>console.log(greeting);  // outputs &quot;Hello!&quot;<br>greeting = &quot;Howdy!&quot;;    // subsequent assignment</pre><p>For functions, the engine not only hoists the declaration but also assigns the entire function value:</p><pre>function greeting() {<br>    console.log(`Hello ${ studentName }!`);<br>}<br>var studentName;<br>studentName = &quot;Suzy&quot;;<br>greeting();<br>// Outputs: &quot;Hello Suzy!&quot;</pre><p>This metaphor is useful even though the engine does not literally re-arrange the code. It emphasizes that variable registration happens before runtime execution.</p><h3>Re-declaration Nuances</h3><p>A common source of confusion is what happens when a variable is declared more than once in the same scope. With var, re-declaration is allowed and effectively becomes a no-op:</p><pre>var studentName = &quot;Frank&quot;;<br>console.log(studentName);<br>// Frank<br>var studentName;<br>console.log(studentName);<br>// Frank</pre><p>Even though the identifier is declared a second time, it does not reset or clear the existing value. However, an explicit initialization (for example, setting it to undefined) does change its value:</p><pre>var studentName = &quot;Frank&quot;;<br>console.log(studentName);<br>// Frank<br>var studentName = undefined;<br>console.log(studentName);<br>// undefined</pre><p>With block-scoped declarations (let and const), the situation is different. Re-declaring a variable with the same name in the same scope results in a SyntaxError:</p><pre>let studentName = &quot;Frank&quot;;<br>console.log(studentName);<br>let studentName = &quot;Suzy&quot;; // SyntaxError: studentName has already been declared</pre><p>Even mixing var and let (or vice versa) in the same scope produces an error, reinforcing best practices that discourage “sloppy re-declaration.”</p><h3>Constants and Their Special Behavior</h3><p>The const keyword further tightens variable behavior:</p><ul><li>A const declaration <strong>requires an initializer</strong>. Omitting the assignment causes a SyntaxError:</li></ul><pre>const empty;   // SyntaxError</pre><ul><li>Once a constant is assigned, it <strong>cannot be re-assigned</strong>. Attempting to do so produces a TypeError (an error that occurs during execution rather than during parsing):</li></ul><pre>const studentName = &quot;Frank&quot;;<br>console.log(studentName); // Frank  studentName = &quot;Suzy&quot;;   // TypeError</pre><p>The technical reason for disallowing re-declaration with const is tied to its requirement for immediate initialization, which also makes any subsequent declaration effectively a forbidden re-assignment.</p><h3>Loop Constructs and Variable Scoping</h3><p>Loops introduce further nuance in variable declaration. Consider a while loop using let:</p><pre>var keepGoing = true;<br>while (keepGoing) {<br>    let value = Math.random();<br>    if (value &gt; 0.5) {<br>        keepGoing = false;<br>    }<br>}</pre><p>Each iteration of the loop creates a new block scope for value, so the variable is declared only once per iteration. In contrast, using var in the same loop makes value a function- or global-scoped variable:</p><pre>var keepGoing = true;<br>while (keepGoing) {<br>    var value = Math.random();<br>    if (value &gt; 0.5) {<br>        keepGoing = false;<br>    }<br>}</pre><p>In this case, there is only one value throughout the entire loop. Similar rules apply in for loops. For example:</p><pre>for (let i = 0; i &lt; 3; i++) {<br>    let value = i * 10;<br>    console.log(`${i}: ${value}`);<br>}<br>// Outputs:<br>// 0: 0<br>// 1: 10<br>// 2: 20</pre><p>Here, each iteration has its own instance of i and value. For for...in and for...of loops, declaring the loop variable with let or const similarly creates a fresh binding on every iteration. However, note that using const with a classic for loop is problematic because the loop’s counter requires re-assignment:</p><pre>for (const i = 0; i &lt; 3; i++) {<br>    // This will fail on the second iteration because i cannot be re-assigned.<br>}</pre><p>Conceptually, you can “expand” the loop to see that a constant binding would conflict with the need to update the loop counter. If no re-assignment is required, then const may be used in other loop forms (like for...in and for...of).</p><h3>Uninitialized Variables and the Temporal Dead Zone (TDZ)</h3><p>One of the key differences between var and the newer declarations (let and const) is how initialization is handled. With var, variables are hoisted and automatically initialized to undefined, which means they can be used (albeit with an undefined value) throughout the entire scope. With let and const, however, the variable is hoisted but <strong>not</strong> initialized until the execution reaches the declaration. This period is known as the <strong>Temporal Dead Zone (TDZ)</strong>.</p><p>For example:</p><pre>console.log(studentName);<br>// ReferenceError: Cannot access &#39;studentName&#39; before initialization<br>let studentName = &quot;Suzy&quot;;</pre><p>Even attempting to assign a value before the actual declaration produces the same error:</p><pre>studentName = &quot;Suzy&quot;;   // ReferenceError: Cannot access &#39;studentName&#39; before initialization<br>console.log(studentName);<br>let studentName;</pre><p>The TDZ is the window of time from when a block is entered until the variable’s declaration is executed. During this period, any attempt to access or assign to the variable will result in a ReferenceError. This behavior reinforces why it is best practice to place let and const declarations at the top of their block scope—minimizing or eliminating the TDZ.</p><p>An important demonstration of the TDZ comes from variable shadowing. Consider the following:</p><pre>var studentName = &quot;Kyle&quot;;<br>{<br>    console.log(studentName); // ReferenceError because the inner studentName is in TDZ<br>    let studentName = &quot;Suzy&quot;;<br>    console.log(studentName);<br>    // Outputs: &quot;Suzy&quot;<br>}</pre><p>Even though an outer studentName exists, the inner declaration is hoisted to the top of its block but remains uninitialized until its declaration is reached. The initial console.log attempts to access the uninitialized inner variable, causing a TDZ error.</p><h3>At The End</h3><p>This chapter carefully unpacks the intricate lifecycle of variables in JavaScript. Key takeaways include:</p><ul><li><strong>Hoisting</strong> is a compile-time process whereby identifiers are registered at the start of their scope. Function declarations are auto-initialized with their function value, while var variables are initialized to undefined.</li><li><strong>Function vs. Variable Hoisting:</strong> The ability to call a function before its declaration is due to function hoisting. Function expressions, on the other hand, do not receive this treatment, leading to potential runtime errors.</li><li><strong>Re-declaration:</strong> Re-declaring a variable with var has no effect, whereas doing so with let or const results in a SyntaxError. Constants further require immediate initialization and prohibit any re-assignment, enforcing immutability.</li><li><strong>Loops and Scope:</strong> In loop constructs, block-scoped declarations (let and const) are created anew for each iteration, preventing accidental re-declarations, while var remains function-scoped.</li><li><strong>Temporal Dead Zone (TDZ):</strong> For let and const, the period between entering a scope and reaching the declaration is the TDZ, during which any access or assignment results in a ReferenceError. This reinforces the importance of placing declarations at the beginning of their scope.</li></ul><p>By grasping these concepts — hoisting, initialization, re-declaration, and the TDZ — developers can write clearer, more predictable code. The chapter not only explains how JavaScript handles variables internally but also advocates for coding practices that minimize common pitfalls associated with these behaviors. In doing so, it lays a solid foundation for understanding more complex topics in scope and closures, setting the stage for deeper exploration in subsequent chapters.</p><p>This comprehensive understanding is essential for any JavaScript developer aiming to write robust and maintainable code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e631dc5f9873" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[You Don’t Know JS Yet: Scope & Closures — Chapter 4]]></title>
            <link>https://medium.com/@m.rastegar991/you-dont-know-js-yet-scope-closures-chapter-4-9f8ac5f1f116?source=rss-23d49b6d6b51------2</link>
            <guid isPermaLink="false">https://medium.com/p/9f8ac5f1f116</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[you-dont-know-js]]></category>
            <category><![CDATA[nodejs-development]]></category>
            <dc:creator><![CDATA[M Rastegar]]></dc:creator>
            <pubDate>Thu, 06 Mar 2025 03:00:32 GMT</pubDate>
            <atom:updated>2025-03-06T03:00:32.796Z</atom:updated>
            <content:encoded><![CDATA[<h3>You Don’t Know JS Yet: Scope &amp; Closures — Chapter 4</h3><h3>Understanding the Global Scope in JavaScript</h3><p>JavaScript’s global scope plays a crucial role in organizing and structuring programs, despite the modern trend of relying on modules and encapsulation. Chapter 4 of <em>You Don’t Know JS Yet: Scope &amp; Closures — 2nd Edition</em> dives deep into the global scope, exploring its utility, nuances, and variations across different JavaScript environments. This article summarizes the key insights, ensuring a thorough understanding of how the global scope functions and why mastering it remains essential for JavaScript developers.</p><p><strong>Reference</strong>:<br><a href="https://github.com/getify/You-Dont-Know-JS/blob/2nd-ed/scope-closures/ch4.md">https://github.com/getify/You-Dont-Know-JS/blob/2nd-ed/scope-closures/ch4.md</a></p><h3>Why Global Scope Matters</h3><p>JavaScript applications often comprise multiple files that need to interact within a shared execution context. The global scope facilitates this interaction in three main ways:</p><ol><li><strong>ES Modules (ESM)</strong> — Each module is loaded separately, and interactions occur through explicit import and export statements rather than shared global variables.</li><li><strong>Bundlers</strong> — Tools like Webpack and Rollup concatenate files, often wrapping them in a single function scope to manage dependencies without polluting the global scope.</li><li><strong>Non-Module Scripts</strong> — When scripts are loaded individually via &lt;script&gt; tags, global scope becomes the primary means of inter-script communication.</li></ol><p>Even though best practices discourage excessive reliance on global variables, the global scope remains an essential <em>glue</em> for JavaScript applications, providing access to built-in JavaScript objects and environment-specific global variables.</p><h3>Where is the Global Scope?</h3><p>At first glance, the global scope appears to be the outermost level of a JavaScript file. However, different execution environments handle it differently:</p><h4>Browser Global Scope (window)</h4><p>In a traditional browser environment, the global object is window, and global variables declared with var become properties of window. For example:</p><pre>var studentName = &quot;Kyle&quot;;<br>function hello() {<br>    console.log(`Hello, ${window.studentName}!`);<br>}<br>window.hello();<br>// Hello, Kyle!</pre><p>However, variables declared with let or const do not become properties of window, leading to potential confusion:</p><pre>let studentName = &quot;Kyle&quot;;<br>console.log(window.studentName); // undefined</pre><p>Additionally, the browser automatically registers DOM elements with id attributes as global variables, a legacy behavior that can lead to unexpected bugs:</p><pre>&lt;ul id=&quot;todo-list&quot;&gt;<br>   &lt;li id=&quot;task&quot;&gt;Write a book&lt;/li&gt;<br>&lt;/ul&gt;</pre><pre>&lt;script&gt;<br>console.log(task); // &lt;li id=&quot;task&quot;&gt;Write a book&lt;/li&gt;<br>&lt;/script&gt;</pre><h4>Web Workers</h4><p>Web Workers provide a separate thread for JavaScript execution and lack access to the DOM. Instead of window, the global object is self:</p><pre>var studentName = &quot;Kyle&quot;;<br>let studentID = 42;<br><br>function hello() {<br>    console.log(`Hello, ${ self.studentName }!`);<br>}<br>self.hello();<br>// Hello, Kyle!<br><br>self.studentID;<br>// undefined</pre><h4>Developer Tools Console</h4><p>Developer consoles in browsers (REPL environments) often exhibit behaviors that differ from real execution contexts. For instance, variables declared in the global scope of the console may not behave exactly like global variables in a script file. This distinction is crucial when testing or debugging code.</p><h4>ES Modules (ESM)</h4><p>With ES6 modules, top-level variables declared in a module file are <em>not</em> global. Instead, they exist in a module-specific scope:</p><pre>var studentName = &quot;Kyle&quot;;<br><br>function hello() {<br>    console.log(`Hello, ${ studentName }!`);<br>}<br><br>hello();<br>// Hello, Kyle!<br><br>export hello;</pre><p>These variables are not attached to the global object, reducing unintended interactions between different modules.</p><h4>Node.js Global Scope</h4><p>In Node.js, every .js file is treated as a module, meaning its top-level variables are scoped to the module, not the global environment. Unlike browsers, Node uses global instead of window:</p><pre>var studentName = &quot;Kyle&quot;;<br><br>function hello() {<br>    console.log(`Hello, ${ studentName }!`);<br>}<br><br>hello();<br>// Hello, Kyle!<br><br>module.exports.hello = hello;</pre><p>Variables declared with var, let, or const at the top level of a Node module are not added to global.</p><h3>The globalThis Object</h3><p>Different JavaScript environments reference the global object differently:</p><ul><li>window (browser)</li><li>self (Web Workers)</li><li>global (Node.js)</li></ul><p>To unify these references, ES2020 introduced globalThis as a standard way to access the global object across all environments:</p><pre>console.log(globalThis); // Works in browser, Node.js, and Web Workers</pre><p>For environments that do not yet support globalThis, a polyfill can provide compatibility:</p><pre>const theGlobalScopeObject =<br>    (typeof globalThis != &quot;undefined&quot;) ? globalThis :<br>    (typeof global != &quot;undefined&quot;) ? global :<br>    (typeof window != &quot;undefined&quot;) ? window :<br>    (typeof self != &quot;undefined&quot;) ? self :<br>    (new Function(&quot;return this&quot;))();</pre><h3>At The End</h3><p>While modern JavaScript development de-emphasizes the use of global variables, understanding the nuances of the global scope is critical. Different environments treat the global scope differently, making it essential for developers to be aware of these distinctions. With globalThis, JavaScript now provides a unified way to reference the global object across platforms, ensuring consistency in global scope access.</p><p>Mastering these concepts enhances your ability to write robust, modular, and cross-environment JavaScript applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9f8ac5f1f116" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[You Don’t Know JS Yet: Scope & Closures — Chapter 3]]></title>
            <link>https://medium.com/@m.rastegar991/you-dont-know-js-yet-scope-closures-chapter-3-2feec4fcba96?source=rss-23d49b6d6b51------2</link>
            <guid isPermaLink="false">https://medium.com/p/2feec4fcba96</guid>
            <category><![CDATA[node-js-development]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[you-dont-know-js]]></category>
            <dc:creator><![CDATA[M Rastegar]]></dc:creator>
            <pubDate>Sun, 02 Mar 2025 05:13:14 GMT</pubDate>
            <atom:updated>2025-03-02T05:14:28.801Z</atom:updated>
            <content:encoded><![CDATA[<h3>You Don’t Know JS Yet: Scope &amp; Closures — Chapter 3</h3><p>In Chapter 3 of “You Don’t Know JS Yet: Scope &amp; Closures” by Kyle Simpson, the concept of the <strong>scope chain</strong> is explored in depth. This chapter elucidates how JavaScript resolves variable references through the interconnected scopes within a program. Understanding the scope chain is crucial for developers to write predictable and bug-free code.</p><p>Reference:<br><a href="https://github.com/getify/You-Dont-Know-JS/blob/2nd-ed/scope-closures/ch3.md">https://github.com/getify/You-Dont-Know-JS/blob/2nd-ed/scope-closures/ch3.md</a></p><h3>The Scope Chain: An Overview</h3><p>The <strong>scope chain</strong> refers to the hierarchical structure of nested scopes in a JavaScript program. When a variable is accessed, the JavaScript engine traverses this chain to locate the variable’s declaration. This traversal begins from the innermost scope and proceeds outward until the variable is found or the global scope is reached.</p><p>Consider the following example:</p><pre>function outer() {<br>    var a = 1;<br>    function inner() {<br>        var b = 2;<br>        console.log(a + b);<br>    }<br>    inner();<br>}<br>outer(); // Outputs: 3</pre><p>In this snippet:</p><ul><li>The outer function creates a scope containing the variable a.</li><li>The inner function, nested within outer, has access to both its own variable b and the variable a from outer&#39;s scope.</li><li>When inner is invoked, it successfully logs the sum of a and b by traversing the scope chain to access a.</li></ul><h3>Shadowing: Variables with the Same Name</h3><p><strong>Shadowing</strong> occurs when a variable declared in an inner scope shares the same name as one in an outer scope. In such cases, the inner variable “shadows” the outer one, making the outer variable inaccessible within that inner scope.</p><p>Example:</p><pre>var x = 10;<br>function foo() {<br>    var x = 20;<br>    console.log(x);<br>}<br>foo(); // Outputs: 20<br>console.log(x); // Outputs: 10</pre><p>Here:</p><ul><li>The global variable x is set to 10.</li><li>Within the function foo, a new variable x is declared and assigned the value 20.</li><li>Inside foo, the local x is accessed, shadowing the global x.</li><li>Outside foo, the global x remains unchanged.</li></ul><h3>Function vs. Block Scope</h3><p>Traditionally, JavaScript utilized <strong>function scope</strong>, meaning variables declared within a function are confined to that function’s scope. However, with the introduction of ES6, <strong>block scope</strong> became available through the let and const keywords, allowing variables to be scoped within blocks delimited by {}.</p><p>Example of block scope using let:</p><pre>function example() {<br>    var x = 1;<br>    if (true) {<br>        let x = 2;<br>        console.log(x); // Outputs: 2<br>    }<br>    console.log(x); // Outputs: 1<br>}<br>example();</pre><p>In this case:</p><ul><li>The variable x declared with let inside the if block is confined to that block.</li><li>The outer x remains unaffected by the inner block&#39;s x.</li></ul><h3>Lexical Scope and Arrow Functions</h3><p><strong>Arrow functions</strong>, introduced in ES6, differ from traditional functions in how they handle the this keyword and their lexical scoping. They do not have their own this context; instead, they inherit this from the enclosing scope.</p><p>Example:</p><pre>function Person() {<br>    this.age = 0;<br>    setInterval(() =&gt; {<br>        this.age++;<br>        console.log(this.age);<br>    }, 1000);<br>}<br>var person = new Person();<br>// output: <br>// 1<br>// 2<br>// 3<br>// ...</pre><p>In this example:</p><ul><li>The arrow function inside setInterval inherits the this context from the Person function.</li><li>Each second, it increments and logs the age property of the person object.</li></ul><p>This behavior contrasts with traditional functions, which have their own this context.</p><h3>Practical Implications of the Scope Chain</h3><p>Understanding the scope chain is vital for several reasons:</p><ul><li><strong>Variable Resolution</strong>: Knowing how variables are resolved helps prevent unintended behavior due to variable shadowing or conflicts.</li><li><strong>Memory Management</strong>: Variables are garbage collected when they are no longer accessible through the scope chain, aiding in efficient memory usage.</li><li><strong>Closures</strong>: Functions that reference variables from their outer scope create closures, enabling powerful programming patterns but also requiring careful management to avoid memory leaks.</li></ul><h3>At The End</h3><p>The scope chain is a foundational concept in JavaScript, dictating how variables are resolved and accessed throughout a program. By mastering the intricacies of scope, shadowing, and the distinctions between function and block scope, developers can write more predictable, maintainable, and efficient code.</p><p>For a comprehensive exploration of these topics, refer to <a href="https://github.com/getify/You-Dont-Know-JS/blob/2nd-ed/scope-closures/ch3.md">Chapter 3 of “You Don’t Know JS Yet: Scope &amp; Closures”</a> by Kyle Simpson.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2feec4fcba96" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[You Don’t Know JS Yet: Scope & Closures — Chapter 2]]></title>
            <link>https://medium.com/@m.rastegar991/you-dont-know-js-yet-scope-closures-chapter-2-a85e1c784d17?source=rss-23d49b6d6b51------2</link>
            <guid isPermaLink="false">https://medium.com/p/a85e1c784d17</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[you-dont-know-js]]></category>
            <dc:creator><![CDATA[M Rastegar]]></dc:creator>
            <pubDate>Tue, 25 Feb 2025 05:44:30 GMT</pubDate>
            <atom:updated>2025-02-25T05:59:12.150Z</atom:updated>
            <content:encoded><![CDATA[<h3>You Don’t Know JS Yet: Scope &amp; Closures — Chapter 2</h3><p><a href="https://github.com/getify/You-Dont-Know-JS/blob/2nd-ed/scope-closures/ch2.md">https://github.com/getify/You-Dont-Know-JS/blob/2nd-ed/scope-closures/ch2.md</a></p><p>In Chapter 2, the focus shifts from merely defining scope to a detailed exploration of <strong>lexical scope</strong> — how JavaScript determines the accessibility of variables based solely on their physical location within the code. The chapter emphasizes that this mechanism is a static, compile-time property and explains why it is fundamental for predictable behavior in JavaScript. Additionally, it distinguishes between lexical scope and the dynamic aspects of execution (such as context), clarifying a few persistent misconceptions.</p><h3>Lexical Scope: A Deeper Dive</h3><h3>Defining Lexical Scope</h3><ul><li><strong>Lexical scope</strong> is the set of rules that determines how variable names are resolved based on where they are declared in the source code.</li><li>Unlike dynamic scope (where the call stack might determine variable lookup), lexical scope is fixed at compile time. That is, the structure of your code — the nested blocks and function definitions — dictates which variables are accessible within any given function.</li></ul><h3>Key Insight:</h3><blockquote><strong><em>The environment in which a function is declared (not where it’s called) defines its scope.</em></strong></blockquote><p>This idea is crucial for understanding how closures work later on. When a function is created, it “remembers” its surrounding scope regardless of where or how it is invoked.</p><h3>How Lexical Scope Works in Practice</h3><p>When JavaScript code is parsed, it creates a tree-like structure of nested scopes:</p><ul><li><strong>Global Scope:</strong> The outermost level that houses variables defined outside any function.</li><li><strong>Function (Local) Scope:</strong> Each function creates its own scope. Any variable declared inside that function is only accessible within it (unless specifically returned or passed out).</li><li><strong>Nested Scopes:</strong> Functions defined inside other functions form nested scopes. The inner function can access variables from its own scope as well as from all outer (parent) scopes.</li></ul><h3>Code Example: Nested Scopes</h3><pre>var globalVar = &quot;global&quot;;<br>function outer() {<br>  var outerVar = &quot;outer&quot;;<br>  function inner() {<br>    var innerVar = &quot;inner&quot;;<br>    console.log(globalVar); // &quot;global&quot; from global scope<br>    console.log(outerVar);  // &quot;outer&quot; from outer()&#39;s scope<br>    console.log(innerVar);  // &quot;inner&quot; from inner()&#39;s own scope<br>  }<br>  inner();<br>}<br>outer();</pre><p><strong>Explanation:</strong></p><ul><li>The function inner() is defined within outer(), so it inherits the scope chain that includes its own scope, outer()’s scope, and finally the global scope.</li><li>Variable lookups occur by checking the local scope first; if not found, the search moves outward.</li></ul><h3>The Static Nature of Lexical Scope</h3><p>A major theme in Chapter 2 is that <strong>lexical scope is static</strong>. This means:</p><ul><li><strong>Immutable Lookup Structure:</strong> The structure of variable lookups does not change at runtime. Even if a function is passed around or invoked in different contexts, its scope chain remains the same as when it was defined.</li><li><strong>Predictability:</strong> Because the lookup is fixed during parsing, you can determine variable accessibility simply by reading the code.</li></ul><h3>Code Example: Function’s Unchanging Scope</h3><pre>function showVar() {<br>  console.log(a);<br>}<br>var a = 42;<br>var obj = { showVar: showVar };<br>// Despite being called as a method of an object,<br>// showVar() still logs the global variable &#39;a&#39; (42).<br>obj.showVar();</pre><p><strong>Explanation:</strong></p><ul><li>The function showVar was defined in the global scope; hence its lookup for a always starts in that context—even though it’s invoked as a method of obj.</li><li>This example underlines that the <strong>call site</strong> does not affect the lexical scope of a function.</li></ul><h3>Variable Resolution and Shadowing</h3><h3>How Variables Are Resolved</h3><p>The process of variable resolution follows the <strong>scope chain</strong>:</p><ol><li><strong>Local Search:</strong> JavaScript first checks the function’s own scope.</li><li><strong>Outer Scopes:</strong> If not found, it looks up in the immediately enclosing function’s scope, then continues upward.</li><li><strong>Global Fallback:</strong> Finally, if the variable isn’t found in any nested scope, the global scope is checked.</li></ol><h3>Variable Shadowing</h3><ul><li><strong>Definition:</strong> Shadowing occurs when a variable declared in an inner scope has the same name as a variable in an outer scope.</li><li><strong>Effect:</strong> The inner variable “shadows” the outer one, making the outer variable inaccessible in that block.</li></ul><h3>Code Example: Shadowing</h3><pre>var name = &quot;Global Name&quot;;<br>function greet() {<br>  var name = &quot;Local Name&quot;;<br>  console.log(name); // Outputs: &quot;Local Name&quot;<br>}<br>greet();<br>console.log(name);   // Outputs: &quot;Global Name&quot;</pre><p><strong>Explanation:</strong></p><ul><li>Within greet(), the local name variable takes precedence over the global name.</li><li>Shadowing is a natural consequence of lexical scoping, reinforcing that variable resolution depends entirely on where a variable is declared.</li></ul><h3>The Relationship Between Lexical Scope and Closures</h3><p>While the primary focus of Chapter 2 is on lexical scope, it naturally sets up the discussion for closures:</p><ul><li><strong>Closure Defined:</strong> A closure occurs when a function “closes over” its lexical environment, retaining access to variables from that environment even after the outer function has executed.</li><li><strong>Foundation in Lexical Scope:</strong> Because lexical scope is determined at creation, a function can reliably remember and access the variables from its declaring context.</li></ul><h3>Code Example: A Simple Closure</h3><pre>function makeCounter() {<br>  var count = 0;<br>  return function() {<br>    count += 1;<br>    return count;<br>  };<br>}<br><br>var counter = makeCounter();<br>console.log(counter()); // 1<br>console.log(counter()); // 2</pre><p><strong>Explanation:</strong></p><ul><li>The inner function retains access to count even after makeCounter() has finished execution.</li><li>This behavior is only possible because of the static, lexical scoping that defines the inner function’s environment.</li></ul><h3>Misconceptions Clarified</h3><p>Chapter 2 also debunks a few common misunderstandings:</p><p><strong>Scope vs. Context:</strong></p><ul><li><strong>Lexical Scope</strong> is about variable lookup determined at code definition time.</li><li><strong>Execution Context (or this-binding):</strong> This is determined at runtime and depends on how a function is called.</li><li><strong>Dynamic vs. Lexical Scope: </strong>JavaScript does <strong>not</strong> use dynamic scope; variable resolution does not change based on the call stack. Instead, it is strictly tied to where variables and functions are declared.</li></ul><pre>function showThis() {<br>  console.log(this);<br>}<br><br>var obj = {<br>  method: showThis<br>};<br><br>showThis();    // in the global environment: in the browser window, in Node.js global<br>obj.method();  // in the environment of the object obj: output obj</pre><p><strong>Explanation:</strong></p><p>In this example, the show This function is always the same in terms of lexical scope (where it is defined in the global). However, depending on how it is called (execution context), the value of this changes.</p><p><em>This example shows that the way the function is called (execution context) does not affect the lexical scope.</em></p><h3>Key Takeaways</h3><ul><li><strong>Static Resolution:</strong> Lexical scope is fixed at compile time. The physical location of code dictates variable accessibility.</li><li><strong>Scope Chain:</strong> Variable lookup follows a clear chain from local scope to outer scopes, ending at the global level.</li><li><strong>Predictability:</strong> Since the scope chain is determined by code structure, it provides a predictable framework for how functions access variables.</li><li><strong>Foundation for Closures:</strong> The static nature of lexical scope is what allows closures to work reliably by preserving the function’s original environment.</li><li><strong>Clear Separation:</strong> Understand the difference between lexical scope (variable resolution) and execution context (how a function is called).</li></ul><h3>At the end:</h3><p>Chapter 2 of <em>You Don’t Know JS: Scope &amp; Closures — 2nd Edition</em> offers a deep exploration into the mechanics of lexical scope, emphasizing its static nature and its critical role in the language’s design. By understanding that the structure of your code determines variable accessibility, you gain powerful insights into why JavaScript behaves the way it does — especially when functions are passed around and invoked in different contexts.</p><p>This chapter reinforces that the predictability of variable lookups is a cornerstone of JavaScript’s design, providing the necessary foundation for understanding more complex concepts such as closures. By carefully tracing the scope chain in nested functions and recognizing the effects of variable shadowing, you are better prepared to write clean, maintainable code and avoid common pitfalls.</p><p>As you continue through the book, keep in mind the distinction between where a function is defined versus where it is called. This principle not only clarifies how variables are accessed but also empowers you to leverage closures effectively in your applications. The clarity provided by understanding lexical scope ultimately contributes to writing more robust, predictable JavaScript code.</p><p>Embrace these concepts, experiment with the code examples provided, and allow your growing understanding of lexical scope to inform your approach to more advanced topics in the coming chapters.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a85e1c784d17" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>