<?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" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ Shejan Mahamud - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ Shejan Mahamud - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Wed, 06 May 2026 11:21:16 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/author/Shejan-Mahamud/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ How Do Global Execution Context and Temporal Dead Zone Work in JavaScript? ]]>
                </title>
                <description>
                    <![CDATA[ Have you ever wondered how JavaScript runs your code behind the scenes, and how the Global Execution Context actually works? How does hoisting work for var, let, and const? Consider the code bellow: console.log('My age is', age) console.log('My name ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/global-execution-context-and-temporal-dead-zone-explained/</link>
                <guid isPermaLink="false">690b5691972e7bfdc1ed09c1</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ optimization ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Shejan Mahamud ]]>
                </dc:creator>
                <pubDate>Wed, 05 Nov 2025 13:52:17 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1762347165225/c7bd75a9-a819-41b6-8a35-4feecfb7cf58.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Have you ever wondered how JavaScript runs your code behind the scenes, and how the Global Execution Context actually works? How does hoisting work for <code>var</code>, <code>let</code>, and <code>const</code>?</p>
<p>Consider the code bellow:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(<span class="hljs-string">'My age is'</span>, age)
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'My name is'</span>, name)
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'My country is'</span>, country)

<span class="hljs-keyword">var</span> age = <span class="hljs-number">24</span>
<span class="hljs-keyword">let</span> name = <span class="hljs-string">'Shejan'</span>
<span class="hljs-keyword">const</span> country = <span class="hljs-string">'Bangladesh'</span>
sayHi()
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sayHi</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Hi!'</span>)
}
</code></pre>
<p>What do you think the output of this code will be?</p>
<p>The first line will probably print <code>undefined</code>, right? But what about the second line with <code>name</code>? This will throw a “<code>ReferenceError</code>: Cannot access <code>name</code> before initialization.” Why? Because <code>let</code> variables are hoisted but remain uninitialized in the temporal dead zone (TDZ) until their declaration line is reached.</p>
<p>The third line with <code>country</code> will never execute because the code stops at line 2 due to the <code>ReferenceError</code>. But if line 2 wasn’t there, line 3 would throw the same error for the same reason – <code>const</code> also stays in the TDZ.</p>
<p>And what about the <code>sayHi()</code> function call? If we could reach it, it would work perfectly and print "Hi!" because function declarations are fully hoisted with their complete body.</p>
<p>The main question: why and how is all this happening? Let's dive in and find answers to these questions.</p>
<h2 id="heading-heres-what-well-cover">Here’s What We’ll Cover:</h2>
<ul>
<li><p><a class="post-section-overview" href="#heading-how-does-the-global-execution-context-work">How Does the Global Execution Context Work?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-memory-creation-phase">Memory Creation Phase</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-understanding-the-flowchart">Understanding the Flowchart</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-exactly-is-hoisting">What Exactly is Hoisting?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-does-only-var-get-hoisted">Does Only var Get Hoisted?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-temporal-dead-zone-tdz-what-is-it-really">Temporal Dead Zone (TDZ) – What is it Really?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-function-hoisting-the-most-interesting-part">Function Hoisting – The Most Interesting Part!</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-what-happens-in-the-memory-phase">What Happens in the Memory Phase:</a></p>
</li>
</ul>
<h2 id="heading-how-does-the-global-execution-context-work">How Does the Global Execution Context Work?</h2>
<p>When we run any JavaScript code, the very first thing that happens is the creation of a <strong>Global Execution Context (GEC)</strong>. This is the fundamental concept behind JavaScript execution! This global execution context has two important phases:</p>
<ol>
<li><p><strong>Memory creation phase</strong> (memory phase)</p>
</li>
<li><p><strong>Code execution phase</strong> (thread phase)</p>
</li>
</ol>
<p>Let's look at what happens in each phase, one by one.</p>
<h2 id="heading-memory-creation-phase">Memory Creation Phase</h2>
<p>This is the preparation time. During this phase, the JavaScript engine scans through the entire code once (without executing it) and allocates memory for all variables and functions.</p>
<p>But here's where it gets interesting:</p>
<ul>
<li><p><strong>Variables</strong> (var, let, const) are given space in memory.</p>
<ul>
<li><p><code>var</code> is assigned the value <code>undefined</code>.</p>
</li>
<li><p><code>let</code> and <code>const</code> are placed in memory but remain uninitialized.</p>
</li>
<li><p>Functions (function declarations) are stored in memory with their complete code body.</p>
</li>
</ul>
</li>
</ul>
<p>So what happens in the memory phase for our example code?</p>
<pre><code class="lang-bash">age: undefined
name: &lt;uninitialized&gt;
country: &lt;uninitialized&gt;
sayHi: <span class="hljs-function"><span class="hljs-title">function</span></span>() { console.log(<span class="hljs-string">"Hi!"</span>); }
</code></pre>
<p>As you can see, even before a single line of code is executed, everything is already in memory! This entire process of lifting variables and functions into memory during the memory creation phase is called <strong>Hoisting</strong> – and this is what makes JavaScript execution seem "magical."</p>
<h3 id="heading-code-execution-phase">Code Execution Phase</h3>
<p>Now the real action begins! The JavaScript engine starts executing the code line by line.</p>
<p><strong>Line 1:</strong> <code>console.log("My age is", age);</code></p>
<ul>
<li><p>Looks for <code>age</code> in memory</p>
</li>
<li><p>Finds <code>undefined</code></p>
</li>
<li><p><strong>Output:</strong> <code>My age is undefined</code></p>
</li>
</ul>
<p>Line 2: <code>console.log("My name is", name);</code></p>
<ul>
<li><p>Looks for name in memory Finds that it exists in memory but hasn't been initialized yet (it's in the temporal dead zone, or TDZ – we'll explore this concept in detail later).</p>
</li>
<li><p>Output: <code>ReferenceError</code>: Cannot access <code>name</code> before initialization.</p>
</li>
</ul>
<p>The code execution stops right here! The remaining lines won't be executed.</p>
<p>But what would happen if Lines 2 and 3 weren't there?</p>
<p><strong>Line 4:</strong> <code>var age = 24;</code></p>
<ul>
<li>The value of <code>age</code> in memory gets updated from <code>undefined</code> to <code>24</code></li>
</ul>
<p><strong>Line 5:</strong> <code>let name = "Shejan";</code></p>
<ul>
<li><p><code>name</code> is now initialized with the value <code>"Shejan"</code></p>
</li>
<li><p>From this point forward, <code>name</code> can be accessed</p>
</li>
</ul>
<p><strong>Line 6:</strong> <code>const country = "Bangladesh";</code></p>
<ul>
<li><code>country</code> is initialized with the value <code>"Bangladesh"</code></li>
</ul>
<p><strong>Lines 7-9:</strong> Function call</p>
<ul>
<li><p>The <code>sayHi()</code> function was already loaded with its complete body during the memory phase.</p>
</li>
<li><p>When <code>sayHi()</code> is called, the JavaScript engine creates a new execution context specifically for this function.</p>
</li>
<li><p>This new context is known as a <strong>Function Execution Context (FEC)</strong> – it works as a child of the global execution context.</p>
</li>
</ul>
<p>This function execution context also has <strong>two phases</strong>, just like the global execution context:</p>
<ol>
<li><p><strong>Memory Creation Phase:</strong></p>
<ul>
<li><p>All variables, parameters, and nested functions inside the function are allocated in memory.</p>
</li>
<li><p>Function arguments are assigned.</p>
</li>
<li><p>A function scope is created and a reference link is established with the outer lexical environment (where the function was defined) – this link is called the <strong>scope chain</strong>. The scope chain is JavaScript's way of resolving variable names. It's like a chain of connected scopes. When JavaScript looks for a variable inside a function, it first checks the function's own scope. If it doesn't find the variable there, it moves up the chain to check the parent scope (where the function was defined), then the grandparent scope, and so on, until it reaches the global scope. This chain ensures that functions can access variables from their outer environments.</p>
</li>
</ul>
</li>
<li><p><strong>Code Execution (Thread) Phase:</strong></p>
<ul>
<li><p>Now the function body is executed line by line.</p>
</li>
<li><p><code>console.log("Hi!");</code> executes and prints <strong>"Hi!"</strong></p>
</li>
</ul>
</li>
</ol>
<p>Once the function execution is complete:</p>
<ul>
<li><p>That function execution context is popped off the call stack.</p>
</li>
<li><p>And control returns to the global execution context.</p>
</li>
</ul>
<p><strong>Note</strong>: When all code execution is complete, the global execution context is also popped off the call stack.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1761988425883/33792916-eee7-4f87-b365-51a04290aa96.png" alt="Flowchart diagram illustrating JavaScript Global Execution Context workflow, showing the two phases - Memory Creation Phase where variables and functions are allocated, and Code Execution Phase where code runs line by line, including how Function Execution Context is created when functions are called" class="image--center mx-auto" width="600" height="400" loading="lazy"></p>
<p>The flowchart diagram above illustrates the JavaScript global execution context workflow, showing the two phases. In the memory creation phase, variables and functions are allocated, and in the code execution phase, the code runs line by line. It also shows how the function execution context is created when functions are called.</p>
<h2 id="heading-understanding-the-flowchart">Understanding the Flowchart</h2>
<p>The diagram above visualizes the complete journey of JavaScript code execution from start to finish.</p>
<p><strong>The flow begins</strong> when JavaScript execution starts and immediately creates a global execution context (GEC). This context then splits into two distinct phases, shown as a diamond in the diagram.</p>
<p><strong>On the left side - Memory Creation Phase:</strong> You can see three parallel branches showing how different types of declarations are handled:</p>
<ul>
<li><p><code>var</code> variables are allocated with the value <code>undefined</code></p>
</li>
<li><p><code>let</code> and <code>const</code> variables are allocated but remain uninitialized (in the temporal dead zone)</p>
</li>
<li><p>Function declarations are fully hoisted with their complete body</p>
</li>
</ul>
<p><strong>On the right side - Code Execution Phase:</strong> JavaScript now executes the code line by line. During execution:</p>
<ul>
<li><p>It accesses variable values from memory</p>
</li>
<li><p>If you try to access <code>let</code> or <code>const</code> before initialization, you get a ReferenceError (temporal dead zone)</p>
</li>
<li><p>If you access <code>var</code> before assignment, you get <code>undefined</code></p>
</li>
<li><p>When a function is called, a new Function Execution Context (FEC) is created</p>
</li>
</ul>
<p><strong>The Function Execution Context (FEC)</strong> (shown in the right branch) works as a child of the GEC and has its own Memory and Execution phases. After the function executes completely, the FEC is popped off the call stack and control returns to the GEC.</p>
<p><strong>Finally</strong>, when all code execution is complete, the GEC itself is popped from the call stack, and the program ends.</p>
<p>This visual representation helps you understand that JavaScript doesn't just read and run your code - it prepares everything first (Memory Phase) and then executes it systematically (Execution Phase).</p>
<h2 id="heading-what-exactly-is-hoisting">What Exactly is Hoisting?</h2>
<p>Hoisting is JavaScript's default behavior of moving variable and function declarations to memory before code execution begins.</p>
<p>Think of it this way – it appears as if all declarations automatically move to the very top of the code. Although the code doesn't physically move, the memory allocation happens first.</p>
<h2 id="heading-does-only-var-get-hoisted">Does Only <code>var</code> Get Hoisted?</h2>
<p>This surprises many people, but the answer is no. It's not just <code>var</code> that gets hoisted! This is a huge misconception among many developers.</p>
<p>The truth is that—<code>let</code>, <code>const</code>, and functions—everything gets hoisted! But their behavior is completely different. Let's dive into the details.</p>
<h3 id="heading-what-happens-with-var">What Happens with <code>var</code>?</h3>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(name) <span class="hljs-comment">// undefined</span>
<span class="hljs-keyword">var</span> name = <span class="hljs-string">'Rahim'</span>
<span class="hljs-built_in">console</span>.log(name) <span class="hljs-comment">// "Rahim"</span>
</code></pre>
<p>Variables declared with <code>var</code>:</p>
<ul>
<li><p>Get hoisted</p>
</li>
<li><p>Are initialized with <code>undefined</code></p>
</li>
<li><p>Exist in global scope or function scope</p>
</li>
<li><p>Can be accessed before declaration (doesn't throw an error)</p>
</li>
</ul>
<h3 id="heading-what-happens-with-let">What Happens with <code>let</code>?</h3>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(name) <span class="hljs-comment">// ReferenceError: Cannot access 'name' before initialization</span>
<span class="hljs-keyword">let</span> name = <span class="hljs-string">'Rahim'</span>
<span class="hljs-built_in">console</span>.log(name) <span class="hljs-comment">// "Rahim"</span>
</code></pre>
<p>Is this magic? No! Actually, <code>let</code> does get hoisted, but it's stuck in a special state called the temporal dead zone!</p>
<p>Space is allocated in memory, but it's not initialized. So if you try to access it before declaration, JavaScript says – "Hey, the variable exists, but you can't use it yet!"</p>
<h3 id="heading-what-happens-with-const">What Happens with <code>const</code>?</h3>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(age) <span class="hljs-comment">// ReferenceError: Cannot access 'age' before initialization</span>
<span class="hljs-keyword">const</span> age = <span class="hljs-number">24</span>
<span class="hljs-built_in">console</span>.log(age) <span class="hljs-comment">// 24</span>
</code></pre>
<p>The behavior of <code>const</code> is exactly the same as <code>let</code>:</p>
<ul>
<li><p>Gets hoisted</p>
</li>
<li><p>Stays in the TDZ until declaration</p>
</li>
<li><p>Exists in block scope</p>
</li>
<li><p>Plus, once assigned, it cannot be reassigned</p>
</li>
</ul>
<h2 id="heading-temporal-dead-zone-tdz-what-is-it-really">Temporal Dead Zone (TDZ) – What is it Really?</h2>
<p>The Temporal Dead Zone is the time period or zone when a variable exists in memory (due to hoisting) but hasn't been initialized yet. During this time, the variable is essentially "dead" – meaning that you cannot access it.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// ← TDZ starts for x and y</span>
<span class="hljs-built_in">console</span>.log(x) <span class="hljs-comment">// ReferenceError - still in TDZ</span>
<span class="hljs-built_in">console</span>.log(y) <span class="hljs-comment">// ReferenceError - still in TDZ</span>

<span class="hljs-comment">// TDZ continues...</span>
<span class="hljs-keyword">let</span> x = <span class="hljs-number">10</span> <span class="hljs-comment">// ← x's TDZ ends at this line</span>
<span class="hljs-keyword">const</span> y = <span class="hljs-number">20</span> <span class="hljs-comment">// ← y's TDZ ends at this line</span>

<span class="hljs-built_in">console</span>.log(x) <span class="hljs-comment">// 10 - can access now</span>
<span class="hljs-built_in">console</span>.log(y) <span class="hljs-comment">// 20 - can access now</span>
</code></pre>
<p>The entire concept of TDZ is to force us to write better code. Using variables before declaring them is a bad practice, and TDZ prevents us from doing that.</p>
<h2 id="heading-function-hoisting-the-most-interesting-part">Function Hoisting – The Most Interesting Part!</h2>
<p>Hoisting with functions is even more interesting and powerful:</p>
<pre><code class="lang-javascript">greet() <span class="hljs-comment">// "Hello World!" - Perfect! It works!</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greet</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Hello World!'</span>)
}
</code></pre>
<p>How is this possible? Because function declarations are completely hoisted! This means not just the name, but the entire function body is lifted into memory. That's why it can be called even before the declaration.</p>
<p>But wait! Not all functions work this way.</p>
<h3 id="heading-with-function-expressions">With Function Expressions:</h3>
<pre><code class="lang-javascript">greet() <span class="hljs-comment">// TypeError: greet is not a function</span>

<span class="hljs-keyword">var</span> greet = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Hello World!'</span>)
}
</code></pre>
<p>What happened here? <code>greet</code> was hoisted as a variable and received the value <code>undefined</code>. It wasn't hoisted as a function! So when you try to call it, you get an error. In other words, it's hoisted as a variable (assigned <code>undefined</code>), but the function body isn't loaded into memory.</p>
<h3 id="heading-with-arrow-functions">With Arrow Functions:</h3>
<pre><code class="lang-javascript">sayHello() <span class="hljs-comment">// ReferenceError (if let/const is used)</span>

<span class="hljs-keyword">const</span> sayHello = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Hello!'</span>)
}
</code></pre>
<p>Arrow functions behave just like function expressions. They follow variable rules.</p>
<p>Let's clear everything up with a complete example:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(a) <span class="hljs-comment">// undefined (var hoisting)</span>
<span class="hljs-built_in">console</span>.log(b) <span class="hljs-comment">// ReferenceError (TDZ)</span>
<span class="hljs-built_in">console</span>.log(c) <span class="hljs-comment">// ReferenceError (TDZ)</span>
multiply(<span class="hljs-number">2</span>, <span class="hljs-number">3</span>) <span class="hljs-comment">// 6 (function hoisting)</span>
add(<span class="hljs-number">2</span>, <span class="hljs-number">3</span>) <span class="hljs-comment">// TypeError (function expression)</span>

<span class="hljs-keyword">var</span> a = <span class="hljs-number">10</span>
<span class="hljs-keyword">let</span> b = <span class="hljs-number">20</span>
<span class="hljs-keyword">const</span> c = <span class="hljs-number">30</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">multiply</span>(<span class="hljs-params">x, y</span>) </span>{
  <span class="hljs-keyword">return</span> x * y
}

<span class="hljs-keyword">var</span> add = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">x, y</span>) </span>{
  <span class="hljs-keyword">return</span> x + y
}
</code></pre>
<h2 id="heading-what-happens-in-the-memory-phase">What Happens in the Memory Phase:</h2>
<pre><code class="lang-javascript">a: <span class="hljs-literal">undefined</span>
<span class="hljs-attr">b</span>: &lt;uninitialized&gt;
c: &lt;uninitialized&gt;
multiply: function(x, y) { return x * y; }
add: undefined
</code></pre>
<p>This snapshot represents the state of memory before any code is executed. Here's what each line means:</p>
<p><code>a: undefined</code> - Since <code>a</code> is declared with <code>var</code>, it gets hoisted and immediately assigned the value <code>undefined</code>. This is why you get <code>undefined</code> instead of an error when you try to access <code>a</code> before its declaration line.</p>
<p><code>b: &lt;uninitialized&gt;</code> - The variable <code>b</code> is declared with <code>let</code>, so it's hoisted and memory is allocated for it, but it remains uninitialized. It's in the Temporal Dead Zone (TDZ). Attempting to access it before the declaration line will throw a <code>ReferenceError</code>.</p>
<p><code>c: &lt;uninitialized&gt;</code> - Similarly, <code>c</code> is declared with <code>const</code> and follows the same behavior as <code>let</code>. It's hoisted but stays uninitialized in the TDZ until the declaration line is reached.</p>
<p><code>multiply: function(x, y) { return x * y; }</code> - This is a function declaration, so it's fully hoisted with its complete body. The entire function is stored in memory and ready to be called even before the JavaScript engine reaches its declaration in the code. This is why <code>multiply(2, 3)</code> works perfectly and returns <code>6</code>.</p>
<p><code>add: undefined</code> - Here's the crucial difference! Even though <code>add</code> will eventually store a function, it's declared using <code>var add = function() {...}</code> (a function expression). During the memory phase, only the variable <code>add</code> is hoisted and initialized with <code>undefined</code>. The actual function body isn't assigned until the execution phase reaches line 11. This is why calling <code>add(2, 3)</code> before the assignment throws a <code>TypeError: add is not a function</code> - you're essentially trying to execute <code>undefined()</code>.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Understanding JavaScript's execution mechanism is fundamental to becoming a proficient developer. Let's recap the essential concepts we've explored:</p>
<p><strong>The Global Execution Context (GEC)</strong> is the foundation of JavaScript execution. Every time you run JavaScript code, the GEC is created first. It works in two critical phases:</p>
<ul>
<li><p><strong>Memory Creation Phase</strong>: JavaScript prepares by scanning the code and allocating memory for variables and functions.</p>
</li>
<li><p><strong>Code Execution Phase</strong>: JavaScript runs your code line by line.</p>
</li>
</ul>
<p><strong>Hoisting is universal</strong> - not just limited to <code>var</code>. Here's how different declarations are hoisted:</p>
<ul>
<li><p><code>var</code> variables are hoisted and initialized with <code>undefined</code>.</p>
</li>
<li><p><code>let</code> and <code>const</code> are hoisted but remain uninitialized in the TDZ.</p>
</li>
<li><p>Function declarations are fully hoisted with their entire body.</p>
</li>
<li><p>Function expressions and arrow functions follow variable hoisting rules</p>
</li>
</ul>
<p><strong>The Temporal Dead Zone (TDZ)</strong> is JavaScript's built-in safety mechanism. It exists from the start of the scope until the variable declaration line is reached. The TDZ prevents us from accessing <code>let</code> and <code>const</code> variables before they're declared, encouraging better coding practices and helping us avoid bugs.</p>
<p><strong>Function hoisting behavior varies</strong>:</p>
<ul>
<li><p>Function declarations can be called before they appear in code.</p>
</li>
<li><p>Function expressions behave like variables and cannot be called before assignment.</p>
</li>
<li><p>Arrow functions follow the same rules as function expressions.</p>
</li>
</ul>
<p><strong>Why does this matter?</strong> Understanding these concepts helps you:</p>
<ul>
<li><p>Predict how your code will behave before running it.</p>
</li>
<li><p>Avoid common errors like <code>ReferenceError</code> and <code>TypeError</code>.</p>
</li>
<li><p>Write cleaner, more maintainable code.</p>
</li>
<li><p>Debug issues faster when they arise.</p>
</li>
<li><p>Make informed decisions about when to use <code>var</code>, <code>let</code>, or <code>const</code>.</p>
</li>
</ul>
<p><strong>The key takeaway</strong>: <strong>JavaScript doesn't just execute your code - it prepares first, then executes.</strong> The memory phase sets up the stage, and the execution phase performs the show. Master this two-phase process, and you'll have a solid understanding of how JavaScript works under the hood.</p>
<p>Now you're equipped with the knowledge to write better JavaScript code and understand exactly what's happening behind the scenes. Keep practicing these concepts, and they'll become second nature!</p>
<p>Happy Coding!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How __proto__, prototype, and Inheritance Actually Work in JavaScript ]]>
                </title>
                <description>
                    <![CDATA[ Have you ever wondered why everything in JavaScript acts like an object? Or how inheritance actually works behind the scenes? What's the difference between __proto__ and prototype? If these questions have crossed your mind, you're not alone. These ar... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-proto-prototype-and-inheritance-actually-work-in-javascript/</link>
                <guid isPermaLink="false">690a2d839d070c31fadbc25e</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ inheritence ]]>
                    </category>
                
                    <category>
                        <![CDATA[ prototypeal-inheritance ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Object Oriented Programming ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Shejan Mahamud ]]>
                </dc:creator>
                <pubDate>Tue, 04 Nov 2025 16:44:51 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1762210692821/651a67f9-cbe5-4f09-b048-957caaa5e1ac.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Have you ever wondered why everything in JavaScript acts like an object? Or how inheritance actually works behind the scenes? What's the difference between <code>__proto__</code> and <code>prototype</code>?</p>
<p>If these questions have crossed your mind, you're not alone. These are some of the most fundamental concepts in JavaScript, yet they often confuse developers.</p>
<p>In this tutorial, we'll demystify prototypes, prototype chains, and inheritance in JavaScript. By the end, you'll understand the "what," "why," and "how" of JavaScript's prototype system.</p>
<h3 id="heading-heres-what-ill-cover">Here’s what I’ll cover:</h3>
<ul>
<li><p><a class="post-section-overview" href="#heading-the-string-method-mystery">The String Method Mystery</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-objects-work-internally">How Objects Work Internally</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-understanding-the-prototype-chain">Understanding the Prototype Chain</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-why-everything-in-javascript-is-an-object">Why Everything in JavaScript is an Object</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-the-difference-between-proto-and-prototype">The Difference Between <strong>proto</strong> and prototype</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-prototypes-work-with-functions">How Prototypes Work with Functions</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-prototypes-work-with-classes">How Prototypes Work with Classes</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></p>
</li>
</ul>
<h2 id="heading-prerequisites">Prerequisites</h2>
<p>To get the most out of this tutorial, you should have:</p>
<ul>
<li><p>Basic understanding of JavaScript fundamentals</p>
</li>
<li><p>Familiarity with objects, functions, and classes in JavaScript</p>
</li>
<li><p>Knowledge of how to declare and use variables</p>
</li>
<li><p>Experience working with the <code>new</code> keyword (helpful but not required)</p>
</li>
</ul>
<h2 id="heading-the-string-method-mystery">The String Method Mystery</h2>
<p>Let's start with a simple example that demonstrates something interesting about JavaScript:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> name = <span class="hljs-string">"Shejan Mahamud"</span>;
</code></pre>
<p>After declaring this variable, we can use String methods like:</p>
<pre><code class="lang-javascript">name.toLowerCase(); <span class="hljs-comment">// "shejan mahamud"</span>
name.toUpperCase(); <span class="hljs-comment">// "SHEJAN MAHAMUD"</span>
</code></pre>
<p>This seems normal at first glance, but wait – something unusual is happening. Notice anything odd here? We're using dot notation on a string primitive.</p>
<p>Here's the puzzling part: we know that strings are primitive types in JavaScript, not objects. So how can we use dot notation to access methods? After all, dot notation typically only works with objects.</p>
<p>The answer to this mystery lies in understanding how JavaScript handles primitives and prototypes. But before we get there, let's first look at how objects work internally.</p>
<h2 id="heading-how-objects-work-internally">How Objects Work Internally</h2>
<p>When you create an object in JavaScript like this:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> info1 = {
  <span class="hljs-attr">fName</span>: <span class="hljs-string">"Shejan"</span>,
  <span class="hljs-attr">lName</span>: <span class="hljs-string">"Mahamud"</span>
};
</code></pre>
<p>JavaScript does something interesting behind the scenes. It automatically adds a hidden property called <code>__proto__</code> to your object. This property points to <code>Object.prototype</code>, which is the prototype of the built-in Object class.</p>
<p>You might wonder: does <code>Object.prototype</code> also have a <code>__proto__</code>? Yes, it does, but its value is <code>null</code>. This is because <code>Object.prototype</code> is at the top of the prototype chain and doesn't inherit from anything else.</p>
<p>Let's look at a more complex example to understand this better:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> info1 = {
  <span class="hljs-attr">fName1</span>: <span class="hljs-string">"Shejan"</span>,
  <span class="hljs-attr">lName1</span>: <span class="hljs-string">"Mahamud"</span>
};

<span class="hljs-keyword">const</span> info2 = {
  <span class="hljs-attr">fName2</span>: <span class="hljs-string">"Boltu"</span>,
  <span class="hljs-attr">lName2</span>: <span class="hljs-string">"Mia"</span>,
  <span class="hljs-attr">__proto__</span>: info1
};

<span class="hljs-keyword">const</span> info3 = {
  <span class="hljs-attr">fName3</span>: <span class="hljs-string">"Habu"</span>,
  <span class="hljs-attr">lName3</span>: <span class="hljs-string">"Mia"</span>,
  <span class="hljs-attr">__proto__</span>: info2
};
</code></pre>
<p>In this example, we've intentionally set the <code>__proto__</code> property for <code>info2</code> and <code>info3</code>. Now here's an interesting question: can we access <code>fName1</code> from <code>info3</code>?</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(info3.fName1); <span class="hljs-comment">// "Shejan"</span>
</code></pre>
<p>Yes, we can! Let's understand how this works.</p>
<h2 id="heading-understanding-the-prototype-chain">Understanding the Prototype Chain</h2>
<p>When you try to access a property on an object, JavaScript follows a specific lookup process:</p>
<ol>
<li><p>First, it searches for the property in the object itself (the base object)</p>
</li>
<li><p>If it doesn't find it there, it looks in the object's <code>__proto__</code></p>
</li>
<li><p>If it still doesn't find it, it continues up the chain, checking each <code>__proto__</code> until it either finds the property or reaches <code>null</code></p>
</li>
</ol>
<p>In our example with <code>info3.fName1</code>:</p>
<ul>
<li><p>JavaScript first looks in <code>info3</code> – and it doesn't find <code>fName1</code></p>
</li>
<li><p>Then it checks <code>info3.__proto__</code>, which points to <code>info2</code> – it doesn't find <code>fName1</code> there, either</p>
</li>
<li><p>Next it checks <code>info2.__proto__</code>, which points to <code>info1</code> – and it finds <code>fName1</code> here!</p>
</li>
</ul>
<p>This is called the <strong>prototype chain</strong>, and this is how inheritance works in JavaScript. Here's a visual representation:</p>
<pre><code class="lang-javascript">┌────────────┐
│  info3     │
│ fName3     │
│ lName3     │
└────┬───────┘
     │ __proto__
     ▼
┌────────────┐
│  info2     │
│ fName2     │
│ lName2     │
└────┬───────┘
     │ __proto__
     ▼
┌────────────┐
│  info1     │
│ fName1     │
│ lName1     │
└────┬───────┘
     │ __proto__
     ▼
┌─────────────────┐
│ <span class="hljs-built_in">Object</span>.prototype│
└────┬────────────┘
     ▼
    <span class="hljs-literal">null</span>
</code></pre>
<p>Each object points to the next object in the chain through its <code>__proto__</code> property. This chain continues until it reaches <code>null</code>.</p>
<h2 id="heading-why-everything-in-javascript-is-an-object">Why Everything in JavaScript is an Object</h2>
<p>Now let's solve the mystery we started with: how can primitive types use object methods?</p>
<p>In JavaScript, almost everything behaves like an object, even though primitive types (like strings, numbers, and booleans) technically aren't objects. This works through a process called <strong>auto-boxing</strong> or <strong>wrapper objects</strong>.</p>
<p>Let's see this in action:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> yourName = <span class="hljs-string">"Boltu"</span>;
</code></pre>
<p>When you try to use a method on this string:</p>
<pre><code class="lang-javascript">yourName.toLowerCase();
</code></pre>
<p>Here's what JavaScript does behind the scenes:</p>
<ol>
<li><p>It temporarily wraps the primitive value in a wrapper object: <code>new String("Boltu")</code></p>
</li>
<li><p>This temporary object's <code>__proto__</code> automatically points to <code>String.prototype</code></p>
</li>
<li><p>The method is found in <code>String.prototype</code> and executed</p>
</li>
<li><p>After the operation completes, the wrapper object is discarded</p>
</li>
<li><p><code>yourName</code> returns to being a simple primitive value</p>
</li>
</ol>
<p>This is why you can use methods on primitives even though they're not objects. JavaScript creates a temporary object, uses it to access the method, then throws it away.</p>
<p>The same process happens with other primitive types:</p>
<ul>
<li><p>Numbers use <code>Number.prototype</code></p>
</li>
<li><p>Booleans use <code>Boolean.prototype</code></p>
</li>
</ul>
<p>And so on. This elegant system is why developers often say "everything in JavaScript is an object" – even when it's not technically true, it behaves that way when needed.</p>
<h2 id="heading-the-difference-between-proto-and-prototype">The Difference Between <code>__proto__</code> and <code>prototype</code></h2>
<p>This is one of the most confusing aspects of JavaScript for many developers. Let's break it down clearly.</p>
<h3 id="heading-what-is-prototype">What is <code>prototype</code>?</h3>
<p>When you create a function or class in JavaScript, the language automatically creates a blueprint object called <code>prototype</code>. This happens behind the scenes.</p>
<p>Here's an example:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Person</span>(<span class="hljs-params">name</span>) </span>{
  <span class="hljs-built_in">this</span>.name = name;
}
</code></pre>
<p>When JavaScript sees this function, it internally does this:</p>
<pre><code class="lang-javascript">Person.prototype = { 
  <span class="hljs-attr">constructor</span>: Person 
};
</code></pre>
<p>The <code>Person</code> function now has a hidden property called <code>prototype</code>, which is an object containing a <code>constructor</code> property.</p>
<p>You can add methods to this prototype object:</p>
<pre><code class="lang-javascript">Person.prototype.sayHi = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Hi, I'm "</span> + <span class="hljs-built_in">this</span>.name);
};
</code></pre>
<h3 id="heading-what-is-proto">What is <code>__proto__</code>?</h3>
<p><code>__proto__</code> is a property that exists on every object instance (arrays, functions, objects – everything). It's an internal reference or pointer that indicates which prototype the object inherits from.</p>
<p>By default, when you create an object, its <code>__proto__</code> points to <code>Object.prototype</code>.</p>
<h3 id="heading-how-they-work-together">How They Work Together</h3>
<p>When you use the <code>new</code> keyword:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> p1 = <span class="hljs-keyword">new</span> Person(<span class="hljs-string">"Shejan"</span>);
</code></pre>
<p>JavaScript performs these steps internally:</p>
<ol>
<li><p>Creates a new empty object: <code>p1 = {}</code></p>
</li>
<li><p>Sets the object's <code>__proto__</code>: <code>p1.__proto__ = Person.prototype</code></p>
</li>
<li><p>Calls the constructor function with the new object: <code>Person.call(p1, "Shejan")</code></p>
</li>
<li><p>Returns the object: <code>return p1</code></p>
</li>
</ol>
<p>Now when you try to access a method:</p>
<pre><code class="lang-javascript">p1.sayHi(); <span class="hljs-comment">// "Hi, I'm Shejan"</span>
</code></pre>
<p>JavaScript looks for <code>sayHi</code> in <code>p1</code> first. When it doesn't find it, it checks <code>p1.__proto__</code>, which points to <code>Person.prototype</code>, where the method is defined.</p>
<p>The relationship can be expressed as:</p>
<pre><code class="lang-javascript">p1.__proto__ === Person.prototype; <span class="hljs-comment">// true</span>
Person.prototype.constructor === Person; <span class="hljs-comment">// true</span>
</code></pre>
<p><strong>In summary:</strong></p>
<ul>
<li><p><code>prototype</code> is a property of functions/classes that serves as a blueprint for instances</p>
</li>
<li><p><code>__proto__</code> is a property of object instances that points to the prototype they inherit from</p>
</li>
</ul>
<h2 id="heading-how-prototypes-work-with-functions">How Prototypes Work with Functions</h2>
<p>Let's see a complete example with functions:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Person</span>(<span class="hljs-params">name, age</span>) </span>{
  <span class="hljs-built_in">this</span>.name = name;
  <span class="hljs-built_in">this</span>.age = age;
}

<span class="hljs-comment">// Adding a method to the prototype</span>
Person.prototype.introduce = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Hi, I'm <span class="hljs-subst">${<span class="hljs-built_in">this</span>.name}</span> and I'm <span class="hljs-subst">${<span class="hljs-built_in">this</span>.age}</span> years old.`</span>);
};

<span class="hljs-comment">// Creating instances</span>
<span class="hljs-keyword">const</span> person1 = <span class="hljs-keyword">new</span> Person(<span class="hljs-string">"Alice"</span>, <span class="hljs-number">25</span>);
<span class="hljs-keyword">const</span> person2 = <span class="hljs-keyword">new</span> Person(<span class="hljs-string">"Bob"</span>, <span class="hljs-number">30</span>);

person1.introduce(); <span class="hljs-comment">// "Hi, I'm Alice and I'm 25 years old."</span>
person2.introduce(); <span class="hljs-comment">// "Hi, I'm Bob and I'm 30 years old."</span>

<span class="hljs-comment">// Both instances share the same prototype</span>
<span class="hljs-built_in">console</span>.log(person1.__proto__ === Person.prototype); <span class="hljs-comment">// true</span>
<span class="hljs-built_in">console</span>.log(person2.__proto__ === Person.prototype); <span class="hljs-comment">// true</span>
<span class="hljs-built_in">console</span>.log(person1.__proto__ === person2.__proto__); <span class="hljs-comment">// true</span>
</code></pre>
<p>The key benefit here is memory efficiency: the <code>introduce</code> method exists only once in <code>Person.prototype</code>, but all instances can access it through the prototype chain.</p>
<h2 id="heading-how-prototypes-work-with-classes">How Prototypes Work with Classes</h2>
<p>ES6 introduced the <code>class</code> syntax, which looks different but works the same way under the hood:</p>
<pre><code class="lang-javascript"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">User</span> </span>{
  <span class="hljs-keyword">constructor</span>(name) {
    <span class="hljs-built_in">this</span>.name = name;
  }

  sayHi() {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Hi, I'm <span class="hljs-subst">${<span class="hljs-built_in">this</span>.name}</span>`</span>);
  }
}

<span class="hljs-keyword">const</span> user1 = <span class="hljs-keyword">new</span> User(<span class="hljs-string">"Charlie"</span>);
user1.sayHi(); <span class="hljs-comment">// "Hi, I'm Charlie"</span>

<span class="hljs-comment">// Let's check what's really happening</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-keyword">typeof</span> User); <span class="hljs-comment">// "function"</span>
<span class="hljs-built_in">console</span>.log(User.prototype); <span class="hljs-comment">// { sayHi: f, constructor: f User() }</span>
<span class="hljs-built_in">console</span>.log(user1.__proto__ === User.prototype); <span class="hljs-comment">// true</span>
</code></pre>
<p>Classes are essentially syntactic sugar over JavaScript's prototype-based inheritance. Internally:</p>
<ul>
<li><p>A class is still a constructor function</p>
</li>
<li><p>Methods defined in the class are added to <code>ClassName.prototype</code></p>
</li>
<li><p>Instances created with <code>new</code> have their <code>__proto__</code> set to the class's prototype</p>
</li>
</ul>
<p>This means everything we learned about function prototypes applies to classes as well.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Understanding prototypes and the prototype chain is fundamental to mastering JavaScript. These concepts form the foundation of how JavaScript implements inheritance and object-oriented programming.</p>
<h3 id="heading-key-takeaways">Key Takeaways</h3>
<p>Let's recap what we've learned:</p>
<ol>
<li><p><strong>Every object has</strong> <code>__proto__</code>: This property points to the prototype the object inherits from, enabling the prototype chain lookup mechanism.</p>
</li>
<li><p><strong>Functions and classes have</strong> <code>prototype</code>: This property serves as a blueprint for instances created with the <code>new</code> keyword.</p>
</li>
<li><p><strong>The prototype chain enables inheritance</strong>: When JavaScript can't find a property on an object, it walks up the prototype chain until it finds the property or reaches <code>null</code>.</p>
</li>
<li><p><strong>Primitives use wrapper objects</strong>: Even though primitives aren't objects, JavaScript temporarily wraps them in objects to provide access to methods.</p>
</li>
<li><p><strong>Classes are syntactic sugar</strong>: The modern <code>class</code> syntax is cleaner, but it still uses prototypes under the hood.</p>
</li>
</ol>
<p>JavaScript might seem quirky at first, but once you understand how it works under the hood, you'll appreciate its elegant and flexible design.</p>
<p>Happy coding!</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
