<?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"><channel><title><![CDATA[Sobit Prasad]]></title><description><![CDATA[Sobit Prasad]]></description><link>https://blogs.sobitprasad.com</link><generator>RSS for Node</generator><lastBuildDate>Sat, 16 May 2026 19:30:45 GMT</lastBuildDate><atom:link href="https://blogs.sobitprasad.com/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[I Built a Voice-Controlled Digital Twin of Myself (And You Can Talk to It!)]]></title><description><![CDATA[How It All Started
So here's the thing - I got tired of the same old portfolio websites. You know the ones: scroll, read, click, repeat. Boring.
I wanted something different. Something that would make people go "wait, what?" when they landed on my si...]]></description><link>https://blogs.sobitprasad.com/i-built-a-voice-controlled-digital-twin-of-myself-and-you-can-talk-to-it</link><guid isPermaLink="true">https://blogs.sobitprasad.com/i-built-a-voice-controlled-digital-twin-of-myself-and-you-can-talk-to-it</guid><category><![CDATA[Voice Activity Detection]]></category><category><![CDATA[Artificial Intelligence]]></category><category><![CDATA[Programming Tips]]></category><dc:creator><![CDATA[Sobit Prasad]]></dc:creator><pubDate>Mon, 10 Nov 2025 16:33:36 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1762792108982/bc8065bc-9537-4789-b4f6-d468b2681c6f.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-how-it-all-started"><strong>How It All Started</strong></h2>
<p>So here's the thing - I got tired of the same old portfolio websites. You know the ones: scroll, read, click, repeat. Boring.</p>
<p>I wanted something different. Something that would make people go "wait, what?" when they landed on my site. That's when I had this wild idea: what if people could just... talk to my portfolio? Like, actually have a conversation with it?</p>
<p>Fast forward a few weeks of research, and boom - I built a voice-interactive digital twin. Visitors can now chat with an AI version of me that knows everything about my projects, experience, and skills. No typing, no clicking buttons to record - just pure conversation.</p>
<p>In this article, I'll show you exactly how I built this thing, from the voice detection magic to the trippy visual effects that react to your voice. Spoiler alert: it involves machine learning, AI APIs, and some shader wizardry that would make your GPU sweat.</p>
<p><strong>What you're about to learn:</strong></p>
<ul>
<li><p>How Voice Activity Detection works (and why it's cooler than it sounds)</p>
</li>
<li><p>Building a complete voice conversation pipeline without losing your sanity</p>
</li>
<li><p>Making WebGL shaders dance to your voice</p>
</li>
<li><p>Real problems I ran into and how I fixed them</p>
</li>
<li><p>Why my API bills went up (worth it though)</p>
</li>
</ul>
<h2 id="heading-wait-whats-voice-activity-detection"><strong>Wait, What's Voice Activity Detection?</strong></h2>
<p>Before we dive in, let me explain VAD (Voice Activity Detection) because it's the secret sauce that makes everything work.</p>
<p>Imagine you're on a Zoom call and the app knows exactly when you're talking. It's not just listening for "loud noises" - it's actually smart enough to tell the difference between you saying "hello" and your dog barking in the background. That's VAD in action.</p>
<p>VAD uses machine learning models trained on tons of audio data to detect actual human speech vs everything else:</p>
<ul>
<li><p>Your mechanical keyboard clicking away</p>
</li>
<li><p>The ambulance siren outside</p>
</li>
<li><p>That Spotify playlist you forgot to pause</p>
</li>
<li><p>Your roommate yelling at their video game</p>
</li>
</ul>
<h3 id="heading-why-this-matters"><strong>Why This Matters</strong></h3>
<p>Here's the problem with traditional voice interfaces: they're annoying. You have to:</p>
<ol>
<li><p>Click a button to start recording</p>
</li>
<li><p>Say your thing</p>
</li>
<li><p>Click another button to stop</p>
</li>
<li><p>Hope you didn't forget to click</p>
</li>
</ol>
<p>It's like having to knock on someone's door, wait for them to answer, then knock again when you're done talking. Weird, right?</p>
<p>With VAD, the app just... knows. It hears you start talking, listens to what you say, and processes it when you're done. Hands-free. Magical. Just like talking to Alexa, but on a website.</p>
<h2 id="heading-the-tech-stack-aka-what-i-glued-together"><strong>The Tech Stack (AKA What I Glued Together)</strong></h2>
<p>Alright, let me show you the pipeline I built. It's basically a Rube Goldberg machine for voice, but it works beautifully:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1762665595863/03418ffd-6ded-4c79-a465-9896bc01d3be.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-the-tools-i-used-and-why"><strong>The Tools I Used (And Why)</strong></h3>
<div class="hn-table">
<table>
<thead>
<tr>
<td>What</td><td>Why I Picked It</td><td>The Real Reason</td></tr>
</thead>
<tbody>
<tr>
<td><strong>@ricky0123/vad-web</strong></td><td>Runs VAD in the browser</td><td>No backend needed = less infrastructure to babysit</td></tr>
<tr>
<td><strong>ONNX Runtime</strong></td><td>Runs ML models in browsers</td><td>Makes the VAD work its magic</td></tr>
<tr>
<td><strong>Google Gemini</strong></td><td>Speech-to-text + AI chat</td><td>One API for two jobs = I'm lazy (efficiently)</td></tr>
<tr>
<td><strong>ElevenLabs</strong></td><td>Voice synthesis</td><td>Makes my digital twin sound less robotic</td></tr>
<tr>
<td><strong>Three.js</strong></td><td>Fancy graphics</td><td>Because static backgrounds are so 2010</td></tr>
<tr>
<td><strong>Next.js 15</strong></td><td>Backend stuff</td><td>Server functions are chef's kiss</td></tr>
<tr>
<td><strong>React 19</strong></td><td>UI framework</td><td>Hooks make everything easier</td></tr>
</tbody>
</table>
</div><h2 id="heading-building-the-thing-the-fun-part"><strong>Building The Thing (The Fun Part)</strong></h2>
<p><strong>Step 1: Getting VAD to Work</strong><br />Setting up VAD was easier than I expected. Here's the basic setup:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> { useMicVAD } <span class="hljs-keyword">from</span> <span class="hljs-string">'@ricky0123/vad-react'</span>;

<span class="hljs-keyword">const</span> vad = useMicVAD({
  startOnLoad: <span class="hljs-literal">false</span>, <span class="hljs-comment">// Don't be creepy, wait for permission</span>

  <span class="hljs-comment">// These CDN links load the ML models</span>
  baseAssetPath: <span class="hljs-string">"https://cdn.jsdelivr.net/npm/@ricky0123/vad-web@0.0.27/dist/"</span>,
  onnxWASMBasePath: <span class="hljs-string">"https://cdn.jsdelivr.net/npm/onnxruntime-web@1.22.0/dist/"</span>,

  <span class="hljs-comment">// Fine-tuning the detection</span>
  positiveSpeechThreshold: <span class="hljs-number">0.5</span>,   <span class="hljs-comment">// "Yep, that's definitely speech"</span>
  negativeSpeechThreshold: <span class="hljs-number">0.35</span>,  <span class="hljs-comment">// "Nope, not speech anymore"</span>

  <span class="hljs-comment">// The cool part - event callbacks</span>
  onSpeechStart: <span class="hljs-function">() =&gt;</span> {
    setConversationState(<span class="hljs-string">'listening'</span>);
    <span class="hljs-comment">// Time to pay attention!</span>
  },

  onSpeechEnd: <span class="hljs-function">(<span class="hljs-params">audio: <span class="hljs-built_in">Float32Array</span></span>) =&gt;</span> {
    setConversationState(<span class="hljs-string">'thinking'</span>);
    <span class="hljs-comment">// Got your audio, now let me process it</span>
    <span class="hljs-keyword">const</span> audioBlob = float32ArrayToWavBlob(audio, <span class="hljs-number">16000</span>);
    processSpeechAudio(audioBlob, <span class="hljs-string">'vad'</span>);
  },

  onVADMisfire: <span class="hljs-function">() =&gt;</span> {
    setConversationState(<span class="hljs-string">'idle'</span>);
    <span class="hljs-comment">// False alarm, my bad</span>
  },
});
</code></pre>
<p><strong>The threshold thing:</strong> I set it to 0.5 to start listening and 0.35 to stop. This gap prevents the annoying flicker between "is talking" and "not talking" when you pause mid-sentence. Without it, every breath would trigger a stop. Trust me, I learned this the hard way.</p>
<h3 id="heading-step-2-making-visual-feedback-that-actually-responds"><strong>Step 2: Making Visual Feedback That Actually Responds</strong></h3>
<p>One of the coolest parts was making the UI react to your voice in real-time. I built a custom hook that calculates how loud you're talking:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">export</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">useVadEnergy</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> [vadEnergy, setVadEnergy] = useState(<span class="hljs-number">0</span>);
  <span class="hljs-keyword">const</span> [smoothedEnergy, setSmoothedEnergy] = useState(<span class="hljs-number">0</span>);

  <span class="hljs-keyword">const</span> vad = useMicVAD({
    startOnLoad: <span class="hljs-literal">false</span>,
    onSpeechEnd: <span class="hljs-function">(<span class="hljs-params">audio: <span class="hljs-built_in">Float32Array</span></span>) =&gt;</span> {
      <span class="hljs-comment">// Math time! Calculate how loud the audio is</span>
      <span class="hljs-keyword">let</span> sum = <span class="hljs-number">0</span>;
      <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; audio.length; i++) {
        sum += audio[i] * audio[i];
      }
      <span class="hljs-keyword">const</span> rms = <span class="hljs-built_in">Math</span>.sqrt(sum / audio.length);
      setVadEnergy(rms);
    },
    onVADMisfire: <span class="hljs-function">() =&gt;</span> setVadEnergy(<span class="hljs-number">0</span>),
  });

  <span class="hljs-comment">// Smooth out the values so animations don't look jerky</span>
  useEffect(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">const</span> interval = <span class="hljs-built_in">setInterval</span>(<span class="hljs-function">() =&gt;</span> {
      setSmoothedEnergy(<span class="hljs-function"><span class="hljs-params">prev</span> =&gt;</span> prev + (vadEnergy - prev) * <span class="hljs-number">0.2</span>);
    }, <span class="hljs-number">50</span>); <span class="hljs-comment">// Update 20 times per second</span>
    <span class="hljs-keyword">return</span> <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">clearInterval</span>(interval);
  }, [vadEnergy]);

  <span class="hljs-keyword">return</span> { vadEnergy: smoothedEnergy, vad };
}
</code></pre>
<p>This calculates something called RMS (Root Mean Square) energy, which is a fancy way of saying "how loud is this audio?" The smoothing part makes sure the animations don't spaz out when your voice volume changes suddenly.</p>
<h3 id="heading-step-3-audio-format-hell-fun-times"><strong>Step 3: Audio Format Hell (Fun Times)</strong></h3>
<p>Okay, this part wasn't actually fun. It was terrible. But I figured it out!</p>
<p>The VAD library gives you audio as a <code>Float32Array</code> (basically an array of decimal numbers), but Google Gemini wants a WAV file. So I had to write a converter:</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">float32ArrayToWavBlob</span>(<span class="hljs-params">float32Array: <span class="hljs-built_in">Float32Array</span>, sampleRate: <span class="hljs-built_in">number</span></span>): <span class="hljs-title">Blob</span> </span>{
  <span class="hljs-comment">// Create a buffer for the WAV file (44 bytes for header + audio data)</span>
  <span class="hljs-keyword">const</span> buffer = <span class="hljs-keyword">new</span> <span class="hljs-built_in">ArrayBuffer</span>(<span class="hljs-number">44</span> + float32Array.length * <span class="hljs-number">2</span>);
  <span class="hljs-keyword">const</span> view = <span class="hljs-keyword">new</span> <span class="hljs-built_in">DataView</span>(buffer);

  <span class="hljs-comment">// Helper to write strings into the buffer</span>
  <span class="hljs-keyword">const</span> writeString = <span class="hljs-function">(<span class="hljs-params">offset: <span class="hljs-built_in">number</span>, <span class="hljs-built_in">string</span>: <span class="hljs-built_in">string</span></span>) =&gt;</span> {
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-built_in">string</span>.length; i++) {
      view.setUint8(offset + i, <span class="hljs-built_in">string</span>.charCodeAt(i));
    }
  };

  <span class="hljs-comment">// WAV header stuff (this is standard WAV format)</span>
  writeString(<span class="hljs-number">0</span>, <span class="hljs-string">'RIFF'</span>);
  view.setUint32(<span class="hljs-number">4</span>, <span class="hljs-number">36</span> + float32Array.length * <span class="hljs-number">2</span>, <span class="hljs-literal">true</span>);
  writeString(<span class="hljs-number">8</span>, <span class="hljs-string">'WAVE'</span>);
  writeString(<span class="hljs-number">12</span>, <span class="hljs-string">'fmt '</span>);
  view.setUint32(<span class="hljs-number">16</span>, <span class="hljs-number">16</span>, <span class="hljs-literal">true</span>);
  view.setUint16(<span class="hljs-number">20</span>, <span class="hljs-number">1</span>, <span class="hljs-literal">true</span>);  <span class="hljs-comment">// PCM format</span>
  view.setUint16(<span class="hljs-number">22</span>, <span class="hljs-number">1</span>, <span class="hljs-literal">true</span>);  <span class="hljs-comment">// Mono</span>
  view.setUint32(<span class="hljs-number">24</span>, sampleRate, <span class="hljs-literal">true</span>);
  view.setUint32(<span class="hljs-number">28</span>, sampleRate * <span class="hljs-number">2</span>, <span class="hljs-literal">true</span>);
  view.setUint16(<span class="hljs-number">32</span>, <span class="hljs-number">2</span>, <span class="hljs-literal">true</span>);
  view.setUint16(<span class="hljs-number">34</span>, <span class="hljs-number">16</span>, <span class="hljs-literal">true</span>); <span class="hljs-comment">// 16-bit</span>
  writeString(<span class="hljs-number">36</span>, <span class="hljs-string">'data'</span>);
  view.setUint32(<span class="hljs-number">40</span>, float32Array.length * <span class="hljs-number">2</span>, <span class="hljs-literal">true</span>);

  <span class="hljs-comment">// Convert the float samples to 16-bit integers</span>
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; float32Array.length; i++) {
    <span class="hljs-keyword">const</span> s = <span class="hljs-built_in">Math</span>.max(<span class="hljs-number">-1</span>, <span class="hljs-built_in">Math</span>.min(<span class="hljs-number">1</span>, float32Array[i]));
    view.setInt16(<span class="hljs-number">44</span> + i * <span class="hljs-number">2</span>, s &lt; <span class="hljs-number">0</span> ? s * <span class="hljs-number">0x8000</span> : s * <span class="hljs-number">0x7FFF</span>, <span class="hljs-literal">true</span>);
  }

  <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Blob([buffer], { <span class="hljs-keyword">type</span>: <span class="hljs-string">'audio/wav'</span> });
}
</code></pre>
<p>Yeah, I know. It looks painful. Basically, I'm manually creating a WAV file header and converting floating-point audio to 16-bit integers. Took me way too long to get this right, but now it works perfectly.</p>
<h3 id="heading-step-4-the-three-stage-conversation-pipeline"><strong>Step 4: The Three-Stage Conversation Pipeline</strong></h3>
<p>Once I have the audio, it goes through three APIs:</p>
<p><strong>Stage 1: Speech → Text</strong></p>
<pre><code class="lang-typescript"><span class="hljs-keyword">export</span> <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">POST</span>(<span class="hljs-params">req: Request</span>) </span>{
  <span class="hljs-keyword">const</span> formData = <span class="hljs-keyword">await</span> req.formData();
  <span class="hljs-keyword">const</span> audioFile = formData.get(<span class="hljs-string">'audio'</span>) <span class="hljs-keyword">as</span> File;

  <span class="hljs-keyword">try</span> {
    <span class="hljs-comment">// Try Gemini first (it's faster)</span>
    <span class="hljs-keyword">const</span> genAI = <span class="hljs-keyword">new</span> GoogleGenerativeAI(process.env.GEMINI_API_KEY!);
    <span class="hljs-keyword">const</span> model = genAI.getGenerativeModel({ model: <span class="hljs-string">"gemini-2.5-flash"</span> });

    <span class="hljs-keyword">const</span> audioData = <span class="hljs-keyword">await</span> audioFile.arrayBuffer();
    <span class="hljs-keyword">const</span> base64Audio = Buffer.from(audioData).toString(<span class="hljs-string">'base64'</span>);

    <span class="hljs-keyword">const</span> result = <span class="hljs-keyword">await</span> model.generateContent([
      {
        inlineData: {
          mimeType: <span class="hljs-string">'audio/wav'</span>,
          data: base64Audio
        }
      },
      <span class="hljs-string">'Transcribe this audio to text. Return only the transcription.'</span>
    ]);

    <span class="hljs-keyword">return</span> NextResponse.json({ transcript: result.response.text().trim() });

  } <span class="hljs-keyword">catch</span> (error) {
    <span class="hljs-comment">// Gemini failed? No problem, Whisper to the rescue</span>
    <span class="hljs-keyword">const</span> openai = <span class="hljs-keyword">new</span> OpenAI({ apiKey: process.env.OPENAI_API_KEY });
    <span class="hljs-keyword">const</span> transcription = <span class="hljs-keyword">await</span> openai.audio.transcriptions.create({
      file: audioFile,
      model: <span class="hljs-string">'whisper-1'</span>,
    });
    <span class="hljs-keyword">return</span> NextResponse.json({ transcript: transcription.text });
  }
}
</code></pre>
<p>I use two providers because sometimes APIs have bad days. Gemini is faster, but if it fails, Whisper is super reliable.</p>
<p><strong>Stage 2: AI Chat Response</strong></p>
<p>This is where the "digital twin" part comes in. I built a knowledge base with all my info:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">export</span> <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">POST</span>(<span class="hljs-params">req: Request</span>) </span>{
  <span class="hljs-keyword">const</span> { message, sessionId } = <span class="hljs-keyword">await</span> req.json();

  <span class="hljs-comment">// Search my knowledge base for relevant info</span>
  <span class="hljs-keyword">const</span> relevantInfo = searchKnowledge(message);

  <span class="hljs-keyword">const</span> genAI = <span class="hljs-keyword">new</span> GoogleGenerativeAI(process.env.GEMINI_API_KEY!);
  <span class="hljs-keyword">const</span> model = genAI.getGenerativeModel({
    model: <span class="hljs-string">"gemini-2.5-flash"</span>,
    systemInstruction: <span class="hljs-string">`You are Sobit, a full-stack developer...

    VOICE MODE RULES (because nobody wants to hear a 5-minute response):
    - Keep it short - 2-4 sentences max
    - Aim for 15-30 seconds when spoken out loud
    - Be conversational, like you're chatting with someone
    - No bullet points (they sound weird when spoken)

    HERE'S WHAT'S RELEVANT:
    <span class="hljs-subst">${relevantInfo}</span>`</span>
  });

  <span class="hljs-keyword">const</span> result = <span class="hljs-keyword">await</span> model.generateContent(message);
  <span class="hljs-keyword">return</span> NextResponse.json({ response: result.response.text() });
}
</code></pre>
<p>The knowledge base (<code>portfolio-knowledge.ts</code>) is just a big JSON object with everything about me - projects, skills, experience, etc. When someone asks about my projects, the AI gets that context and can answer accurately.</p>
<h4 id="heading-stage-3-making-it-sound-human"><strong>Stage 3: Making It Sound Human</strong></h4>
<p>Finally, I turn the AI response into speech using ElevenLabs:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">export</span> <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">POST</span>(<span class="hljs-params">req: Request</span>) </span>{
  <span class="hljs-keyword">const</span> { text } = <span class="hljs-keyword">await</span> req.json();

  <span class="hljs-keyword">const</span> client = <span class="hljs-keyword">new</span> ElevenLabsClient({
    apiKey: process.env.ELEVENLABS_API_KEY
  });

  <span class="hljs-keyword">const</span> audio = <span class="hljs-keyword">await</span> client.textToSpeech.convert(
    process.env.ELEVENLABS_VOICE_ID!,
    {
      text,
      model_id: <span class="hljs-string">"eleven_turbo_v2_5"</span>,
      voice_settings: {
        stability: <span class="hljs-number">0.5</span>,        <span class="hljs-comment">// Not too robotic, not too wild</span>
        similarity_boost: <span class="hljs-number">0.5</span>,  <span class="hljs-comment">// Keep it consistent</span>
        style: <span class="hljs-number">0.0</span>,            <span class="hljs-comment">// Neutral tone</span>
        use_speaker_boost: <span class="hljs-literal">true</span> <span class="hljs-comment">// Make it clear</span>
      }
    }
  );

  <span class="hljs-comment">// Convert the audio stream to base64</span>
  <span class="hljs-keyword">const</span> chunks: <span class="hljs-built_in">Uint8Array</span>[] = [];
  <span class="hljs-keyword">for</span> <span class="hljs-keyword">await</span> (<span class="hljs-keyword">const</span> chunk <span class="hljs-keyword">of</span> audio) {
    chunks.push(chunk);
  }
  <span class="hljs-keyword">const</span> audioBuffer = Buffer.concat(chunks);
  <span class="hljs-keyword">const</span> base64Audio = audioBuffer.toString(<span class="hljs-string">'base64'</span>);

  <span class="hljs-keyword">return</span> NextResponse.json({
    audio: base64Audio,
    mimeType: <span class="hljs-string">'audio/mpeg'</span>
  });
}
</code></pre>
<p>The voice settings took some tweaking. Too much stability and it sounds like a robot. Too little and it sounds drunk. 0.5 is the sweet spot.</p>
<p><strong>Step 5: State Management (Keeping Track of What's Happening)</strong></p>
<p>I use a simple state machine to track the conversation:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">type</span> ConversationState = <span class="hljs-string">'idle'</span> | <span class="hljs-string">'listening'</span> | <span class="hljs-string">'thinking'</span> | <span class="hljs-string">'speaking'</span>;
</code></pre>
<p>The flow looks like this:</p>
<p>idle ──[you start talking]──► listening listening ──[you stop talking]──► thinking thinking ──[AI responds]──► speaking speaking ──[audio ends]──► idle (and back to listening)</p>
<p>Each state changes the UI colors, animations, and that glowing effect around the avatar. Makes it feel alive.</p>
<p><strong>The Visual Magic (AKA The Fun Stuff)</strong></p>
<p>The boring version would've been a static page with a microphone icon. But I wanted something that felt <em>reactive</em> - like the page was actually listening to you.</p>
<p><strong>1. The Trippy Background Shader</strong></p>
<p>I built a WebGL shader that creates this cloud-like effect that literally moves with your voice:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> fragmentShader = <span class="hljs-string">`
uniform float u_time;
uniform float u_voice_intensity;  // How loud you're talking (0-1)
uniform int u_conversation_state;  // What state we're in

// This creates organic, cloud-like patterns
float noise(vec2 p) {
  return fract(sin(dot(p, vec2(12.9898, 78.233))) * 43758.5453);
}

// Layer multiple noise patterns for complexity
float fbm(vec2 p) {
  float value = 0.0;
  float amplitude = 0.5;
  for(int i = 0; i &lt; 5; i++) {
    value += amplitude * noise(p);
    p *= 2.0;
    amplitude *= 0.5;
  }
  return value;
}

void main() {
  vec2 uv = vUv;
  vec2 p = uv * 3.0 + u_time * 0.1;

  // HERE'S THE COOL PART - your voice distorts the pattern
  float distortion = u_voice_intensity * 0.3;
  p.x += sin(p.y * 10.0 + u_time) * distortion;
  p.y += cos(p.x * 10.0 + u_time) * distortion;

  float clouds = fbm(p);
  float voiceReaction = smoothstep(0.3, 0.7, clouds + u_voice_intensity * 0.5);

  // Pick colors based on what's happening
  vec3 baseColor;
  if(u_conversation_state == 0) baseColor = u_color_idle;
  else if(u_conversation_state == 1) baseColor = u_color_listening;
  else if(u_conversation_state == 2) baseColor = u_color_thinking;
  else baseColor = u_color_speaking;

  // Add a glow in the center that gets brighter when you talk
  float centerGlow = 1.0 - length(uv - 0.5) * 2.0;
  centerGlow = pow(centerGlow, 2.0) * u_voice_intensity;

  vec3 finalColor = mix(baseColor, baseColor * 1.5, voiceReaction);
  finalColor += vec3(centerGlow * 0.3);

  gl_FragColor = vec4(finalColor, 1.0);
}`</span>
;
</code></pre>
<p>Every frame, I update the <code>u_voice_intensity</code> value based on your voice volume. The shader uses that to distort the cloud pattern. Louder voice = more distortion. It's mesmerizing to watch.</p>
<h3 id="heading-2-pulsing-circles-around-the-avatar"><strong>2. Pulsing Circles Around the Avatar</strong></h3>
<p>Three concentric circles that pulse and rotate:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> circles = [
  { delay: <span class="hljs-number">0</span>, scale: <span class="hljs-number">1</span> },
  { delay: <span class="hljs-number">3</span>, scale: <span class="hljs-number">1.1</span> },
  { delay: <span class="hljs-number">6</span>, scale: <span class="hljs-number">1.2</span> },
];

<span class="hljs-keyword">return</span> circles.map(<span class="hljs-function">(<span class="hljs-params">circle, i</span>) =&gt;</span> (
  &lt;motion.div
    key={i}
    className=<span class="hljs-string">"absolute rounded-full border-2"</span>
    animate={{
      scale: [<span class="hljs-number">1</span>, <span class="hljs-number">1.05</span> + (micVolume * <span class="hljs-number">0.4</span>), <span class="hljs-number">1</span>],  <span class="hljs-comment">// Breathes with your voice</span>
      opacity: [<span class="hljs-number">0.25</span>, <span class="hljs-number">0.5</span> + (micVolume * <span class="hljs-number">0.5</span>), <span class="hljs-number">0.25</span>],  <span class="hljs-comment">// Pulses</span>
      rotate: <span class="hljs-number">360</span>,  <span class="hljs-comment">// Spins continuously</span>
    }}
    transition={{
      duration: <span class="hljs-number">8</span> + i * <span class="hljs-number">3</span>,  <span class="hljs-comment">// Each circle rotates at different speeds</span>
      repeat: <span class="hljs-literal">Infinity</span>,
      ease: <span class="hljs-string">'easeInOut'</span>,
      delay: circle.delay,
    }}
  /&gt;
));
</code></pre>
<p>When you talk, they scale up. When you're quiet, they shrink. The colors change based on the conversation state:</p>
<ul>
<li><p>Green when listening</p>
</li>
<li><p>Yellow when thinking</p>
</li>
<li><p>Purple when speaking</p>
</li>
</ul>
<h3 id="heading-3-the-avatar-itself"><strong>3. The Avatar Itself</strong></h3>
<p>The profile picture scales and glows:</p>
<pre><code class="lang-typescript">&lt;motion.div
  animate={{
    scale: conversationState === <span class="hljs-string">'listening'</span> ? <span class="hljs-number">1.05</span> :
           conversationState === <span class="hljs-string">'speaking'</span> ? <span class="hljs-number">1.02</span> : <span class="hljs-number">1</span>,
    boxShadow: conversationState === <span class="hljs-string">'listening'</span>
      ? <span class="hljs-string">'0 0 50px rgba(59, 130, 246, 0.3)'</span>  <span class="hljs-comment">// Blue glow</span>
      : conversationState === <span class="hljs-string">'speaking'</span>
      ? <span class="hljs-string">'0 0 50px rgba(168, 85, 247, 0.3)'</span>  <span class="hljs-comment">// Purple glow</span>
      : conversationState === <span class="hljs-string">'thinking'</span>
      ? <span class="hljs-string">'0 0 50px rgba(234, 179, 8, 0.3)'</span>   <span class="hljs-comment">// Yellow glow</span>
      : <span class="hljs-string">'none'</span>,
  }}
&gt;
  &lt;Image src=<span class="hljs-string">"/sobit.jpg"</span> alt=<span class="hljs-string">"Avatar"</span> /&gt;
&lt;/motion.div&gt;
</code></pre>
<p>Simple but effective. The glow color tells you exactly what's happening without reading any text.</p>
<p><strong>Problems I Ran Into (And Fixed)</strong></p>
<p><strong>Problem 1: "Can I Use Your Mic?" Popup Hell</strong></p>
<p>Modern browsers won't let you access the microphone without a user action (good for privacy, annoying for UX). I had to add a big "Start Conversation" button that triggers the mic request:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> handleStart = <span class="hljs-keyword">async</span> () =&gt; {
  <span class="hljs-keyword">try</span> {
    <span class="hljs-keyword">await</span> vad.start();
    setIsListening(<span class="hljs-literal">true</span>);
  } <span class="hljs-keyword">catch</span> (error) {
    <span class="hljs-comment">// User said no or browser blocked it</span>
    <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Microphone access denied:'</span>, error);
  }
};
</code></pre>
<h3 id="heading-problem-2-why-is-there-a-5-second-delay"><strong>Problem 2: "Why Is There A 5 Second Delay?"</strong></h3>
<p>At first, the response time was terrible. Like 7-10 seconds bad. I fixed it by:</p>
<ul>
<li><p>Using Gemini 2.5 Flash (way faster than the regular model)</p>
</li>
<li><p>Telling the AI to keep responses short (2-4 sentences)</p>
</li>
<li><p>Using ElevenLabs Turbo v2.5 for faster voice generation</p>
</li>
</ul>
<p>Now it's 2-4 seconds from when you stop talking to when you hear the response. Much better.</p>
<h3 id="heading-problem-3-conversation-context"><strong>Problem 3: Conversation Context</strong></h3>
<p>APIs are stateless, which means each request is treated like a brand new conversation. The AI would forget what we just talked about. I fixed this with session-based caching:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> conversationCache = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Map</span>&lt;<span class="hljs-built_in">string</span>, Message[]&gt;();

<span class="hljs-keyword">export</span> <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">POST</span>(<span class="hljs-params">req: Request</span>) </span>{
  <span class="hljs-keyword">const</span> { message, sessionId } = <span class="hljs-keyword">await</span> req.json();

  <span class="hljs-comment">// Load previous messages</span>
  <span class="hljs-keyword">const</span> history = conversationCache.get(sessionId) || [];

  history.push({ role: <span class="hljs-string">'user'</span>, content: message });
  <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> generateResponse(history);
  history.push({ role: <span class="hljs-string">'assistant'</span>, content: response });

  <span class="hljs-comment">// Save for next time</span>
  conversationCache.set(sessionId, history);

  <span class="hljs-keyword">return</span> NextResponse.json({ response });
}
</code></pre>
<p>Now the AI remembers the whole conversation. In production, I'd use Redis or a database, but for now this works.</p>
<h3 id="heading-problem-4-mobile-phones-hate-me"><strong>Problem 4: Mobile Phones Hate Me</strong></h3>
<p>Running ONNX models and WebGL shaders on a phone made it laggy. Solution: detect mobile devices and simplify the effects:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> isMobile = <span class="hljs-regexp">/iPhone|iPad|iPod|Android/i</span>.test(navigator.userAgent);
<span class="hljs-keyword">const</span> shouldUseShaders = !isMobile &amp;&amp; <span class="hljs-built_in">window</span>.WebGL2RenderingContext;
</code></pre>
<p>Mobile users get simpler animations, desktop users get the full visual experience.</p>
<h2 id="heading-how-it-performs-in-the-real-world"><strong>How It Performs in the Real World</strong></h2>
<p>After launching this thing:</p>
<p><strong>VAD Accuracy:</strong></p>
<ul>
<li><p>95%+ accuracy detecting speech</p>
</li>
<li><p>Less than 5% false positives (usually from very loud noises)</p>
</li>
</ul>
<p><strong>Speed:</strong></p>
<ul>
<li><p>Speech end → Transcript: 1-2 seconds</p>
</li>
<li><p>Transcript → AI response: 0.5-1 second</p>
</li>
<li><p>Response → Audio playback: 1-2 seconds</p>
</li>
<li><p><strong>Total: 2.5-5 seconds</strong> (feels pretty instant)</p>
</li>
</ul>
<p><strong>User Engagement:</strong></p>
<ul>
<li><p>People stay 3x longer than on my old static portfolio</p>
</li>
<li><p>70% of visitors try the voice feature</p>
</li>
<li><p>Average 4-5 questions per session</p>
</li>
</ul>
<p><strong>Browser Support:</strong></p>
<ul>
<li><p>Works perfectly on Chrome, Firefox, Safari, Edge (desktop)</p>
</li>
<li><p>Works well on mobile Chrome and Safari (with reduced visuals)</p>
</li>
</ul>
<h2 id="heading-what-id-add-next"><strong>What I'd Add Next</strong></h2>
<p>I've got some ideas for v2:</p>
<ol>
<li><p><strong>Actual 3D Avatar with Lip Sync</strong></p>
<ul>
<li><p>Use Ready Player Me for a 3D model</p>
</li>
<li><p>Make it actually mouth the words</p>
</li>
<li><p>Add facial expressions</p>
</li>
</ul>
</li>
<li><p><strong>Emotion Detection</strong></p>
<ul>
<li><p>Analyze the tone of your voice</p>
</li>
<li><p>Adjust the AI's personality (sympathetic, excited, etc.)</p>
</li>
<li><p>Change the visual vibe to match</p>
</li>
</ul>
</li>
<li><p><strong>Multi-Language Support</strong></p>
<ul>
<li><p>Auto-detect what language you're speaking</p>
</li>
<li><p>Respond in the same language</p>
</li>
<li><p>ElevenLabs supports 29+ languages</p>
</li>
</ul>
</li>
<li><p><strong>Conversation Analytics</strong></p>
<ul>
<li><p>Track what people ask about most</p>
</li>
<li><p>See which projects get the most interest</p>
</li>
<li><p>Use it to improve the knowledge base</p>
</li>
</ul>
</li>
<li><p><strong>Voice Options</strong></p>
<ul>
<li><p>Let users pick from different voice styles</p>
</li>
<li><p>Adjust speed and personality</p>
</li>
<li><p>Make it more personalized</p>
</li>
</ul>
</li>
</ol>
<h2 id="heading-final-thoughts"><strong>Final Thoughts</strong></h2>
<p>Building this was one of the most fun projects I've done. It combines so many cool technologies - machine learning for VAD, AI for conversation, voice synthesis for speech, and WebGL for visuals.</p>
<p>A few years ago, this would've been impossible (or at least required a massive backend infrastructure). Now? Everything runs in the browser using modern web APIs and cloud services. The entire pipeline - from detecting your voice to playing a response - happens in seconds.</p>
<p>The craziest part? Most visitors don't even realize how complex it is. They just click "Start," ask a question, and get an answer. That's the dream - complex tech that feels simple and magical.</p>
<p>If you're thinking about adding voice features to your projects, I hope this gives you a starting point. VAD libraries like @ricky0123/vad-web make it way easier than building from scratch, and modern AI APIs are fast enough for real-time conversation.</p>
<p>The future of web interaction is conversational. The tools are ready. Go build something cool.</p>
<hr />
<h2 id="heading-resources-amp-links"><strong>Resources &amp; Links</strong></h2>
<p><strong>Try it yourself:</strong> <a target="_blank" href="http://sobitprasad.com/chat">sobitprasad.com/chat</a></p>
<p><strong>Tech I used:</strong></p>
<ul>
<li><p><a target="_blank" href="https://github.com/ricky0123/vad">@ricky0123/vad-web</a> - VAD library</p>
</li>
<li><p><a target="_blank" href="https://ai.google.dev/">Google Gemini</a> - AI brain</p>
</li>
<li><p><a target="_blank" href="https://elevenlabs.io/">ElevenLabs</a> - Voice synthesis</p>
</li>
<li><p><a target="_blank" href="https://threejs.org/">Three.js</a> - Graphics</p>
</li>
<li><p><a target="_blank" href="https://nextjs.org/">Next.js</a> - Framework</p>
</li>
<li><p><a target="_blank" href="https://www.framer.com/motion/">Framer Motion</a> - Animations</p>
</li>
</ul>
<p><strong>Useful reads:</strong></p>
<ul>
<li><p><a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia">WebRTC getUserMedia docs</a></p>
</li>
<li><p><a target="_blank" href="https://onnxruntime.ai/docs/tutorials/web/">ONNX Runtime Web</a></p>
</li>
<li><p><a target="_blank" href="https://thebookofshaders.com/">The Book of Shaders</a></p>
</li>
</ul>
<hr />
]]></content:encoded></item><item><title><![CDATA[How Asynchronous JavaScript Works: A Deep Dive into Its Execution Process]]></title><description><![CDATA[Overview
If you are an aspiring JavaScript developer, you will likely be asked whether JavaScript is synchronous or asynchronous.
And when you look around for the answers, you might get mixed answers for it. Some considered that JavaScript is synchro...]]></description><link>https://blogs.sobitprasad.com/how-asynchronous-javascript-works-a-deep-dive-into-its-execution-process</link><guid isPermaLink="true">https://blogs.sobitprasad.com/how-asynchronous-javascript-works-a-deep-dive-into-its-execution-process</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[javascript engine]]></category><category><![CDATA[Event Loop]]></category><category><![CDATA[callstack]]></category><category><![CDATA[JavaScript Runtime Environment]]></category><category><![CDATA[javascript ]]></category><dc:creator><![CDATA[Sobit Prasad]]></dc:creator><pubDate>Wed, 22 Mar 2023 07:28:50 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1678883766730/9b2aa249-25c9-4694-ac7d-0dae74917ca3.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-overview">Overview</h1>
<p>If you are an aspiring JavaScript developer, you will likely be asked whether JavaScript is synchronous or asynchronous.</p>
<p>And when you look around for the answers, you might get mixed answers for it. Some considered that JavaScript is synchronous while others say that it is asynchronous.</p>
<p>Then, what is the correct answer? Is it synchronous or asynchronous? Well, at its base JavaScript is synchronous but somehow it can be manipulated to work asynchronously.</p>
<p>But, how does it all happens? So, In this blog, we will dive deep and will try to understand how JavaScript is executed under the hood asynchronously.</p>
<h1 id="heading-understanding-synchronous-and-asynchronous">Understanding Synchronous and Asynchronous</h1>
<p>In JavaScript, both synchronous and asynchronous are different ways of executing the code.</p>
<h2 id="heading-synchronous">Synchronous</h2>
<p>Synchronous codes are executed in order, one statement at a time. Each statement must finish its execution before the next one is executed.</p>
<p>Think of it as a running race track, but only with one single track for all the athletes. Once the athlete at the very first reaches the finish line, then only the next athlete can start the race and so on.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1678358435868/3add72c4-1c79-4842-aecc-abbb46f3f839.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-asynchronous">Asynchronous</h2>
<p>Asynchronous codes are executed out of order, multiple statements at a time. All the statements can be executed parallelly.</p>
<p>Think of it as a regular running race track, each track for each athlete. Here, the athletes don't have to wait for the other athletes to start the race.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1678359015874/e61101a0-8506-43f5-8a03-f804ffea0ed9.png" alt class="image--center mx-auto" /></p>
<h1 id="heading-understanding-javascript-engine">Understanding JavaScript Engine</h1>
<p>JavaScript engines are programs that help in executing the JavaScript code. They are typically responsible for compiling the JavaScript code from human-readable to machine-readable instructions.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1678423651817/78c033f8-cf8c-4029-8767-af1ae40353b3.png" alt class="image--center mx-auto" /></p>
<p>There are several JavaScript Engines. Some of the most popular ones are :</p>
<ul>
<li><p><strong>V8</strong>: It was developed by Google for use in the Chrome browser and is also used in Node.js.</p>
</li>
<li><p><strong>SpiderMonkey</strong>: It was developed by Mozilla for use in Firefox.</p>
</li>
<li><p><strong>Chakra</strong>: It was developed by Microsoft for use in the Edge browser.</p>
</li>
</ul>
<h2 id="heading-how-javascript-engine-compiles-the-code">How JavaScript Engine Compiles the Code?</h2>
<p>JavaScript Engines have to go through multiple phases to compile the code from human-readable format to machine-readable format. So that, the computer can understand and executes the code.</p>
<p>When we give our code to JavaScript Engines, it has to go through - <em>parsing</em>, <em>compilation</em> and <em>execution</em>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1678434888387/da876979-74be-4a8e-a9fe-c7b331c22d3f.png" alt class="image--center mx-auto" /></p>
<blockquote>
<p>Every JavaScript Engine might have different algorithms to execute the code. However, the fundamentals of how JavaScript code is parsed, compiled, and executed are generally the same across different JavaScript engines.</p>
</blockquote>
<h3 id="heading-parsing-phase"><strong>Parsing Phase</strong></h3>
<p>During parsing, JavaScript Engines break down the code into its tokens such as keywords, identifiers, or operators. These tokens are used to form the Abstract Syntax Tree(AST) which is the high-level representation of the source code.</p>
<p>Let's take an example and see how it looks when it gets converted to Abstract Syntax Tree.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> hw = <span class="hljs-string">'hello world'</span>;
<span class="hljs-built_in">console</span>.log(hw);
</code></pre>
<p>The above code will be broken into individual tokens during a process called tokenization.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1678451410625/fcc5e515-cf83-4b47-bb56-a975851c4fad.png" alt class="image--center mx-auto" /></p>
<p>These tokens and the source code are then used to generate the Abstract Syntax Tree(AST).</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1678462514410/f14057f1-031d-40b6-8c10-a7dc2a3df004.png" alt class="image--center mx-auto" /></p>
<p>See Abstract Syntax Tree in JSON format below.</p>
<p><a target="_blank" href="https://gist.github.com/sobitp59/2edf4ade0a749dd5be9c2a5e4c118e16">open GitHub Gist</a></p>
<h3 id="heading-compilation-phase"><strong>Compilation Phase</strong></h3>
<p>During compilation, JavaScript Engine takes the Abstract Syntax Tree(AST) and turns it into low-level bytecode that the computer understands. Let's see how it does.</p>
<p>In the beginning, JavaScript Engines uses interpreters to compile the code. The interpreter makes debugging easier because it stops and updates whenever it finds an error. But the interpreter works slower as it has to translate the code line-by-line.</p>
<blockquote>
<p>An interpreter reads and executes the code line by line. As each line gets interpreted, it is executed by the computer, and the interpreter proceeds to the next line and so on.</p>
</blockquote>
<p>To overcome the interpreter's inefficiency, JavaScript Engines started using compilers along with interpreters. Compilers are fast but debugging the code was slower.</p>
<blockquote>
<p>A compiler translates the entire source code into machine language before it is executed.</p>
</blockquote>
<p>And this is what we called a Just-in-Time(JIT) compilation. JIT uses the best of both interpreter and compiler. JIT compilers make debugging easier because of the interpreter and faster because of compilers.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1678513512905/816dc117-8a21-491d-9e06-66c515897b99.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-execution-phase"><strong>Execution Phase</strong></h3>
<p>In most JavaScript engines, the compilation and execution of code happen concurrently and hand-in-hand, rather than in a strict sequential order.</p>
<p>As the code gets compiled, the JavaScript engine <strong>starts the execution</strong> before it has finished compiling the entire program and this is possible because of the JIT compiler.</p>
<p>In the execution phase, we have three important components - the <strong>call stack</strong>, the <strong>memory heap</strong> and the <strong>garbage collector</strong>. Let's understand each of them in the next section.</p>
<h2 id="heading-understanding-callstack-and-memory-management">Understanding CallStack and Memory Management</h2>
<p>When the code reaches the execution phase, it is the job of the call stack, memory heap and garbage collector to ensure that the programs run smoothly and efficiently.</p>
<p>So, what are their jobs, let's understand each of them.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1678557083645/0ffbfe07-bf79-42af-a98b-ce1ff2f29ad9.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-understanding-call-stack"><strong>Understanding Call Stack</strong></h3>
<p>When we say JavaScript is a <strong>single-threaded language</strong>, it means that it has only <strong>one call stack</strong>. The call stack can do only one thing at a time.</p>
<p>The job of the call stack is to track the execution context of a running program and it does by keeping track of all the functions that currently running.</p>
<p>It is based on Last-In-First-Out(LIFO) data structure, which means that the most recently called function is the first to be executed and the last to be completed.</p>
<p>So, whenever there’s a function call it gets pushed to the top of the stack. After it finishes executing it is removed from the top of the stack.</p>
<h3 id="heading-understanding-memory-management"><strong>Understanding Memory Management</strong></h3>
<p>JavaScript Engines manage the memory for us, removing the burden of explicitly allocating and deallocating memory unlike we do in other programming languages like C or C++. Let's understand in brief how JavaScript Engines manage memory.</p>
<p>The three phases of the memory life cycle are allocation, utilization, and deallocation.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1678630902792/1844ea98-5715-4d9d-b0ca-4b61835eeb9d.png" alt class="image--center mx-auto" /></p>
<ul>
<li><p><strong>allocation</strong>: reserving memory for a particular object or data structure.</p>
</li>
<li><p><strong>utilization</strong>: use of that memory by the program, which may involve reading from or writing to the memory.</p>
</li>
<li><p><strong>deallocation</strong>: releasing the memory when it is no longer needed, to make it available for other uses.</p>
</li>
</ul>
<p>JavaScript Engines can allocate memory in two places, either on the stack or a memory heap.</p>
<h3 id="heading-stack">Stack</h3>
<p>All the primitive values like <em>strings</em>, <em>numbers</em>, <em>booleans</em>, <em>undefined</em>, and <em>null</em> are stored on the stack.</p>
<p>When we pass a variable having primitive values as a reference to a new variable, a copy of the value is passed to the new variable. So, changing the value of the new variable will not affect the one that is passed as a reference.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1678713079160/d46a126a-8865-4af5-98f4-ec6fc30581b5.png" alt class="image--center mx-auto" /></p>
<p>In the above example,</p>
<ul>
<li><p>We have assigned <code>buy vegetables</code> (a primitive value) to variable <code>todoOne</code>.</p>
</li>
<li><p>Then we created another variable <code>todoTwo</code> and assigned it with the variable <code>todoOne</code>.</p>
</li>
<li><p>Here, the copy of the value of the variable <code>todoOne</code> i.e. <code>buy vegetables</code> is assigned to the variable <code>todoTwo</code>.</p>
</li>
<li><p>Then, we redeclared the variable <code>todoTwo</code> with <code>exercise : 500 skipping</code>. Here, re-declaring the variable <code>todoTwo</code> will not affect the variable <code>todoOne</code>.</p>
</li>
<li><p>So, when we consoled the variable <code>todoOne</code>, its value remained the same.</p>
</li>
</ul>
<h3 id="heading-memory-heap">Memory Heap</h3>
<p>All non-primitive values like arrays, objects or functions are first stored on the heap and then passed as a reference to the stack.</p>
<p>When we pass a variable having non-primitive values as a reference to a new variable, the reference of the memory location is passed to the new variable. So, changing the value of the new variable will also affect the one that is passed as a reference.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1678713120023/633e99e0-7ba8-4612-98d8-25af097c39c0.png" alt class="image--center mx-auto" /></p>
<p>In the above example,</p>
<ul>
<li><p>We have assigned an object (a non-primitive value) to variable <code>userOne</code>.</p>
</li>
<li><p>Then, we created another variable <code>userTwo</code> and assigned it to variable <code>userOne</code></p>
</li>
<li><p>Here, the reference of the variable <code>userOne</code> will be assigned and not a copy of it.</p>
</li>
<li><p>So, when we changed the property <code>name</code> of the variable <code>userTwo</code> , the property(<code>name</code>) of variable <code>userOne</code> also got changed.</p>
</li>
</ul>
<p>Now, we also need to de-allocate the memory that is not in use, and this is done by <strong>Garbage Collector</strong>. It works by periodically finding and removing the objects that are no longer referenced by the program.</p>
<p>Till now, we have only understood how JavaScript Engine works under the hood from parsing, compiling, and executing to memory management. But where does it all happen? And that's what we will be learning in the next section.</p>
<h1 id="heading-understanding-javascript-runtime-environment">Understanding JavaScript Runtime Environment</h1>
<p>As human beings, we need some environment to work effectively. For example, to study, we need a quiet environment, books, etc. To cook food we need a kitchen provided it has all the necessary items to cook food like gas stoves, groceries, water, etc.</p>
<p>It also applies to JavaScript Engine as well. JavaScript Engine cannot work independently, it needs some environment. And that environment is called <strong>JavaScript Runtime Environment(JRE)</strong> for JavaScript Engines.</p>
<p>JavaScript Runtime Environment(JRE) provides all the necessary components to JavaScript Engine so that it can work effectively. <strong>And you know what, it's the</strong> <strong>JRE only that manipulates JavaScript to work asynchronously</strong>.</p>
<p>First, let's discuss the important components of the JavaScript Runtime Environment and then we will discuss how these components work together with JavaScript Engine.</p>
<h2 id="heading-core-components-of-javascript-runtime-environment">Core Components of JavaScript Runtime Environment</h2>
<p>The core components of the JavaScript Runtime Environment(JRE) are JavaScript Engine itself, which we have discussed earlier and the <strong>Web APIs</strong>, <strong>microtask queue</strong>, <strong>callback queue</strong>, and the <strong>event loop</strong>. Let's discuss each of them.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1678883821415/955e2254-fd23-403d-bafd-c35ce86bdd6d.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-web-apis">Web APIs</h3>
<p>Web APIs are a set of built-in interfaces and functionalities provided by the Javascript Runtime Environment(JRE) to interact with external systems like servers, databases and other web services.</p>
<p>These Web APIs help in <strong>handling asynchronous operations</strong> like making a network request, processing large amounts of data, animating elements on a web page, etc.</p>
<p>There are several built-in interfaces and functionalities, let's discuss some of them.</p>
<ul>
<li><p><a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model">DOM API</a>: Document Object Model(DOM) API helps in accessing and manipulating the elements and attributes of an HTML or XML document in real-time.</p>
</li>
<li><p><a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/Console_API">Console API</a>: Console API helps in performing debugging tasks, such as logging messages or the values of variables at set points in your code, etc.</p>
</li>
<li><p><a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API">Fetch API</a>: Fetch API helps in making HTTP requests to retrieve resources from servers without blocking the main thread.</p>
</li>
<li><p><a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/setTimeout">setTimeOut</a>: This method allows us to schedule the execution of a function after a certain amount of time has passed.</p>
</li>
</ul>
<h3 id="heading-callback-queue-and-microtask-queue">Callback Queue and Microtask Queue</h3>
<p>A callback queue is a data structure that stores a queue of callback functions waiting to be executed. It is based on First-In-First-Out(FIFO) data structure which means the first in the queue will be the first to execute.</p>
<p>A microtask queue also stores a queue of callback functions waiting to be executed but the one with the <strong>higher priority</strong>. The callback functions with higher priority are the ones that came through <strong>Promises</strong>, <strong>mutation observer</strong>, <strong>queueMicrotask</strong>, etc.</p>
<h3 id="heading-event-loop">Event Loop</h3>
<p>Event Loop helps in executing the callback functions that are waiting on the callback queue. It does this by constantly checking the call stack and the event queues(callback queue and microtask queue).</p>
<p>The event loop checks if the call stack is empty or not and if it is then it checks if any callback functions are waiting to be executed in the callback queue or microtask queue.</p>
<p>And if there are any callback functions to be executed, it takes the first callback function from the queue and pushes it to the call stack.</p>
<p>The event loop then waits for the call stack to be emptied again so that it can push the next callback function in the queue. It does until all the callback functions are executed.</p>
<h2 id="heading-how-javascript-runtime-environment-works">How JavaScript Runtime Environment Works?</h2>
<p>So far, we have discussed and understood the JavaScript Engine and the core components of the JavaScript Runtime Environment(JRE). But how do all these work together? Let's find out with the help of an example.</p>
<blockquote>
<p><strong>Remember:</strong></p>
<ol>
<li><p>When the JavaScript Engine goes through the code, it first creates a <strong>Global Execution Context(GEC)</strong> and put it on the Call Stack. The global execution context includes information about the global scope, such as global variables and functions.</p>
</li>
<li><p>And whenever a function is invoked it creates a new <strong>Execution Context(FEC)</strong> for that function and put it on the Call Stack. The function execution context includes information about the local scope of the function, such as its arguments and local variables.</p>
</li>
<li><p>All synchronous operations must complete their execution before the asynchronous operation gets executed.</p>
</li>
</ol>
</blockquote>
<p>In the example below, we have defined four functions <code>greetUser()</code>, <code>delayedBy20ms()</code>, <code>getMovie()</code> and <code>letMeRun()</code>.</p>
<ul>
<li><p><code>greetUser()</code> function has a variable <code>message</code> assigned with <code>hello user! welcome to moviehub</code> and simply consoling the value.</p>
</li>
<li><p><code>delayedBy20ms()</code> function returning <code>setTimeOut</code> method to delay the execution by 20 milliseconds.</p>
<blockquote>
<p>Syntax of setTimeout:</p>
<p>setTimeout(callbackFunction, delayInMilliseconds);</p>
<ul>
<li><p><strong>callbackFunction</strong>- a function containing a block of code</p>
</li>
<li><p><strong>delayInMilliseconds</strong>- the time after which the function is executed</p>
</li>
</ul>
</blockquote>
</li>
<li><p><code>getMovie()</code> function is returning a promise that fetches some movies from the server.</p>
</li>
<li><p><code>greetUser()</code> function has a variable <code>run</code>assigned with value <code>let me run please!!</code> and it also simply consoling the value.</p>
</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greetUser</span>(<span class="hljs-params"></span>)</span>{
     <span class="hljs-keyword">const</span> message = <span class="hljs-string">'hello user! welcome to moviehub'</span>;                              
     <span class="hljs-built_in">console</span>.log(message); 
};

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">delayedBy20ms</span>(<span class="hljs-params"></span>)</span>{    
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {    
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'I will be print at least after 20 milliseconds!!'</span>)
    }, <span class="hljs-number">20</span>);
};

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getMovie</span>(<span class="hljs-params">movieName</span>)</span>{
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> {
        <span class="hljs-keyword">if</span>(movieName === <span class="hljs-string">'inception'</span>){
            resolve({<span class="hljs-attr">data</span> : <span class="hljs-string">'here is your movie from the server!'</span>})
        }<span class="hljs-keyword">else</span>{
            reject({<span class="hljs-attr">message</span> : <span class="hljs-string">'movie not found!!'</span>})
        }
    });
};

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">letMeRun</span>(<span class="hljs-params"></span>)</span>{
    <span class="hljs-keyword">const</span> run = <span class="hljs-string">'let me run please!!'</span>;
    <span class="hljs-built_in">console</span>.log(run);
};


greetUser();

delayedBy20ms();

getMovie(<span class="hljs-string">'inception'</span>)
.then(<span class="hljs-function">(<span class="hljs-params">response</span>) =&gt;</span> <span class="hljs-built_in">console</span>.log(response.data))
.catch(<span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> <span class="hljs-built_in">console</span>.log(error.message));

letMeRun();
</code></pre>
<h3 id="heading-phase-1-when-programs-execute-for-the-first-time"><strong>Phase 1: When programs execute for the first time</strong></h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1679294240364/38d0c7e2-996b-43c4-95f7-5a2347a5cc82.png" alt class="image--center mx-auto" /></p>
<p>Do you remember what will happen when JavaScript Engine goes through the code? Let's find out.</p>
<ol>
<li><p>So first, a Global Execution Context(GCE) is created and pushed in the Call Stack.</p>
</li>
<li><p>The Global Execution Context will hold information about all the functions' definitions and variables.</p>
</li>
<li><p>Also for each function, a function object is created and stored in the memory heap. This function object will contain the function's code and any variables declared within that function.</p>
</li>
</ol>
<h3 id="heading-phase-2-when-greetuser-function-is-invoked"><strong>Phase 2 : When greetUser() function is invoked</strong></h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1679407016401/be21372d-8efa-4fd4-92e4-d7f006533870.png" alt class="image--center mx-auto" /></p>
<p>After defining all the functions in the global execution context, now all these functions will execute when they are invoked. So, first, we are invoking <code>greetUser.</code> Let's understand what will happen when it gets invoked.</p>
<ol>
<li><p>First, an execution context of <code>greetUser</code> function will be created and pushed to the call stack. The execution context includes the variable <code>message</code> and value <code>hello user! welcome to moviehub</code>.</p>
</li>
<li><p><code>greetUser</code> function is consoling the variable <code>message</code>. It will be pushed into the call stack and tries to find the value of the variable in the execution context.</p>
</li>
<li><p>When it gets the value of <code>message</code>, it simply prints in the console.</p>
</li>
<li><p>Since <code>greetUser</code> function finishes its execution, its execution context will be destroyed.</p>
</li>
<li><p>Then, <code>greetUser</code> function is popped off from the call stack.</p>
</li>
</ol>
<p>Now the program moves to the next line of code.</p>
<h3 id="heading-phase-3-when-delayedby20ms-is-invoked">Phase 3: When delayedBy20ms() is invoked</h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1679407393918/1ea87984-0c00-4132-989b-23b682085694.png" alt class="image--center mx-auto" /></p>
<ol>
<li><p>When <code>delayedBy20ms</code> function is invoked, a new execution context is created and it will be pushed to the call stack. It is returning a <code>setTimeout</code> method.</p>
</li>
<li><p>When <code>setTimeout</code>method is invoked a new execution context for <code>setTimeout</code> is created and will also be pushed in the call stack. Inside the <code>setTimeout</code> execution context, we have a <strong>callback function</strong> and a <strong>timer</strong> of <strong>20 milliseconds</strong>, which says that the <code>setTimeout</code> method will be executed at least after 20 milliseconds.</p>
</li>
<li><p>Since <code>setTimeout</code> is an asynchronous operation provided by Web APIs, it will not execute immediately. So, the callback function and timer (20 ms) will be moved to Web APIs.</p>
</li>
<li><p>Meanwhile, the execution context of <code>setTimeout</code> will be destroyed.</p>
</li>
<li><p>Then <code>setTimeout</code> method will be popped off from the call stack.</p>
</li>
<li><p>Then the execution context of <code>delayedBy20ms</code> function will be destroyed.</p>
</li>
<li><p>And finally, <code>delayedBy20ms</code> pops off from the call stack.</p>
</li>
<li><p>Now, when the timer of 20ms expires the callback function moved to the callback queue</p>
</li>
<li><p>The event loop is continuously checking if there is any function in the callback queue ready to be executed. But the call stack is not emptied yet, so the callback function will wait in the callback queue till the call stack is empty.</p>
</li>
</ol>
<h3 id="heading-phase-4-when-getmovie-function-is-invoked">Phase 4: When getMovie() function is invoked</h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1679405324807/7bd90050-4f17-4cc0-9308-b8c28f20899d.png" alt class="image--center mx-auto" /></p>
<ol>
<li><p>Now <code>getMovie()</code> the function is invoked, a new execution context for it will be created and it will be pushed into the call stack. It holds the argument <code>movieName</code> and value <code>inception</code> and also it is returning a promise.</p>
</li>
<li><p>Since <code>getMovie</code> function is returning a <code>promise</code>, so when the promise executes a new execution context will be created and it will be pushed into the call stack. The execution context includes <code>value</code> which is initially <code>undefined</code>, <code>status</code> which is <code>pending</code> and function definitions when the promise is resolved and rejected.</p>
</li>
<li><p>As <strong>Promise</strong> is an asynchronous operation, it will be moved to Web API.</p>
</li>
<li><p>The execution context of <strong>Promise</strong> will be destroyed</p>
</li>
<li><p>And it will be popped off from the call stack.</p>
</li>
<li><p>Now the execution context of <code>getMovie</code> function will also be destroyed.</p>
</li>
<li><p>And then popped off from the call stack.</p>
</li>
<li><p>The <strong>Promise</strong> waits in the Web API till it gets a response from the server.</p>
</li>
<li><p>When it gets the response from the server <code>value</code> will be the data returned from the server, <code>status</code> changes to <code>resolved</code> from <code>pending</code>.</p>
</li>
<li><p>Based on whether the promise is resolved or rejected, a callback function is pushed into the microtask queue. In this case, the callback function is <code>(response) =&gt; console.log(response.data).</code></p>
<blockquote>
<p>Q. Why Promise is pushed into the microtask queue and setTimeout into the callback queue?</p>
<p>A. Because Promise has <strong>higher priority</strong> than setTimeout.</p>
</blockquote>
</li>
<li><p>The event loop is still checking if there is any task to be executed from the microtask or callback queue and also if the call stack is empty or not. Since the call stack is not emptied yet it cannot execute the callback functions that are ready to be executed.</p>
</li>
</ol>
<h3 id="heading-phase-5-when-letmerun-function-is-invoked">Phase 5: When letMeRun() function is invoked</h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1679405344407/da23d24b-e301-477b-bfe8-f8964fbe940d.png" alt class="image--center mx-auto" /></p>
<ol>
<li><p>When <code>letMeRun()</code> is invoked a new execution context will be created and pushed into the call stack. The execution context includes the variable <code>run</code> and its value <code>let me run!!.</code></p>
</li>
<li><p><code>letmMeRun</code> function calling the <code>console.log(run).</code> So it will be pushed into the call stack and tries to find the value of the variable <code>run</code> in the execution context.</p>
</li>
<li><p>When it gets the value from the execution context, the value will be printed on the console.</p>
</li>
<li><p>Now, the execution context of <code>letMeRun</code> function will be destroyed.</p>
</li>
<li><p>Then <code>letMeRun</code> function will be popped off from the call stack</p>
</li>
<li><p>Since there is nothing to execute anymore the global execution context will also be popped off from the call stack.</p>
</li>
</ol>
<h3 id="heading-phase-6-when-the-microtask-queue-executes">Phase 6: When the microtask queue executes</h3>
<p>Now we have one callback function(Promise) in the microtask queue and one callback function(setTimeout) in the callback queue.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1679405369262/1e289611-a42f-48c8-8ac8-c617118d5753.png" alt class="image--center mx-auto" /></p>
<ol>
<li><p>The event loop finds that the call stack is empty and also there is one callback function in the microtask queue and one callback function in the callback queue is ready to be executed.</p>
</li>
<li><p>Since the callback function(Promise) resides in the microtask queue have higher priority, therefore it will execute first.</p>
</li>
<li><p>When the callback function executes, a new execution context is created and pushed into the call stack. The execution context includes arguments <code>response</code> and value <code>{data : 'here is your movie from the server!'}</code>.</p>
</li>
<li><p>Now <code>console.log(response.data)</code> is invoked, it gets the value from the execution context.</p>
</li>
<li><p>The value <code>here is your movie from the server!</code> is printed on the console.</p>
</li>
<li><p>The execution context of the callback function is destroyed.</p>
</li>
<li><p>And finally popped off from the call stack.</p>
</li>
</ol>
<h3 id="heading-phase-7-when-the-callback-queue-executes">Phase 7: When the callback queue executes</h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1679405396319/e7d1c9e6-bec0-4b74-950e-6331d3328dbf.png" alt class="image--center mx-auto" /></p>
<ol>
<li><p>Again event loop finds that the call stack is empty and there is a task in the callback queue ready to be executed.</p>
</li>
<li><p>The callback function gets executed.</p>
</li>
<li><p>So, a new execution context is created. Then it is pushed into the call stack. The execution context includes an argument <code>1</code> and value <code>i will be print at least after 20 milliseconds!!</code>.</p>
</li>
<li><p>Now, console.log() is called, it gets the value from the execution context.</p>
</li>
<li><p>Then the is printed on the console.</p>
</li>
<li><p>The execution context of the callback function is destroyed.</p>
</li>
<li><p>And finally, the callback function is popped off from the call stack.</p>
</li>
</ol>
<h3 id="heading-the-output">The output</h3>
<p>After executing all the programs we get the output as :</p>
<pre><code class="lang-plaintext">hello user! welcome to moviehub
let me run please!!
here is your movie from the server!
i will be print at least after 20 milliseconds!!
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1679405452834/f6ef676b-30d4-484f-abdb-0881ada3dbf5.png" alt class="image--center mx-auto" /></p>
<p>Even though we have executed the code in the order below, we get the output in a different order, and this is how the JavaScript Runtime Environment gives an illusion of asynchronicity.</p>
<p>I hope now it makes sense to you whenever you get the output as the above one.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// ORDER OF INVOCATION OF THE FUNCTIONS</span>
greetUser(); <span class="hljs-comment">//1</span>

delayedBy20ms(); <span class="hljs-comment">//2</span>

getMovie(<span class="hljs-string">'inception'</span>) <span class="hljs-comment">//3</span>
.then(<span class="hljs-function">(<span class="hljs-params">response</span>) =&gt;</span> <span class="hljs-built_in">console</span>.log(response.data))
.catch(<span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> <span class="hljs-built_in">console</span>.log(error.message));

letMeRun(); <span class="hljs-comment">//4</span>
</code></pre>
<h1 id="heading-conclusion">Conclusion</h1>
<p>I know this was a long article but I hope you have read all the sections carefully. We learned a lot of things, aren't we? So let's quickly recap what we have learned so far.</p>
<ul>
<li><p>JavaScript at its base is synchronous, but with the help of <strong>JavaScript Runtime Environment(JRE),</strong> it can work asynchronously.</p>
</li>
<li><p>Every browser has a JavaScript Engine, and the runtime environment is the browser itself.</p>
</li>
<li><p>JavaScript Engine helps in parsing, compiling and executing the code.</p>
<ul>
<li><p>During parsing, code breaks down into small tokens and it gets converted to Abstract Syntax Tree(AST).</p>
</li>
<li><p>During compilation, the AST is converted into the bytecode.</p>
</li>
<li><p>During execution, JavaScript Engine executes the code as the code gets compiled.</p>
</li>
</ul>
</li>
<li><p>We don't need to worry about memory management in JavaScript.</p>
<ul>
<li><p>JavaScript Engine takes care of all these, from allocation to utilization to de-allocation.</p>
</li>
<li><p>All the primitive values like <em>strings</em>, <em>numbers</em>, <em>booleans</em>, <em>undefined</em>, and <em>null</em> are stored on the stack.</p>
</li>
<li><p>All non-primitive values like arrays, objects or functions are first stored on the heap</p>
</li>
</ul>
</li>
<li><p>The core components of the JavaScript Runtime Environment are:</p>
<ul>
<li><p>Web APIs: it helps in interacting with external systems like servers, databases, etc.</p>
</li>
<li><p>Microtask Queue: it stores a queue of callback functions waiting to be executed with a higher priority.</p>
</li>
<li><p>Callback Queue: it stores a queue of callback functions waiting to be executed after the microtask queue becomes empty.</p>
</li>
<li><p>Event Loop: it helps in executing the callback functions that are waiting on the callback queue by constantly checking if the call stack is empty or not.</p>
</li>
</ul>
</li>
</ul>
<p>While writing this article I came to know about so many amazing things and my love for JavaScript increases even more. I hope this article helped you too to understand how Asynchronous JavaScript works under the hood.</p>
<p>Additionally, I welcome your feedback. If you come across any areas that require correction or you just want to connect, feel free to contact me via email at sobitwrites@gmail.com.</p>
<hr />
<p><strong>References and Useful Resources</strong>:</p>
<ul>
<li><p><a target="_blank" href="https://www.youtube.com/watch?v=fOdcuDigxfw">JavaScript the Hard Parts by CodeSmith</a></p>
</li>
<li><p><a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API">JavaScript Web APIs</a></p>
</li>
<li><p><a target="_blank" href="https://www.youtube.com/watch?v=svJerixawV0">JIT Compiler by Programming With Avelx</a></p>
</li>
<li><p><a target="_blank" href="https://felixgerschau.com/javascript-memory-management/">JavaScript's Memory Management Explained by Felix Gerschau</a></p>
</li>
<li><p><a target="_blank" href="https://astexplorer.net/">Abstract Syntax Tree(AST) viewer</a></p>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Understanding Var, Let and Const in JavaScript with Examples]]></title><description><![CDATA[Overview
Unlike other programming languages, like Java and C++ where we need to specify the type of variables while declaring, it is somewhat different in JavaScript.
JavaScript limits us to declare variables only using these three keywords - the var...]]></description><link>https://blogs.sobitprasad.com/understanding-var-let-and-const-in-javascript-with-examples</link><guid isPermaLink="true">https://blogs.sobitprasad.com/understanding-var-let-and-const-in-javascript-with-examples</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[temporal-dead-zone]]></category><category><![CDATA[hosting]]></category><dc:creator><![CDATA[Sobit Prasad]]></dc:creator><pubDate>Wed, 01 Mar 2023 07:27:54 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1677393252289/40480aee-f4be-464e-85df-19867f340781.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-overview">Overview</h2>
<p>Unlike other programming languages, like Java and C++ where we need to specify the type of variables while declaring, it is somewhat different in JavaScript.</p>
<p>JavaScript limits us to declare variables only using these three keywords - the <em>var</em>, the <em>let</em> and the <em>const</em>. Also, we do not need to specify the type of variables while declaring it.</p>
<p>And even though, having only three ways of defining variables most beginners find it difficult to digest them.</p>
<p>In this blog, we'll explore var, let, and const through various examples and will try to understand the differences between them.</p>
<h2 id="heading-a-brief-history-of-variables-in-javascript">A Brief History of Variables in JavaScript</h2>
<p>Until EcmaScript2015(ES6), we were only declaring variables using the <em>var</em> keyword.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1677384254482/c40ed66f-e769-49fc-8844-72cf556e2885.png" alt class="image--center mx-auto" /></p>
<p>With the introduction of ES6 in June 2015, the <em>let</em> and <em>const</em> came into existence and were considered the best practice to declare variables in modern JavaScript.</p>
<h2 id="heading-what-is-a-variable">What is a Variable?</h2>
<p>A variable is a named storage location that holds some value pointing to some memory location in the computer's memory, that we can use later to manipulate our programs.</p>
<p>Think of it like you are giving a name to some location in the computer's memory. This memory location can be used to store the value you wanted.</p>
<p>Later, if you need the value you have stored, you can simply use the name you have given to that memory location.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1677304507248/9c15ddf5-08ff-4a0e-85a2-e59f2dd5b882.png" alt class="image--center mx-auto" /></p>
<p>From the above figure, you can see we have three variables <code>var1</code>, <code>var2</code> and <code>var3</code> stored in memory locations 1, 3 and 5 with assigned values of <code>hello world</code>, <code>{....}</code> and <code>121432</code> respectively.</p>
<p>Now, whenever we need these values we can simply use the names we have assigned to those memory locations.</p>
<h2 id="heading-understanding-var-and-let">Understanding Var and Let</h2>
<p>We know that both var and let are used to declare variables, but there are some important differences that we need to consider.</p>
<p>We will measure the differences in terms of their <em>declaration</em>, <em>scoping</em> and <em>hoisting.</em> So, let's discuss each of them in detail with examples.</p>
<h3 id="heading-var-is-re-declarable-while-let-is-not">var is re-declarable while let is not</h3>
<p>When we declare a variable using <em>var</em>, we can re-declare that variable in the same scope multiple times.</p>
<blockquote>
<p>re-declaration refers to declaring a variable with the same name multiple times within the same scope.</p>
</blockquote>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> greetUser = <span class="hljs-string">'good morning!'</span>;
<span class="hljs-keyword">var</span> greetUser = <span class="hljs-string">'good afternoon!'</span>;
<span class="hljs-built_in">console</span>.log(greetUser); <span class="hljs-comment">// good afternoon!</span>
</code></pre>
<p>In the above example, you can see we have two variables <code>greetUser</code> with the same name. The second <code>greetUser</code> overwrites the value of the first, so we get the output as <code>good afternoon!</code> .</p>
<p>This is not in the case of variables declared with <em>let</em>. This means, re-declaration is not allowed for variables declared using <em>let</em>. We will get a syntax error if we do so.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> greetUser = <span class="hljs-string">'good morning!'</span>;
<span class="hljs-keyword">let</span> greetUser = <span class="hljs-string">'good afternoon!'</span>;
<span class="hljs-built_in">console</span>.log(greetUser); 
<span class="hljs-comment">// SyntaxError: Identifier 'greetUser' has already been declared</span>
</code></pre>
<p>However, we can re-initialize a variable declared using both with var and let multiple times in the same scope.</p>
<blockquote>
<p>re-initialization refers to assigning a new value to a variable that has already been declared and initialized within the same scope.</p>
</blockquote>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> greetUser = <span class="hljs-string">'good morning!'</span>;
greetUser = <span class="hljs-string">'good afternoon!'</span>;
<span class="hljs-built_in">console</span>.log(greetUser); <span class="hljs-comment">// good afternoon!</span>
</code></pre>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> greetUser = <span class="hljs-string">'good morning!'</span>;
greetUser = <span class="hljs-string">'good afternoon!'</span>;
<span class="hljs-built_in">console</span>.log(greetUser); <span class="hljs-comment">// good afternoon!</span>
</code></pre>
<p>Also, even if we remove the keywords var and let from the above examples, we will get the same output.</p>
<pre><code class="lang-javascript">greetUser = <span class="hljs-string">'good afternoon!'</span>;
<span class="hljs-built_in">console</span>.log(greetUser); <span class="hljs-comment">// good afternoon!</span>
</code></pre>
<p>This is because when we use a variable without explicitly declaring with keywords var or let, it is automatically created as a global variable. However, it is not possible in <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode">strict mode</a>, we will get a reference error.</p>
<pre><code class="lang-javascript"><span class="hljs-meta">"use strict"</span>;
greetUser = <span class="hljs-string">'good afternoon!'</span>;
<span class="hljs-built_in">console</span>.log(greetUser);
<span class="hljs-comment">// ReferenceError: greetUser is not defined</span>
</code></pre>
<h3 id="heading-var-is-function-scoped-while-let-is-block-scoped">var is function-scoped while let is block-scoped</h3>
<p>In JavaScript, scoping is used to determine the availability or visibility of a variable in a particular part of a program, based on where it is declared.</p>
<p>There are primarily four types of scopes in JavaScript - global, functional, block and module scope. We will discuss only the first three.</p>
<ul>
<li><p><strong>global scope</strong> - a variable declared outside any function or block(inside curly braces <strong>{}</strong>) can be said to be in the global scope. It is visible or accessible throughout the whole program.</p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1677434211932/2181fde1-2f4f-4460-9bf7-f267f5bc3330.png" alt class="image--center mx-auto" /></p>
<pre><code class="lang-javascript">  <span class="hljs-keyword">var</span> varA = <span class="hljs-string">'I am in global scope'</span>;
  <span class="hljs-keyword">let</span> letA = <span class="hljs-string">'hey, I am too in global scope'</span>;

  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">printData</span>(<span class="hljs-params"></span>)</span>{
      <span class="hljs-built_in">console</span>.log(varA);
      <span class="hljs-built_in">console</span>.log(letA);
  };
  printData();
  <span class="hljs-comment">// I am in global scope</span>
  <span class="hljs-comment">// hey, I am too in global scope</span>
</code></pre>
<p>  In the above code, variables <code>varA</code> and <code>letA</code> both are in the global scope and can be accessed inside any function and block.</p>
</li>
<li><p><strong>function scope</strong> - variables declared using the <em>var</em> keyword are functionally scoped. This means, if we declare a variable inside a function it will be accessible inside that function only.</p>
<p>  The accessibility of variables declared using <em>var</em> inside a function is limited to that function only.</p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1677434248785/90875844-016e-48a1-8b27-b8ee9bf34a14.png" alt class="image--center mx-auto" /></p>
<pre><code class="lang-javascript">  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">printData</span>(<span class="hljs-params"></span>)</span>{
      <span class="hljs-keyword">var</span> favoriteBook = <span class="hljs-string">'the happiness hypothesis'</span>;
      <span class="hljs-built_in">console</span>.log(favoriteBook); 
  };
  printData(); <span class="hljs-comment">// the happiness hypothesis</span>
  <span class="hljs-built_in">console</span>.log(favoriteBook); <span class="hljs-comment">// ReferenceError: favouriteBook is not defined</span>
</code></pre>
<p>  We will get a reference error from the second console because we are trying to access the variable <code>favouriteBook</code>, which is defined inside the function <code>printData</code>.</p>
</li>
<li><p><strong>block scope</strong> - variables declared using the <em>let</em> keyword have block scope. This means that if we declare a variable inside any block(block refers to curly braces <strong>{}</strong>), we will not be able to access that variable outside that block.</p>
<p>  The accessibility of variables declared using <em>let</em> inside a block is limited to that block only.</p>
<p>  <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1677434297860/549326cd-3077-4e07-9473-397f9edaef24.png" alt class="image--center mx-auto" /></p>
<pre><code class="lang-javascript">   <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">printSomething</span>(<span class="hljs-params"></span>) </span>{
      <span class="hljs-keyword">let</span> x = <span class="hljs-number">10</span>;
      <span class="hljs-keyword">if</span> (<span class="hljs-literal">true</span>) {
        <span class="hljs-keyword">let</span> y = <span class="hljs-number">20</span>;
        <span class="hljs-built_in">console</span>.log(x); <span class="hljs-comment">// 10</span>
        <span class="hljs-built_in">console</span>.log(y); <span class="hljs-comment">// 20</span>
      }
      <span class="hljs-built_in">console</span>.log(x); <span class="hljs-comment">// 10</span>
      <span class="hljs-built_in">console</span>.log(y); <span class="hljs-comment">// ReferenceError: y is not defined</span>
  };
  printSomething();
</code></pre>
<p>  In the above example, we have declared two variables, <code>x</code> inside function <code>printSomething</code> and <code>y</code> inside the <code>if</code> block which again is inside the <code>printSomething</code> function only.</p>
<p>  The scope of the variable <code>x</code> is the whole <code>printSomething</code> function, while the scope of the variable <code>y</code> is limited only to the <code>if</code> block.</p>
<p>  So, when we tried to access the variable <code>y</code> (<code>console.log(y);</code>) at the very end of the function <code>printSomething</code> we get a reference error.</p>
</li>
</ul>
<h3 id="heading-var-and-let-both-are-hoisted">var and let both are hoisted?</h3>
<p>Hoisting is a mechanism that is used to move the variable and function declarations to the top of their respective scope before the code is executed.</p>
<p>However, the code doesn't actually re-arrange, but the JavaScript Engine finds the variables and functions and reserves memory for them before the code gets executed.</p>
<p>By default, variables get initialized with a value of <em>undefined</em> and in the case of functions, an actual copy of the functions is allocated.</p>
<p>And that's the reason when we run the code below, we get undefined and the function gets executed without any error.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(varA);
print();

<span class="hljs-keyword">var</span> varA = <span class="hljs-string">'hello shipper!'</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">print</span>(<span class="hljs-params"></span>)</span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'hello builder!'</span>)
};
<span class="hljs-comment">// undefined</span>
<span class="hljs-comment">// hello builder!</span>
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1677582919691/6d9b8263-610e-4220-9d86-0f5eb0040361.png" alt class="image--center mx-auto" /></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1677582969506/5a9dfb0a-c7d0-40d8-bb78-8073117655f1.png" alt class="image--center mx-auto" /></p>
<p>Till now, we have been only discussing the functions and variables declared using <em>var</em>. But, what if we declared it using <em>let</em>? Will we get <em>undefined</em> or it will be an error? Are the variables declared using <em>let</em> hoisted?</p>
<p>And many questions might come to your mind. So, let's try to find the answers to all the questions above.</p>
<p>First, let's try to find whether variables declared using <em>let</em> are hoisted or not. Well, some say that <em>let</em> is hoisted while others deny it. This argument is fine since hoisting is not a globally agreed term.</p>
<p>However, variables declared using <em>let</em> show behavioural characteristics of hoisting. It's too get allocated with a default value of <em>undefined</em> in the memory.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(letA);
<span class="hljs-keyword">let</span> letA = <span class="hljs-string">'hello shipper!'</span>;
<span class="hljs-comment">//ReferenceError : Cannot access 'letA' before initialization</span>
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1677593660689/0f6a5699-7c81-400f-8fd1-3ca488594279.png" alt class="image--center mx-auto" /></p>
<p>If it is already allocated with a default value of undefined, then why did we get the error? And this is where <strong>Temporal Dead Zone</strong> comes in.</p>
<p>A variable declared using <em>let</em> is said to be in a "temporal dead zone" (TDZ) from the start of the block until code execution reaches the line where the variable is declared and initialized.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(letA); <span class="hljs-comment">// I am in Temporal Dead Zone</span>

<span class="hljs-keyword">let</span> letA = <span class="hljs-string">'hello shipper!'</span>

<span class="hljs-keyword">if</span>(<span class="hljs-literal">true</span>){
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'hello batman!'</span>);
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'hello spiderman!'</span>);
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'hello superman!'</span>);

    <span class="hljs-built_in">console</span>.log(shaktiman); <span class="hljs-comment">// I am too in Temporal Dead Zone</span>
    <span class="hljs-keyword">let</span> shaktiman = <span class="hljs-string">'hello shaktiman'</span>;
}
</code></pre>
<p>In the above example, both <code>console.log(letA);</code> and <code>console.log(shaktiman);</code> are in the temporal dead zone.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1677645840046/94ef6bf3-1769-41de-b25e-d439629a4ad1.png" alt class="image--center mx-auto" /></p>
<p>The TDZ for variable <code>letA</code> starts from the very top and ends on the line where it is declared and initialized. While the TDZ for the variable <code>shaktiman</code> starts from the top of the <code>if</code> block and ends where it is declared and initialized.</p>
<p>If we will try to access those variables in their temporal dead zone(TDZ) then it will result in a reference error.</p>
<h2 id="heading-understanding-const">Understanding Const</h2>
<p>The reason I didn't talk about variables declared using <em>const</em> earlier was that it works almost like variables declared using <em>let</em>, with some slight key differences. So, let's discuss each of them.</p>
<h3 id="heading-initialization">Initialization</h3>
<p>We can declare a variable with <em>let</em> without an initial value and can assign it later. But it is not possible with variables declared using <em>const</em>. It must be initialized with a value when they are declared.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Allowed ✅</span>
<span class="hljs-keyword">let</span> letA;
letA = <span class="hljs-string">'hello shipper!'</span>;

<span class="hljs-comment">// Not Allowed ❌</span>
<span class="hljs-keyword">const</span> constA;
constA = <span class="hljs-string">'hello builder'</span>;
<span class="hljs-comment">// SyntaxError: Missing initializer in const declaration</span>
</code></pre>
<h3 id="heading-mutability">Mutability</h3>
<p>We can mutate a variable declared using <em>let</em> while variables declared using <em>const</em> are immutable, meaning that their values cannot be changed after they are initialized.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Allowed ✅</span>
<span class="hljs-keyword">let</span> letA = <span class="hljs-string">'hello shipper!'</span>;
letA = <span class="hljs-string">'hello earth!'</span>;

<span class="hljs-comment">// Not Allowed ❌</span>
<span class="hljs-keyword">const</span> constA = <span class="hljs-string">'hello builder'</span>;
constA = <span class="hljs-string">'hello mars!'</span>;
<span class="hljs-comment">// TypeError: Assignment to constant variable.</span>
</code></pre>
<h3 id="heading-scope">Scope</h3>
<p>Variables declared using <em>const</em> have the same block scope as variables declared using <em>let</em>. However, variables declared using <em>const</em> have a more restrictive scope than variables declared using <em>let</em>.</p>
<p>We can neither redeclare nor we can re-assign variables declared using const within the same block, although variables declared using let can be re-assigned but cannot be re-declared within the same block.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">if</span>(<span class="hljs-literal">true</span>){
    <span class="hljs-keyword">let</span> iWantToBe = <span class="hljs-string">'an astronaut'</span>;
    iWantToBe = <span class="hljs-string">'a web developer'</span>; <span class="hljs-comment">// Allowed ✅</span>

    <span class="hljs-keyword">const</span> youWantToBe = <span class="hljs-string">'a doctor'</span>;
    youWantToBe = <span class="hljs-string">'a soldier'</span>; <span class="hljs-comment">// Not Allowed ❌</span>
}
</code></pre>
<h2 id="heading-reason-for-introducing-let-and-const">Reason for introducing let and const</h2>
<p>We have been declaring variables using <em>var</em> for almost 20 years, then why there was a need of introducing let and const? Some of them we have already discussed above by comparing with var. Let's discuss a few more and then we can conclude this post.</p>
<h3 id="heading-naming-collision">Naming collision</h3>
<p>As we know that variables declared using var are re-declarable in the same scope, which leads to naming collision. This can be prevented if we will use let or const as re-declaration is not allowed with let and const is even stricter than let.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Allowed ✅</span>
<span class="hljs-keyword">var</span> favoriteAnimeName = <span class="hljs-string">'naruto'</span>;
<span class="hljs-keyword">var</span> favoriteAnimeName = <span class="hljs-string">'deathnote'</span>; 

<span class="hljs-comment">// Not Allowed ❌</span>
<span class="hljs-keyword">let</span> favoriteAnimeName = <span class="hljs-string">'naruto'</span>;
<span class="hljs-keyword">let</span> favoriteAnimeName = <span class="hljs-string">'deathnote'</span>; 

<span class="hljs-comment">// Not Allowed ❌</span>
<span class="hljs-keyword">const</span> favoriteAnimeName = <span class="hljs-string">'naruto'</span>;
<span class="hljs-keyword">const</span> favoriteAnimeName = <span class="hljs-string">'deathnote'</span>;
</code></pre>
<h3 id="heading-memory-save">Memory save</h3>
<p>If we declare variables using let and const they can help to save memory by limiting the scope of variables to only the blocks where they are needed, and by allowing for the re-use of variable names within different blocks of code.</p>
<p>This can help to ensure that memory is used efficiently and not wasted on variables that are no longer needed.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">calculate</span>(<span class="hljs-params">numbers1, numbers2</span>) </span>{
    <span class="hljs-keyword">let</span> total = <span class="hljs-number">0</span>; <span class="hljs-comment">// declare and initialize ⚡ 'total' variable</span>

    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> number <span class="hljs-keyword">of</span> numbers1) {
      total += number;
    }
    <span class="hljs-built_in">console</span>.log(total);

    {
      <span class="hljs-keyword">let</span> total = <span class="hljs-number">0</span>; <span class="hljs-comment">// declare and initialize new ✨ 'total' variable</span>
      <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> number <span class="hljs-keyword">of</span> numbers2) {
        total += number;
      }
      <span class="hljs-built_in">console</span>.log(total);
    }
}

calculate([<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>,<span class="hljs-number">4</span>],[<span class="hljs-number">10</span>,<span class="hljs-number">11</span>,<span class="hljs-number">12</span>, <span class="hljs-number">13</span>]);
<span class="hljs-comment">// 10</span>
<span class="hljs-comment">// 46</span>
</code></pre>
<h1 id="heading-summary">Summary</h1>
<p>In this blog, we tried to understand the three ways of declaring variables using <em>var</em>, <em>let</em> and <em>const</em>.</p>
<p>Variables declared using <em>var</em> are more flexible but it leads to more confusion and bugs due to its function-level scoping and hoisting behaviour.</p>
<p>On one hand, let allows the re-assignment, making it useful for situations where variable values may change over time.</p>
<p>On the other hand, const doesn't allow re-assignment, making it useful for situations where variable values should not be changed.</p>
<p>While I cannot say that you should completely stop using <em>var</em> and only use <em>let</em> and <em>const</em> from now on. Choosing between var, let and const will depend on the specific needs of our program.</p>
<p>If we understand the differences and trade-offs between these three variable declaration methods, we can write more efficient and bug-free code.</p>
<h1 id="heading-conclusion">Conclusion</h1>
<p>I hope this article helps you to understand the differences and use cases of variables declared using var, let and const.</p>
<p>Share this with your friends and provide feedback to me at sobitp59@gmail.com. If you come across any incorrect information, please don't hesitate to reach out. I'm open to hearing your thoughts!</p>
<p>And also, I am doing the #151DaysOfCode challenge on Twitter, connect with me if you wanna join too and let's get started!</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://twitter.com/sobit_prasad/status/1624307436428627968?s=20">https://twitter.com/sobit_prasad/status/1624307436428627968?s=20</a></div>
]]></content:encoded></item><item><title><![CDATA[Why do browser consoles return undefined? Explained]]></title><description><![CDATA[Overview
As web developers, we are blessed with consoles in the browsers to interact and debug our web pages and applications.
The most common type of console is the JavaScript console, which is found in most modern web browsers.
These consoles are b...]]></description><link>https://blogs.sobitprasad.com/why-do-browser-consoles-return-undefined-explained</link><guid isPermaLink="true">https://blogs.sobitprasad.com/why-do-browser-consoles-return-undefined-explained</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[console.log]]></category><category><![CDATA[undefined]]></category><dc:creator><![CDATA[Sobit Prasad]]></dc:creator><pubDate>Fri, 17 Feb 2023 20:20:26 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1676656540225/b3f58efe-8336-407b-9fc1-f085421f81db.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-overview">Overview</h1>
<p>As web developers, we are blessed with consoles in the browsers to interact and debug our web pages and applications.</p>
<p>The most common type of console is the JavaScript console, which is found in most modern web browsers.</p>
<p>These consoles are built into the web browser that provides a command-line interface(CLI) for executing JavaScript commands and inspecting and debugging the state of our web pages.</p>
<p>In this blog, we will try to find the answer to "Why browser console returns undefined?".</p>
<h1 id="heading-the-browser-console">The Browser Console</h1>
<p>The first time I interacted with the console(<code>press F12</code>) was during following a course on JavaScript on Udemy.</p>
<p>I performed a lot of operations and getting the results in real-time in the console felt so convenient.</p>
<p>But, one thing that constantly bothered me was in some operations it returns the result as expected like adding two numbers <code>10 + 39</code> gives <code>49</code>, while in other cases like after defining a function or variable it gives <code>undefined.</code></p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1676440216021/9e26bf8c-4eaa-4ef0-8fbf-23aa921c969b.png" alt class="image--center mx-auto" /></p>
<p>So, let's understand the reason behind getting <code>undefined</code>. But, before that, we have to know what <code>`undefined` </code> actually is.</p>
<h1 id="heading-understanding-undefined">Understanding Undefined</h1>
<p>In JavaScript, <code>undefined</code> is a primitive value that is assigned to variables that have been declared but have not been initialized with a value, or to function parameters that have not been provided with an argument.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1676450491435/c3e746f2-b3ae-4421-bcb0-6faa8dfd831a.png" alt class="image--center mx-auto" /></p>
<p>We can say that <code>undefined</code> is like a placeholder for the variables and functions' arguments in the memory space until it's not get assigned with any value or passed with any arguments in functions.</p>
<h1 id="heading-understanding-the-working-of-repl-and-console">Understanding the working of REPL and Console</h1>
<p>The way code is executed in the console of a web browser is similar to the Read-Eval-Print Loop (REPL) methodology that is commonly used in interactive programming environments.</p>
<p>However, the console of a web browser is not strictly a REPL environment but it does share some similarities in terms of how code is entered, executed, and displayed.</p>
<p>This is different from how we code in a traditional programming environment, where we typically have to save our code to a file, compile it (if necessary), and then run it.</p>
<p>Now first, let's understand what each part of the abbreviation of REPL tells us:</p>
<ul>
<li><p><strong>Read</strong>: Hey! I am <em>Read</em> and I help in reading the input(code) that you enter. If your input is not correct(syntactically), I will not be able to pass your input to Eval.</p>
</li>
<li><p><strong>Eval</strong>: Heya! I am <em>Eval</em>(not evil) and I help in evaluating the input that you gave me via <em>Read</em> so that I can determine the results for your input.</p>
</li>
<li><p><strong>Print</strong>: Helloo! I am <em>Print</em> and I help in displaying the result of the evaluation provided by the Eval on the console.</p>
</li>
<li><p><strong>Loop</strong>: Hello! I am <em>Loop</em> and I help in taking you back to the <em>Read</em> so that you continue your chit-chat(giving input) with Read.</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1676485591604/f459f847-a8b2-4fef-af28-036ff313d940.png" alt class="image--center mx-auto" /></p>
<p>So basically, it is a type of interactive programming environment that reads the code, evaluates it, prints the result (if there is one), and then waits for us to enter more code.</p>
<h1 id="heading-understanding-the-reason-behind-undefined">Understanding the Reason Behind Undefined</h1>
<p>We know that because of the REPL methodology, the codes get executed immediately after we press <code>ENTER.</code></p>
<p>We also know there are three steps( <strong>Read, Evaluate and Print</strong> ) in between before it gets ready to read our code again (basically before <strong>Loop</strong> ).</p>
<p>At the <strong>Print</strong> stage, it is decided what should be printed in the console by JavaScript Console.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1676569398260/cde1c612-5de4-4706-8619-419859345047.png" alt class="image--center mx-auto" /></p>
<p>So, let's understand the different scenarios that probably might help us to understand when the JavaScript console decides to print <code>undefined</code>, and when not.</p>
<h2 id="heading-the-consolelog">the console.log()</h2>
<p>In JavaScript, every function returns a value, even if there is no explicit specification of one using the <code>return</code> keyword. If no <code>return</code> statement is used, the function automatically returns <code>undefined</code> by default.</p>
<p>When we call <code>console.log()</code> with a value as an argument, the value is printed to the console and then <code>undefined</code> is printed because <code>console.log()</code> itself does not have a return value.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(<span class="hljs-string">'hello world!'</span>)
<span class="hljs-comment">// hello world!</span>
<span class="hljs-comment">// undefined</span>
</code></pre>
<p>It is designed to output messages to the console, but it doesn't return a value that could be used elsewhere in the code.</p>
<p>So, after the value is printed to the console, the function returns <code>undefined</code> as its default return value.</p>
<h2 id="heading-the-explicit-return-type">the explicit return type</h2>
<p>Since we know that every function in JavaScript returns something. If there will be nothing, then it will be <code>undefined</code> by default.</p>
<p>So, let's tell the browser console explicitly what we want to return and see how it responds to us.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">animeLists</span>(<span class="hljs-params"></span>)</span>{
    <span class="hljs-keyword">return</span> [<span class="hljs-string">'naruto'</span>,<span class="hljs-string">'attack on titans'</span>, <span class="hljs-string">'one piece'</span>]
}
<span class="hljs-comment">// undefined</span>
<span class="hljs-comment">// animeLists()</span>
<span class="hljs-comment">// ▸(3) ['naruto', 'attack on titans', 'one piece']</span>
</code></pre>
<p>When we run the above code in the console, at first we will get <code>undefined</code>. This is because just defining a function does not produce a return value, so the console does not have anything to display as a result of the function definition.</p>
<p>The function definition is just stored in memory somewhere and is not executed until we call it.</p>
<p>In the next line, when we called the function <code>animeLists</code> and since we are explicitly telling the console to return the <code>['naruto', 'attack on titans', 'one piece']</code> using <code>return</code> keyword, we will only get the output and not <code>undefined</code>.</p>
<h2 id="heading-the-expressions">the expressions</h2>
<p>An expression in JavaScript is a combination of values, variables, and operators that can be evaluated to a single value.</p>
<p>It can be as simple as a single value or it can be as complex as a combination of multiple expressions.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">//01: Arithmetic Expression</span>
<span class="hljs-number">2</span> + <span class="hljs-number">3</span> * <span class="hljs-number">4</span> <span class="hljs-comment">// returns 14</span>

<span class="hljs-comment">//02: Function call Expression</span>
<span class="hljs-built_in">Math</span>.max(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>) <span class="hljs-comment">// returns 3</span>

<span class="hljs-comment">//03: Ternary operator Expression</span>
x &gt; y ? <span class="hljs-string">"x is greater"</span> : <span class="hljs-string">"y is greater"</span> <span class="hljs-comment">// returns the greater one</span>

<span class="hljs-comment">//04: Boolean Expression</span>
<span class="hljs-literal">true</span> === <span class="hljs-number">1</span> <span class="hljs-comment">// returns false</span>
</code></pre>
<p>In all the examples above, the console does not display the value <code>undefined</code> because after reading the expression, it gets evaluated and the result is immediately printed on the console.</p>
<p>After printing the result, it loops back to Read so that it starts taking more inputs from us.</p>
<h2 id="heading-the-final-example">the final example</h2>
<p>Till now if you have got a little idea about how all these work from the examples above, then let's finally conclude this, understanding the example below step by step.</p>
<p>Before that, let's give aliases to "Read", "Eval", "Print "and "Loop" as "Mr. Read", "Mr. Eval", "Mr. Print" and "Mr. Loop" respectively.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Run this code in console</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greetUser</span>(<span class="hljs-params"></span>)</span>{
    <span class="hljs-keyword">const</span> message = <span class="hljs-string">'hey user! welcome to console'</span>;
    <span class="hljs-built_in">console</span>.log(message);
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'your total cost for the stay is : '</span>);
    <span class="hljs-keyword">return</span> <span class="hljs-number">2100</span> - <span class="hljs-number">100</span>;
}
</code></pre>
<ul>
<li><p><strong>Step 1</strong>: When we enter this input in the console and press <code>ENTER</code>, Mr. Read will look into our code and finds everything fine. So, he tells Mr. Eval to look into it.</p>
</li>
<li><p><strong>Step 2</strong>: Now, when Mr. Eval looks into the code, he finds that it is just a function definition because the function hasn't been called yet. Since there is nothing to return, Mr Eval returns <code>undefined</code> and sends it to Mr. Print.</p>
</li>
<li><p><strong>Step 3</strong>: The job of Mr. Print is to display whatever is received by Mr. Eval on the console. This time it was <code>undefined</code>, so he prints the same on the console.</p>
</li>
<li><p><strong>Step 4</strong>: Since the final result is printed for the execution of code till now, Mr. Loop will tell Mr. Read, "hey Mr. Read! you can now take another input from the user". And this process continues.</p>
</li>
</ul>
<p>Till now, we have only gotten the <code>undefined</code> because we haven't called the function yet, so let's finally call the function <code>greetUser()</code> .</p>
<pre><code class="lang-javascript">greetUser(); <span class="hljs-comment">// calling the function</span>
</code></pre>
<p>The same process will be followed this time as well, let's understand this one as well.</p>
<ul>
<li><p><strong>Step 1</strong>: After we call the function <code>greetUser,</code> Mr. Read will look into our code and reads the various commands we have given.</p>
</li>
<li><p><strong>Step 2</strong>: Now, Mr. Loop will evaluate our code and since we are explicitly returning with the <code>return</code> keyword, we will not get <code>undefined</code>. After evaluation, Mr. Loop sends the result to Mr. Print.</p>
</li>
<li><p><strong>Step 3</strong>: Now, Mr. Print displays the final result on the console.</p>
<pre><code class="lang-plaintext">  hey user! welcome to console
  your total cost for the stay is : 
  2000
</code></pre>
</li>
<li><p><strong>Step 4</strong>: Again, Mr. Loop will tell Mr. Read, "hey Mr. Read! you can now take another input from the user". And this process continues.</p>
</li>
</ul>
<h1 id="heading-summary">Summary</h1>
<ul>
<li><p>A console is a built-in tool in modern web browsers that provides a command-line interface for debugging and interacting with web pages.</p>
</li>
<li><p>It is similar to the Read-Eval-Print Loop (REPL) methodology used in interactive programming environments where,</p>
<ul>
<li><p>Read: It reads the input we enter</p>
</li>
<li><p>Eval: It evaluates and determines the results of the input.</p>
</li>
<li><p>Print: It prints the result on the console.</p>
</li>
<li><p>Loop: It loops back to Read so that Read can take another input.</p>
</li>
</ul>
</li>
<li><p>In JavaScript, every function returns a value, by default it is <code>undefined</code>. And since console.log() does not have a return value so it prints <code>undefined.</code></p>
</li>
<li><p>If we explicitly state the return value in the code then it resolves the issue of getting "undefined" as output.</p>
</li>
</ul>
<p>I hope this blog helps you to understand at least the basic concept behind returning <code>undefined</code> to the console. If it does, do share it and if you want to connect with me, say Hi! <a target="_blank" href="https://twitter.com/sobit_prasad">here</a>.</p>
]]></content:encoded></item><item><title><![CDATA[variable shadowing in javascript 👥]]></title><description><![CDATA[Introduction 🐥
Hello everyone, this article is going to be very short but also important. Before reading this blog, please read my previous blog on Scope, Scope-Chain, and Lexical Environment in JavaScript. So, in this blog we will talk on shadowing...]]></description><link>https://blogs.sobitprasad.com/variable-shadowing-in-javascript</link><guid isPermaLink="true">https://blogs.sobitprasad.com/variable-shadowing-in-javascript</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Web Development]]></category><dc:creator><![CDATA[Sobit Prasad]]></dc:creator><pubDate>Fri, 01 Apr 2022 12:30:48 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1648793374677/iJ3WHzldv.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-introduction">Introduction 🐥</h1>
<p>Hello everyone, this article is going to be very short but also important. Before reading this blog, please read my previous blog on <a target="_blank" href="https://sobitprasad.hashnode.dev/scope-scope-chain-and-lexical-environment-in-javascript">Scope, Scope-Chain, and Lexical Environment in JavaScript</a>. So, in this blog we will talk on <strong><em>shadowing in javascript</em></strong>, what is <strong><em>illegal shadowing</em></strong>. So, please read this blog carefully, because it will help you in your web dev journey. So, let's start.</p>
<h1 id="heading-variable-shadowing-in-javascript">Variable Shadowing in JavaScript 👀</h1>
<p>In my previous blog, we have talked a lot about scopes in javascript like global, local, and block scope. Now, let's understand shadowing with the help of an example. We will use the <code>var</code> and <code>let</code> keywords,
as <code>let</code> and <code>const</code> behave the same in variable shadowing so we will skip <code>const</code> here.</p>
<h2 id="heading-variable-shadowing-with-var-keyword">variable shadowing with <code>var</code> keyword 🦉</h2>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> a = <span class="hljs-number">10</span>; <span class="hljs-comment">// variable declared in global scope</span>
{
    <span class="hljs-keyword">var</span> a = <span class="hljs-number">100</span>; <span class="hljs-comment">// variable declared inside a block</span>
}
<span class="hljs-built_in">console</span>.log(a);
</code></pre>
<p>So, what will be the output here 🤔? Before answering, let's understand the above code. We have declared two variables with the same name <code>a</code> one in the global space and one inside the block, and we are consoling <code>a</code> in the global scope. So, now you can tell me your answer. If your answer is <code>100</code>, congratulations 🥳, it's the right answer. But why we are getting <code>100</code> even though we have written <code>console.log(a);</code> in the global scope. This is because, both the variables are pointing to the same memory location i.e. both are pointing to the Global Memory Scope. </p>
<p>So, what is variable shadowing here? Here, the variable inside the block is shadowing the variable in the global scope. In simpler terms you can say, a variable in block scope is hiding the value of the variable in global scope with its shadow and printing its own value. But what if we write the variable declared inside the block, in a function. Let's see</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> a = <span class="hljs-number">10</span>; <span class="hljs-comment">// variable declared in global scope</span>
func();
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">func</span>(<span class="hljs-params"></span>)</span>{
    <span class="hljs-keyword">var</span> a = <span class="hljs-number">100</span>; <span class="hljs-comment">// variable declared inside a function</span>
}
<span class="hljs-built_in">console</span>.log(a);
</code></pre>
<p>So, here output will be <code>10</code>, Why? Because both the variables are stored in different memory spaces. As keyword <code>var</code> is a function/local scoped i.e. variable declared inside the function can be accessed inside that function only, we will not be able to access it outside its boundary. And here, the variable <code>a</code> inside function fails to shadow the variable <code>a</code> in the global scope.</p>
<h2 id="heading-variable-shadowing-with-let-keyword">variable shadowing with <code>let</code> keyword 🦚</h2>
<p>Let's understand this with the above example only. </p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span>  a = <span class="hljs-number">10</span>; <span class="hljs-comment">// variable declared in global scope</span>
{
   <span class="hljs-keyword">let</span> a = <span class="hljs-number">100</span>; <span class="hljs-comment">// variable declared inside a block</span>
}
<span class="hljs-built_in">console</span>.log(a);
</code></pre>
<p>So, here our output will be <code>10</code>, we should print <code>100</code> are you saying? No, it's not like that in the case of <code>let</code>, because <code>let</code> is a block-scope type i.e. if we declare a variable with <code>let</code> inside any block whether inside a function, inside an if-else, or inside a while/for loop, we will never be able to access <code>let</code> outside that block. As <code>let</code> is a block-scope type, in the above example both the variables have different memory spaces and the variable inside the block is not able to shadow the variable in the global space.</p>
<h1 id="heading-illegal-shadowing-in-javascript">Illegal Shadowing in JavaScript 🧛‍♀️</h1>
<p>To understand illegal shadowing we will use <code>var</code> and <code>let</code> keywords in our example. So, let's try to understand illegal shadowing.</p>
<pre><code class="lang-javascript">    <span class="hljs-keyword">let</span> a = <span class="hljs-number">10</span>; <span class="hljs-comment">// variable declared in global scope using `let` keyword</span>
    {
      <span class="hljs-keyword">var</span> a = <span class="hljs-number">100</span>; <span class="hljs-comment">// variable declared inside a block using `var` keyword</span>
    }
   <span class="hljs-built_in">console</span>.log(a);
</code></pre>
<p>Now, here we will get an error <code>Uncaught SyntaxError: Identifier 'a' has already been declared</code>. Although here both the variables are pointing to the global memory space, the variable <code>a</code> inside the block fails to shadow the variable <code>a</code> from the global space.  This is said to be illegal shadowing.</p>
<p>But what if we swap the keywords <code>let</code> and <code>var</code> or write the var <code>a</code> in a function instead in a block. So, let's see.</p>
<h2 id="heading-example-1-swapping-variables-let-and-var-in-the-above-example">Example 1: Swapping variables <code>let</code> and <code>var</code> in the above example</h2>
<pre><code><span class="hljs-keyword">var</span> a <span class="hljs-operator">=</span> <span class="hljs-number">10</span>; <span class="hljs-comment">// variable declared in global scope using `var` keyword</span>
    {
      let a <span class="hljs-operator">=</span> <span class="hljs-number">100</span>; <span class="hljs-comment">// variable declared inside a block using `let` keyword</span>
    }
  console.log(a);
</code></pre><p>Here, we will get <code>10</code> in the console and not an error, but why? Because, both the variables are pointing to separate memory spaces. Although, the variable inside the block will not shadow the variable in the global space, because <code>let</code> has its own separate memory space.</p>
<h2 id="heading-example-2-writing-variable-var-inside-a-function-in-the-above-example">Example 2: Writing variable <code>var</code> inside a function in the above example</h2>
<pre><code class="lang-javascript">    <span class="hljs-keyword">let</span> a = <span class="hljs-number">10</span>; <span class="hljs-comment">// variable declared in global scope using `let` keyword</span>
    func();
    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">func</span>(<span class="hljs-params"></span>)</span>{
      <span class="hljs-keyword">var</span> a = <span class="hljs-number">100</span>; <span class="hljs-comment">// variable declared inside a block using `var` keyword</span>
    }
   <span class="hljs-built_in">console</span>.log(a);
</code></pre>
<p>Here, we will also get <code>10</code> in the console because variable <code>a</code> inside the function and variable <code>a</code> outside the function is pointing to the different memory location,s and here also var <code>a</code> inside the function will not shadow the variable declared with <code>let</code> keyword.</p>
<p>So, that's it guys for this blog. I will be very glad if you let me know any suggestions/corrections in any of my blog articles. If you find this article helpful, say hi to me on <a target="_blank" href="https://www.linkedin.com/in/sobit-prasad/">LinkedIn</a> 🌸</p>
]]></content:encoded></item><item><title><![CDATA[Scope, Scope-Chain, and Lexical Environment in JavaScript]]></title><description><![CDATA[Introduction
What comes to your mind when you heard the term "scope"? It probably might be a "binocular" or if you play any battle-royale game (like PUBG, Fortnite, etc), then it might be a 2X, 3X, 4X scopes, etc, Right? Whatever it might be, let's s...]]></description><link>https://blogs.sobitprasad.com/scope-scope-chain-and-lexical-environment-in-javascript</link><guid isPermaLink="true">https://blogs.sobitprasad.com/scope-scope-chain-and-lexical-environment-in-javascript</guid><category><![CDATA[Scope]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[Web Development]]></category><dc:creator><![CDATA[Sobit Prasad]]></dc:creator><pubDate>Sat, 26 Mar 2022 17:05:36 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1647541942583/xVDVTHtAo.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-introduction">Introduction</h1>
<p>What comes to your mind when you heard the term <strong><em>"scope"</em></strong>? It probably might be a <strong><em>"binocular"</em></strong> or if you play any battle-royale game (like PUBG, Fortnite, etc), then it might be a 2X, 3X, 4X scopes, etc, Right? Whatever it might be, let's see scope from the perspective of a battle royale game. So, from the perspective of a battle-royale game, the scope is used to see/find enemies that fall in the range of the scope, isn't it? And in JavaScript, the scope works something like this. </p>
<p>Namaste everyone, in this blog article we are going to explore a bunch of things like scope, scope-chain, lexical environment, etc. But, before reading this article I will recommend you to read my blog on <a target="_blank" href="https://sobitprasad.hashnode.dev/javascript-behind-the-scene">JavaScript Behind The Scene</a> so that you got familiar with how JavaScript works behind the scene. So, let's explore.</p>
<h1 id="heading-scope-in-javascript">Scope in JavaScript</h1>
<p>Scope in JavaScript is the range where we can access specific variables and functions or you can say, scopes tell us where we can access particular variables and functions in our code. So, there are basically three types of scopes in JavaScript : </p>
<ol>
<li>Global Scope </li>
<li>Local/Function Scope</li>
<li>Block Scope</li>
</ol>
<p>Let's explore all these scopes one by one and see how it works.</p>
<h3 id="heading-global-scope-in-javascript">Global Scope in JavaScript</h3>
<p>When we declare variables or functions at the top of our code i.e. in the global space then those variables or functions are said to be in the Global Scope. We can access these variables or functions from anywhere inside our code. Let's understand this with the help of an example -</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// variables and functions declared in the global space</span>
<span class="hljs-keyword">var</span> globalScopeVariable = <span class="hljs-string">`variable "globalScopeVariable" declared in Global space`</span>;
            <span class="hljs-built_in">console</span>.log(globalScopeVariable);

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">globalScopeFunction</span>(<span class="hljs-params"></span>)</span>{
            <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`function "globalScopeFunction()"" declared in Global space and accessing 
            "globalScopeVariable" below : `</span>);
           <span class="hljs-comment">// accessing variable "globalScopeVariable" </span>
            <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Accessed "globalScopeVariable" : <span class="hljs-subst">${globalScopeVariable}</span>`</span>);
        }
 globalScopeFunction();

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">callingGlobalScopeFunction</span>(<span class="hljs-params"></span>)</span>{
            <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`an another function "callingGlobalScopeFunction()" declared in Global space and 
            accessing "globalScopeFunction" below : `</span>);
            <span class="hljs-comment">// accessing function "globalScopeFunction()"</span>
            <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Accessed "globalScopeFunction()" : `</span>);
            globalScopeFunction();
        }
 callingGlobalScopeFunction();
</code></pre>
<p>The above code might overwhelm you, but don't worry we will understand each and every line of code.
In the above example, we have declared a variable <code>globalScopeVariable</code> and two functions <code>globalScopeFunction()</code> and <code>callingGlobalScopeFunction()</code> all in the global space. And function <code>globalScopeFunction()</code> is accessing the variable <code>globalScopeVariable</code> and function <code>callingGlobalScopeFunction()</code> is accessing the function <code>globalScopeFunction()</code>, we can also access function <code>callingGlobalScopeFunction()</code> inside an another function. </p>
<p>But how are we able to access the variable <code>globalScopeVariable</code> inside function <code>globalScopeFunction()</code> and function <code>globalScopeFunction()</code> inside function <code>callingGlobalScopeFunction()</code> which are not physically present inside that code. The answer is very simple, it's because we have declared all the variables and functions in the global space and thus we are able to access these variables and functions.</p>
<p>But what if we reverse the situation, i.e. what if we declare a variable or function inside a function and try to access that, outside the code or in the global space. What do you think? And here ladies and gentlemen come the term <strong>Local/Function</strong> scope, so let's explore this one as well.</p>
<h3 id="heading-localfunction-scope-in-javascript">Local/Function Scope in JavaScript</h3>
<p>First, let's understand this term, and later we will understand more deeply with the help of examples.</p>
<p>If we declare a variable or a function inside a function then, the scope of that variable and function is said to be Local/Function scope i.e., we can't access those variables and functions outside that function.
Let's understand this with the help of an example - </p>
<pre><code class="lang-javascript">
<span class="hljs-number">1</span>   <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">funcOne</span>(<span class="hljs-params"></span>)
2    </span>{ <span class="hljs-comment">// start of scope of variable "varOne"</span>
<span class="hljs-number">3</span>      <span class="hljs-keyword">var</span> varOne = <span class="hljs-string">`I am inside function "funcOne()"`</span>;
<span class="hljs-number">4</span>      <span class="hljs-built_in">console</span>.log(varOne);
<span class="hljs-number">5</span>
<span class="hljs-number">6</span>      funcTwo();
<span class="hljs-number">7</span>      <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">funcTwo</span>(<span class="hljs-params"></span>)
8       </span>{ <span class="hljs-comment">// start of scope of variable "varTwo"</span>
<span class="hljs-number">9</span>            <span class="hljs-keyword">var</span> varTwo = <span class="hljs-string">`I am inside function "funcTwo()."`</span>;
<span class="hljs-number">10</span>           <span class="hljs-built_in">console</span>.log(varOne);
<span class="hljs-number">11</span>           <span class="hljs-built_in">console</span>.log(varTwo);
<span class="hljs-number">12</span>           
<span class="hljs-number">13</span>          funcThree();
<span class="hljs-number">14</span>          <span class="hljs-function"><span class="hljs-keyword">function</span>  <span class="hljs-title">funcThree</span>(<span class="hljs-params"></span>)
15           </span>{ <span class="hljs-comment">// start of scope of variable "varThree"</span>
<span class="hljs-number">16</span>                <span class="hljs-keyword">var</span> varThree = <span class="hljs-string">`I am inside function "funcThree()".`</span>;
<span class="hljs-number">17</span>                 <span class="hljs-built_in">console</span>.log(varOne);
<span class="hljs-number">18</span>                 <span class="hljs-built_in">console</span>.log(varTwo);
<span class="hljs-number">19</span>                 <span class="hljs-built_in">console</span>.log(varThree); 
<span class="hljs-number">20</span>           } <span class="hljs-comment">// end of scope of variable "varThree"</span>
<span class="hljs-number">21</span>
<span class="hljs-number">22</span>        }  <span class="hljs-comment">// end of scope of variable "varTwo"</span>
<span class="hljs-number">23</span> 
<span class="hljs-number">24</span>    } <span class="hljs-comment">// end of scope of variable "varOne"</span>
<span class="hljs-number">25</span>        
<span class="hljs-number">26</span>     funcOne();
</code></pre>
<p>In the above example, we have three functions <code>funcOne()</code>, <code>funcTwo()</code> and <code>funcThree()</code>, and also we have three variables namely <code>varOne</code>, <code>varTwo</code> and <code>varThree</code>.</p>
<p><code>funcOne()</code> is declared inside <code>funcTwo()</code>, <code>funcTwo()</code> is declared inside <code>funcThree</code>, and <code>funcThree()</code> is declared in the global space. And variables <code>varOne</code>, <code>varTwo</code>, and <code>varThree</code> are declared inside functions <code>funcOne</code>, <code>funcTwo</code>, and <code>funcThree</code> respectively. </p>
<p>The scope of these variables starts with the opening curly brace <code>{</code> and ends with the closing curly brace <code>}</code> of their respective functions, i.e. we cannot access these variables outside that function. And same in the case of functions, in the above example, if we will try to invoke/call function <code>funcOne()</code> outside the function <code>funcOne()</code> we will get <code>ReferenceError</code>.</p>
<p>But, have you noticed that inside function <code>funcTwo()</code> we are trying to access variable <code>varOne</code> and inside function <code>funcThree</code> we are trying to access variables <code>varOne</code> and <code>varTwo</code> which are physically not present there. But how are we able to do it? Why we are not getting any errors? All these are possible because of the <code>Lexical Scope/Environment</code>. </p>
<p>And here we will need the concept of Global Execution Context and Callstack, that's why I recommended reading <a target="_blank" href="https://sobitprasad.hashnode.dev/javascript-behind-the-scene">that blog</a> at the beginning of this article. So guys, let's explore this one as well.</p>
<h3 id="heading-lexical-scopeenvironment-in-javascript">Lexical Scope/Environment in JavaScript</h3>
<p>We know that when we run our code, a Global Execution Context is created, and with every invocation of a function another Execution Context gets created and all these are pushed to the Callstack in order of their invocation.</p>
<p>But what is Lexical Scope/Environment? Don't worry we will understand this more deeply. First, let's understand how lexical scope/environment is created. So, when Global Execution Context is created, a lexical scope/environment is also created i.e. with every Execution Context there is something called <code>lexical scope/environment</code> is present with it. Let's understand this with the help of the figure below by taking the example of the code above.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1647886721490/z6pMbfGI5.png" alt="lexical-environment.png" /></p>
<p>So, when we will run the above code a Global Execution Context is created, and <code>funcOne</code> will be assigned with whole code inside the <code>{ .. }</code> curly braces and <code>varOne</code> will be assigned with <code>undefined</code> in the memory component and when the code runs in the code component <code>varOne</code> will be assigned with its actual value i.e. <code>I am inside function "funcOne()</code> and another Execution Context is created for <code>funcTwo</code> and <code>funcThree</code> as well.</p>
<p>Now remember this paragraph we have discussed above</p>
<blockquote>
<p>But, have you noticed that inside function <code>funcTwo()</code> we are trying to access variable <code>varOne</code> and inside function <code>funcThree</code> we are trying to access variables <code>varOne</code> and <code>varTwo</code> which are physically not present there. But how are we able to do it? Why we are not getting any errors? All these are possible because of the <code>Lexical Scope/Environment</code>. </p>
</blockquote>
<p>So, here is the answer. <strong>The lexical environment is the local memory along with the lexical environment of its parent.</strong> Didn't understand? Let's go deep and understand this with the help of the code above.</p>
<p>In function <code>funcThree</code>, we have only declared variable <code>varThree</code>. So, when <code>funcThree</code> executes, JavaScript Engine will assign <code>undefined</code> to all the variables i.e. to <code>varOne</code>, <code>varTwo</code>, and <code>varThree</code> in the memory component. But, <code>varOne</code>, and <code>varTwo</code> are not initialized inside <code>funcThree</code>. So, the lexical environment of <code>funcThree</code> will start looking for the values of its parent i.e. inside function <code>funcTwo</code> and here we will find the value of <code>varTwo</code>. But again, the value of <code>varOne</code> is not inside function <code>funcTwo()</code>, so the lexical environment of <code>funcTwo</code> will start searching for the value of <code>varOne</code> of its parent i.e. inside <code>funcOne()</code> and when the value is found it is assigned to its respective variables. The chain of these lexical environments is known as <strong><em>Scope Chain</em></strong>.</p>
<blockquote>
<p>NOTE: the lexical environment of global or window object is null. If we will try to access a variable or function which is not declared anywhere, then of course it will not be present in any of the lexical environments and we will get a beautiful error.</p>
</blockquote>
<p>It's enough for the lexical environments, now let's head to our final destination of this article i.e. the block scope in JavaScript. </p>
<h3 id="heading-block-scope-in-javascript">Block Scope in JavaScript</h3>
<p>Before learning block scope in JavaScript, first, let's understand what a <strong><em>BLOCK</em></strong> is? So, a block in JavaScript is defined by the curly braces <code>{ }</code>, also known as the compound statement. Now, you might be wondering what is the use of <strong><em> block</em></strong>, Right? So, a block is used to combine multiple JavaScript statements into a group. Now, you might have another question why do we need to group multiple JavaScript statements into a group? So, here is the answer, we need to group multiple JavaScript statements in a block so that we can use that block where JavaScript expects only one statement. If it sounds confusing don't worry, let's understand this by creating a block of statements step by step.</p>
<p>Step 1:We can start our block with this <code>{ }</code> curly braces. This curly braces <code>{ }</code> below is a block and a valid JavaScript code. </p>
<pre><code class="lang-javascript">{
<span class="hljs-comment">// I am a block</span>
}
</code></pre>
<p>Step 2: Now, we can write multiple JavaScript statements inside this block <code>{ }</code>.</p>
<pre><code class="lang-javascript">{
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'I am inside a block'</span>);
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'I am also inside a block'</span>);
}
</code></pre>
<p>Step 3: Let's used the above block with the <code>if</code> where JavaScript expects only one statement, i.e. we can write an <code>if</code> statement as <code>if (true) console.log('I am not inside a block');</code> when we need a single statement, but when we need multiple statements we can use block as shown below in the code.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">if</span>(<span class="hljs-literal">true</span>){
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'I am inside a block'</span>);
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'I am also inside a block'</span>);
}

<span class="hljs-comment">//Output : </span>
<span class="hljs-comment">//I am inside a block</span>
<span class="hljs-comment">//I am also inside a block</span>
</code></pre>
<p>Now, as we have understood <strong><em>block</em></strong>, let's dive into <strong><em>block scope</em></strong> in JavaScript. To understand block scope, let's declare three variables using <code>var</code>, <code>let</code>, and <code>const</code>.</p>
<pre><code class="lang-javascript">{
<span class="hljs-keyword">var</span> a = <span class="hljs-string">'I am var a'</span>;
<span class="hljs-keyword">let</span> b = <span class="hljs-string">'I am let b'</span>;
<span class="hljs-keyword">const</span> c = <span class="hljs-string">'I am const c'</span>;

<span class="hljs-comment">// inside block</span>
<span class="hljs-built_in">console</span>.log(a);
<span class="hljs-built_in">console</span>.log(b);
<span class="hljs-built_in">console</span>.log(c);
}

<span class="hljs-comment">// outside block</span>
<span class="hljs-built_in">console</span>.log(a);
<span class="hljs-built_in">console</span>.log(b);
<span class="hljs-built_in">console</span>.log(c);

<span class="hljs-comment">//Output : </span>
<span class="hljs-comment">//I am var a</span>
<span class="hljs-comment">//I am let b</span>
<span class="hljs-comment">//I am const c</span>
<span class="hljs-comment">//I am var a</span>
<span class="hljs-comment">//Uncaught ReferenceError: b is not defined</span>
</code></pre>
<p>Now, when we run the above code we will get the error <code>Uncaught ReferenceError: b is not defined</code> i.e. while accessing the variable <code>b</code> outside the block. This is because the scope of variables <code>b</code> and <code>c</code> is inside that block only i.e. these variables are stored in the separate memory space, we cannot access variables declared with <code>let</code> and <code>const</code> outside that block. And thus, <code>let</code> and <code>const</code> is said to be <strong><em>block-scoped</em></strong>.</p>
<p>But, if we have written the same code inside a function, we will not be able to access a single variable outside the block i.e.</p>
<pre><code class="lang-javascript">func();
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">func</span>(<span class="hljs-params"></span>)</span>{
<span class="hljs-keyword">var</span> a = <span class="hljs-string">'I am var a'</span>;
<span class="hljs-keyword">let</span> b = <span class="hljs-string">'I am let b'</span>;
<span class="hljs-keyword">const</span> c = <span class="hljs-string">'I am const c'</span>;

<span class="hljs-comment">// inside block</span>
<span class="hljs-built_in">console</span>.log(a);
<span class="hljs-built_in">console</span>.log(b);
<span class="hljs-built_in">console</span>.log(c);
}

<span class="hljs-comment">// outside block</span>
<span class="hljs-built_in">console</span>.log(a);
<span class="hljs-built_in">console</span>.log(b);
<span class="hljs-built_in">console</span>.log(c);

<span class="hljs-comment">//Output : </span>
<span class="hljs-comment">//I am var a</span>
<span class="hljs-comment">//I am let b</span>
<span class="hljs-comment">//I am const c</span>
<span class="hljs-comment">//Uncaught ReferenceError: a is not defined</span>
</code></pre>
<p>And thus, var is said to be <code>function/local scoped</code> i.e. if we declare a variable using the <code>var</code> keyword inside a function, we will not be able to access that variable outside that function. </p>
<p>So, that's it guys for in this blog. I will be very glad if you let me know any suggestions/corrections in any of my blog articles. If you find this article helpful, say hi to me on <a target="_blank" href="https://www.linkedin.com/in/sobit-prasad/">LinkedIn</a> 🌸</p>
]]></content:encoded></item><item><title><![CDATA[What is 'this' in JavaScript?]]></title><description><![CDATA[What is the this keyword in JavaScript?
Introduction
When we run our code in JavaScript, a Global Execution Context (GBE) is created. But, along with GBE, a global object  and  this keywords also get created. But, what are Global Object and this keyw...]]></description><link>https://blogs.sobitprasad.com/what-is-this-in-javascript</link><guid isPermaLink="true">https://blogs.sobitprasad.com/what-is-this-in-javascript</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[Web Development]]></category><dc:creator><![CDATA[Sobit Prasad]]></dc:creator><pubDate>Sun, 13 Mar 2022 17:10:50 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1647019195921/2SHy7UMZW.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-what-is-the-this-keyword-in-javascript">What is the <code>this</code> keyword in JavaScript?</h1>
<h2 id="heading-introduction">Introduction</h2>
<p>When we run our code in JavaScript, a <a target="_blank" href="https://sobitprasad.hashnode.dev/javascript-behind-the-scene">Global Execution Context (GBE)</a> is created. But, along with GBE, a <strong><em>global object</em> </strong> and  <em><code>this</code></em> keywords also get created. But, what are <strong>Global Object</strong> and <code>this</code> keyword we are talking about here? So, let's explore, here <strong>Global Object</strong> refers to the <code>window</code> object and <code>this</code> is a keyword that refers to this <code>window</code> object at the global space i.e., in the global space <code>window === this</code>. So, if we will type <code>window === this</code> in the <code>console</code> we will get <code>true</code> as the output. But, the behavior of <code>this</code> changes according to where it is being invoked. So, let's explore how it behaves at different places.</p>
<h2 id="heading-invoking-this-in-global-space-or-alone">invoking <code>this</code> in global space or alone</h2>
<p>When you write <code>console.log(this)</code> in your javascript program and inspect it in the <code>console</code>, you will see that <code>this</code> is referring to the <code>Window</code> object. So, in the global space <code>this</code> refers to <code>Window</code>.</p>
<h2 id="heading-invoking-this-inside-an-function">invoking <code>this</code> inside an function</h2>
<p>So, what do you think if we invoke <code>this</code> inside a function? So, let's write a few lines and see</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">func</span>(<span class="hljs-params"></span>)</span>{
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>);
}
func();
</code></pre>
<p>Here, <code>this</code> also refers to the <code>Window</code> object, but why? Because here function <code>func</code> is a property of <code>Global</code> i.e. <code>Window</code> object. So, here we can also say if we call <code>this</code> in a function as - <strong><em><code>this</code> refers to the object of which this function is a property of</em></strong>. Don't worry if you didn't get it yet, believe me, you will understand it in the next section.</p>
<h2 id="heading-invoking-this-in-an-object">invoking <code>this</code> in an object</h2>
<p>So, let's make an object and invoke <code>this</code> inside that.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> data = {
<span class="hljs-attr">firstName</span> : <span class="hljs-string">'Sobit'</span>,
<span class="hljs-attr">lastName</span> : <span class="hljs-string">'Prasad'</span>,
<span class="hljs-attr">fullName</span> : <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
     <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.firstName + <span class="hljs-string">" "</span> +<span class="hljs-built_in">this</span>.lastName;
     }
}
<span class="hljs-built_in">console</span>.log(data.fullName());

<span class="hljs-comment">// Output : Sobit Prasad</span>
</code></pre>
<p>So, here output will be <code>Sobit Prasad</code>. Here, inside object <code>data</code> we have invoked <code>this</code> inside function <code>fullName</code> and function <code>fullName</code> is a property of object <code>data</code> and that's why here <code>this</code> refers to <code>data</code> object and not the <code>Window</code> object. Let's understand more deeply with the help of an another example.</p>
<pre><code class="lang-javascript"> <span class="hljs-keyword">const</span> data1 = {
            <span class="hljs-attr">firstName</span>: <span class="hljs-string">'Sobit'</span>,
            <span class="hljs-attr">lastName</span>: <span class="hljs-string">'Prasad'</span>,
            <span class="hljs-attr">fullName</span>: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
                <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.firstName + <span class="hljs-string">" "</span> + <span class="hljs-built_in">this</span>.lastName;
            }
        }
 <span class="hljs-keyword">const</span> dataOne = data1.fullName;
 <span class="hljs-keyword">const</span> data2 = {<span class="hljs-attr">firstName</span>: <span class="hljs-string">'Mohit'</span>, <span class="hljs-attr">lastName</span>: <span class="hljs-string">'Sharma'</span>, dataOne };
 <span class="hljs-built_in">console</span>.log(data2.dataOne());

<span class="hljs-comment">//Output : Mohit Sharma</span>
</code></pre>
<p>In the above program, in spite of declaring function <code>fullName</code> inside object <code>data1</code>, we get output as <code>Mohit Sharma</code>, because at the time of invoking <code>dataOne</code> is the property of object <code>data2</code>.</p>
<h2 id="heading-this-under-use-strict"><code>this</code> under <code>use strict</code></h2>
<pre><code class="lang-javascript"><span class="hljs-meta"> "use strict"</span>
        <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">data</span>(<span class="hljs-params"></span>)</span>{
            <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>);
        }
        data();

<span class="hljs-comment">//Output : undefined</span>
</code></pre>
<p>When we include<code>use strict</code> in our program it doesn't allow default binding and thus we get <code>undefined</code>.</p>
<p>So, that's it guys for in this blog. I will be very glad if you let me know any suggestions/corrections in any of my blog articles. If you find this article helpful, say hi to me on <a target="_blank" href="https://www.linkedin.com/in/sobit-prasad/">LinkedIn</a> 🌸</p>
]]></content:encoded></item><item><title><![CDATA[javascript: let, const, and the temporal dead zone]]></title><description><![CDATA[Introduction
And as I promised in my previous blog that we have a trip with Temporal Dead Zone, and here it is. So, if you haven't understood Temporal Dead Zone and how to play with variables using keywords let and const yet. Don't worry, this blog i...]]></description><link>https://blogs.sobitprasad.com/javascript-let-const-and-the-temporal-dead-zone</link><guid isPermaLink="true">https://blogs.sobitprasad.com/javascript-let-const-and-the-temporal-dead-zone</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[Programming Tips]]></category><category><![CDATA[software development]]></category><dc:creator><![CDATA[Sobit Prasad]]></dc:creator><pubDate>Wed, 23 Feb 2022 20:07:06 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1645294885681/xWy4GcWyc.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-introduction">Introduction</h1>
<p>And as I promised in my <a target="_blank" href="https://sobitprasad.hashnode.dev/hoisting-in-javascript">previous blog</a> that we have a trip with <strong>Temporal Dead Zone</strong>, and here it is. So, if you haven't understood Temporal Dead Zone and how to play with variables using keywords <code>let</code> and <code>const</code> yet. Don't worry, this blog is totally dedicated to <code>let</code>, <code>const</code>, and <code>temporal dead zone</code>, and believe me if you will read this blog with the whole heart, this is going to be very beneficial for you in your future interviews. So without any further due let's start our trip.</p>
<h1 id="heading-starting-with-basics-var-let-and-const">Starting with basics: <code>var</code>, <code>let</code>, and <code>const</code></h1>
<p>As <code>let</code> and <code>const</code> are almost similar I will explain this only with the help of <code>var</code> and <code>let</code>. So, below is our program with the same code but using variable keywords <code>var</code> and <code>let</code>. So, what do you think, what will be the answer? </p>
<pre><code class="lang-javascript"><span class="hljs-comment">//using `var` keyword</span>
<span class="hljs-built_in">console</span>.log(food);
<span class="hljs-keyword">var</span> food = <span class="hljs-string">'cooking'</span>;
</code></pre>
<pre><code class="lang-javascript"><span class="hljs-comment">//using `let` keyword</span>
<span class="hljs-built_in">console</span>.log(food);
<span class="hljs-keyword">let</span> food = <span class="hljs-string">'cooking'</span>;
</code></pre>
<p>In our first program (using <code>var</code>), of course, we will get <code>undefined</code> and why is that, because of hoisting, Right? If you don't know what hoisting is, please read my <a target="_blank" href="https://sobitprasad.hashnode.dev/hoisting-in-javascript">previous blog</a>. Now, let's move to our next program i.e. using the <code>let</code> keyword for variable declaration. Here, we will get an error as <code>Uncaught ReferenceError: Cannot access 'food' before initialization</code>. Now let's understand why this error occurs with <code>let</code>(and <code>const</code>).</p>
<p>First thing first, <code>let</code> and <code>const</code> are <em>block-scoped</em> unlike <code>var</code> which is <em>function-scoped</em> . Now, let's understand the <em>term</em> function-scoped and block-scoped.</p>
<ul>
<li><strong>Function-Scoped</strong>: <code>var</code> is a <em>function-scoped</em> which means if we declare a variable inside a function, we will not be able to access it from outside the function. So, <code>var</code> is only limited to function i.e. if we declare variables inside <code>if</code> and <code>for</code>, we can access it from outside of <code>if</code> as well as of <code>for</code>.
Let's understand this with the help of an example - </li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> food = <span class="hljs-string">'cooking'</span>;
<span class="hljs-built_in">console</span>.log(food);

<span class="hljs-comment">// function</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">funcOne</span>(<span class="hljs-params"></span>)</span>{
    <span class="hljs-keyword">var</span> food;
    <span class="hljs-built_in">console</span>.log(food);
}
funcOne();

<span class="hljs-comment">// if</span>
<span class="hljs-keyword">if</span>(<span class="hljs-literal">true</span>){
    <span class="hljs-keyword">var</span> food;
    <span class="hljs-built_in">console</span>.log(food);
}

<span class="hljs-comment">// for-loop</span>
<span class="hljs-keyword">for</span>(<span class="hljs-keyword">var</span> i = <span class="hljs-number">1</span>; i &lt;= <span class="hljs-number">3</span>; i++){
    <span class="hljs-keyword">var</span> food;
    <span class="hljs-built_in">console</span>.log(food);
}

<span class="hljs-comment">//OUTPUT : </span>
<span class="hljs-comment">//cooking</span>
<span class="hljs-comment">//undefined</span>
<span class="hljs-comment">//cooking</span>
<span class="hljs-comment">//cooking</span>
<span class="hljs-comment">//cooking</span>
<span class="hljs-comment">//cooking</span>
</code></pre>
<p>In the above program, we have declared four variables with the same name <code>food</code>, one in the global scope, one inside function <code>funcOne</code>, one inside <code>if</code>, and the last one inside a <code>for</code> loop. Also, we have initialized with value <code>cooking</code> only at the top i.e. at Global Scope. Now, when we run this code we will get <code>undefined</code> only when function <code>funcOne</code> is invoked because the scope of variable <code>food</code> inside function <code>fucnOne</code> lies only inside the <code>{ }</code> curly braces of the function <code>funcOne</code>. So, it cannot access the value <code>cooking</code> we initialized at the top. And that's why it is known as function-scoped.</p>
<ul>
<li><strong>Blocked-Scoped</strong>: <code>let</code> and <code>const</code> are <em>blocked-scoped</em>  which means if we declare a variable using <code>let</code> or <code>const</code> inside any block( block means inside any <code>{ }</code> braces), whether it is a function, an <code>if</code> or a <code>for</code> loop, we will not be able to access it outside its scope. Now, let's understand this with the help of an example. Below we have the same program as above but replaced it with <code>let</code> to <code>var</code>.</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> food = <span class="hljs-string">'cooking'</span>;
<span class="hljs-built_in">console</span>.log(food);

<span class="hljs-comment">// function</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">funcOne</span>(<span class="hljs-params"></span>)</span>{
    <span class="hljs-keyword">let</span> food;
    <span class="hljs-built_in">console</span>.log(food);
}
funcOne();

<span class="hljs-comment">// if</span>
<span class="hljs-keyword">if</span>(<span class="hljs-literal">true</span>){
    <span class="hljs-keyword">let</span> food;
    <span class="hljs-built_in">console</span>.log(food);
}

<span class="hljs-comment">// for-loop</span>
<span class="hljs-keyword">for</span>(<span class="hljs-keyword">let</span> i = <span class="hljs-number">1</span>; i &lt;= <span class="hljs-number">3</span>; i++){
    <span class="hljs-keyword">let</span> food;
    <span class="hljs-built_in">console</span>.log(food);
}

<span class="hljs-comment">//OUTPUT :</span>
<span class="hljs-comment">//cooking</span>
<span class="hljs-comment">//undefined</span>
<span class="hljs-comment">//undefined</span>
<span class="hljs-comment">//undefined</span>
<span class="hljs-comment">//undefined</span>
<span class="hljs-comment">//undefined</span>
</code></pre>
<p>Now you see we get <code>undefined</code> to all the variables we have declared with <code>let</code> inside function <code>funcOne</code>, inside <code>if</code>, and also inside <code>for</code> loop. This is because, when we declare variables using <code>let</code> and <code>const</code>, JavaScript Engine assigns memory to it in a separate scope i.e. the variable is only accessible inside <code>{ }</code> curly braces. And here also comes the concept of <code>**TEMPORAL DEAD ZONE**</code>, so let's get immersed into it.</p>
<h1 id="heading-the-temporal-dead-zone">The Temporal Dead Zone</h1>
<p>So, what is <em>Temporal Dead Zone</em>? Here is the answer, <em>Temporal Dead Zone</em> is the time that starts from the beginning of its(<em>variable</em>) scope till the variable is declared. This is the time when a variable is dead i.e. if you try to access a variable in this time zone, you will find it useless, you will not be able to access it. But you will find <code>Temporal Dead Zone</code> only when you declare variables using <code>let</code> and <code>const</code>. So, let's understand this concept with the help of an example - </p>
<pre><code class="lang-javascript"><span class="hljs-comment">// **********************************************************************</span>
<span class="hljs-comment">// ******************** Temporal Dead Zone *****************************</span>
<span class="hljs-comment">// *************************** for ***************************************</span>
<span class="hljs-comment">// ************************* variable ************************************</span>
<span class="hljs-comment">// ************************** `food1` ************************************</span>
<span class="hljs-comment">// ********************************************************************** </span>
<span class="hljs-keyword">let</span> food1 = <span class="hljs-string">'food is cooking at top'</span>;
<span class="hljs-built_in">console</span>.log(food1);


<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">funcOne</span>(<span class="hljs-params"></span>)</span>{
    <span class="hljs-comment">// **********************************************************************</span>
    <span class="hljs-comment">// ******************** Temporal Dead Zone *****************************</span>
    <span class="hljs-comment">// *************************** for ***************************************</span>
    <span class="hljs-comment">// ************************* variable ************************************</span>
    <span class="hljs-comment">// *************************  `food2`  ***********************************</span>
    <span class="hljs-comment">// **********************************************************************</span>
    <span class="hljs-keyword">let</span> food2 = <span class="hljs-string">'food is cooking inside funcOne'</span>;
    <span class="hljs-built_in">console</span>.log(food2);
}
funcOne();
</code></pre>
<blockquote>
<p>Note : *(asterisks) are given to visualize how (temporal dead zone)TDZ looks.</p>
</blockquote>
<p>Here we have two variables <code>food1</code> and <code>food2</code> declared at top-level and inside function <code>funcOne</code> respectively. The scope of variable <code>food1</code> is Global because it is declared at the very top level. So, its temporal dead zone starts from the very beginning and ends when it is being declared. And variable <code>food2</code> is declared inside function <code>funcOne</code> so its scope will be only inside the curly braces <code>{ }</code> of the function <code>funcOne</code>. Now, its temporal dead zone starts from the start of curly brace <code>{</code> and ends when it is being declared. </p>
<p>Now, when we try to access variables declared with <code>let</code> and <code>const</code> inside this <code>temporal dead zone</code>, you will not be able to access it, you are going to get a bunch of errors instead. Don't believe in me? let's do it then. Just move the <code>console.log()</code> in the temporal dead zone and see what happens.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// **********************************************************************</span>
<span class="hljs-comment">// ******************** Temporal Dead Zone *****************************</span>
<span class="hljs-comment">// *************************** for ***************************************</span>
<span class="hljs-comment">// ************************* variable ************************************</span>
<span class="hljs-comment">// ************************** `food1` ************************************</span>
<span class="hljs-built_in">console</span>.log(food1); <span class="hljs-comment">// OMG! inside TDZ</span>
<span class="hljs-comment">// ********************************************************************** </span>
<span class="hljs-keyword">let</span> food1 = <span class="hljs-string">'food is cooking at top'</span>;



<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">funcOne</span>(<span class="hljs-params"></span>)</span>{
    <span class="hljs-comment">// **********************************************************************</span>
    <span class="hljs-comment">// ******************** Temporal Dead Zone *****************************</span>
    <span class="hljs-comment">// *************************** for ***************************************</span>
    <span class="hljs-comment">// ************************* variable ************************************</span>
    <span class="hljs-comment">// *************************  `food2`  ***********************************</span>
    <span class="hljs-built_in">console</span>.log(food2);  <span class="hljs-comment">//OMG! it is also inside TDZ</span>
    <span class="hljs-comment">// **********************************************************************</span>
    <span class="hljs-keyword">let</span> food2 = <span class="hljs-string">'food is cooking inside funcOne'</span>;

}
funcOne();
</code></pre>
<pre><code class="lang-javascript"> Uncaught <span class="hljs-built_in">ReferenceError</span>: Cannot access <span class="hljs-string">'food1'</span> before initialization
</code></pre>
<p>You will get an error at the very first line because the variable is not accessible there. That's why it is preferred to use <code>let</code> and <code>const</code> in place of  <code>var</code> to avoid bugs. And now to save our variables from the  <strong><em>TEMPORAL DEAD ZONE</em></strong>, we must always try to declare it at the very top-level of its scope.</p>
<p>So, that's it guys for in this blog. I will be very glad if you let me know any suggestions/corrections in any of my blog articles. If you find this article helpful, say <code>hi</code> to me on <a target="_blank" href="https://www.linkedin.com/in/sobit-prasad/">LinkedIn</a></p>
]]></content:encoded></item><item><title><![CDATA[Hoisting In JavaScript]]></title><description><![CDATA[Introduction
First of all, let's understand the term 'HOISTING'. Hoisting means lifting up. For example, when we hoist our flag or when a crane lifts something, it's hoisting(lifting up) that thing, Right? Now, before proceeding further, I will recom...]]></description><link>https://blogs.sobitprasad.com/hoisting-in-javascript</link><guid isPermaLink="true">https://blogs.sobitprasad.com/hoisting-in-javascript</guid><category><![CDATA[Hoisting]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[javascript books]]></category><category><![CDATA[javascript framework]]></category><dc:creator><![CDATA[Sobit Prasad]]></dc:creator><pubDate>Fri, 18 Feb 2022 13:28:24 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1645154850712/50-dei_1i.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction">Introduction</h2>
<p>First of all, let's understand the term 'HOISTING'. Hoisting means lifting up. For example, when we hoist our flag or when a crane lifts something, it's hoisting(lifting up) that thing, Right? Now, before proceeding further, I will recommend you to read my <a target="_blank" href="https://sobitprasad.hashnode.dev/javascript-behind-the-scene">previous blog</a>, because both the blogs are connected to each other and it will help you to understand the concept of this blog very easily. But let's revise a few concepts from the previous blog.</p>
<p>In the previous blog, we have understood that whenever we run our code an Execution Context is created and inside that context, we have two phases - Memory Creation Phase and Code Execution Phase. Memory Creation Phase runs first and allocates memory/space to all the <code>variables</code> and <code>functions</code> and after that Code Execution Phase runs and it assigns the actual values to its corresponding <code>variables</code>. But why I am saying here <code>variables</code> only, don't worry we will understand it later in this blog.</p>
<h2 id="heading-variable-hoisting-in-javascript">Variable Hoisting In JavaScript</h2>
<p>Now coming back again to the Memory Creation Phase. We know that when we run our code Javascript Engine scans the whole code and allocates memory to all the <code>variables</code> and <code>functions</code>. But, in the case of <code>variables</code>, it assigns with a default value of <code>undefined</code> in Memory Creation Phase only, even before the execution of our code. Now let's understand all these concepts with the help of examples.</p>
<h4 id="heading-variable-hoisting-using-the-keyword-var">Variable Hoisting: using the keyword <code>var</code></h4>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> exOne =  <span class="hljs-string">'I am learning Hoisting in Javascript'</span>;
<span class="hljs-built_in">console</span>.log(exOne);
<span class="hljs-comment">// Output : I am learning Hoisting in Javascript</span>
</code></pre>
<p>What do you think, what will be the output? It's simple, Right? It will give <strong>I am learning Javascript</strong> in the console. Now let's move to the next program.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(exTwo);
<span class="hljs-keyword">var</span> exTwo = <span class="hljs-string">'Programming is fun'</span>;
<span class="hljs-built_in">console</span>.log(exTwo);
</code></pre>
<p>Now, what do you think, what will be the output? But before giving you the answer I want to remind you of something and that is 'Memory Creation Phase'. We know in Memory Creation Phase, Javascript Engine will allocate memory and the default value <code>undefined</code> to its variable before executing the program. So, let's find out the answer.</p>
<p>First, let's see the code above, here Javascript Engine will go to <code>line 1</code> and find <code>console.log(exTwo);</code>. Now, it finds the variable <code>exTwo</code> but till now we haven't assigned any values to it and also trying to console log <code>exTwo</code>, Right? So, it will assign the default value i.e. <code>undefined</code> to <code>exTwo</code>. Now, JS Engine will move to <code>line 2</code>. Here, we are assigning '<strong>Programming is fun</strong>' to variable <code>exTwo</code>, so it will hold this value. Now, JS Engine will move to <code>line 3</code>, here we are again trying to console log variable <code>exTwo</code>. Now, it will print '<strong>Programming is fun</strong>', because here we have assigned '<strong>Programming is fun</strong> ' to variable <code>exTwo</code>. So our output will look something like this,</p>
<pre><code><span class="hljs-comment">//Output : </span>
<span class="hljs-comment">// undefined</span>
<span class="hljs-comment">// Programming is fun</span>
</code></pre><p>In the above program, we tried to console log variable <code>exTwo</code> before declaring it. But, what if we try to console log the variable <code>exTwo</code> without declaring it. So, what do think, what will be the output when we run the below code?</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(exTwo);
</code></pre>
<p>So, here also JS Engine will scan the whole program and it finds <code>exTwo</code> but there is no declaration for <code>exTwo</code>, so JS Engine will not assign any memory to it and throws an error.</p>
<pre><code> Uncaught ReferenceError: exTwo <span class="hljs-keyword">is</span> <span class="hljs-keyword">not</span> defined
</code></pre><blockquote>
<p>Difference between undefined and not defined. <strong>undefined</strong>: we will get <code>undefined</code> as an output when we try to access the variable before its being initialized or without initializing the variable. On the other hand, <strong>not defined</strong> is an error, we will face when we try to access the variable before declaring it.</p>
</blockquote>
<p> Think it of as a stranger whom you don't know, will you let him/her in your house, No!, Right? Now let's understand hoisting through the 'let' and 'const' keywords.</p>
<h4 id="heading-variable-hoisting-using-the-keywords-let-and-const">Variable Hoisting: using the keywords <code>let</code> and <code>const</code></h4>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(exThree);
<span class="hljs-keyword">let</span> exThree = <span class="hljs-string">'I love programming'</span>;
</code></pre>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(exFour);
<span class="hljs-keyword">const</span> exFour = <span class="hljs-string">'Javascript is a weird language'</span>;
</code></pre>
<p>When we declare variables using keywords <code>let</code> and <code>const</code>, it will work as same as the keyword <code>var</code>. But when we try to access the variable declared with keywords <code>let</code> and <code>const</code> before initializing it, it will throw an error.</p>
<pre><code> Uncaught ReferenceError: Cannot <span class="hljs-keyword">access</span> <span class="hljs-string">'exThree'</span> <span class="hljs-keyword">before</span> initialization
</code></pre><pre><code> Uncaught ReferenceError: Cannot <span class="hljs-keyword">access</span> <span class="hljs-string">'exFour'</span> <span class="hljs-keyword">before</span> initialization
</code></pre><p>But why do these happen? In the case of the keyword <code>var</code>, when we try to access the variable before initializing it we get <code>undefined</code>, but with keywords <code>let</code> and <code>const</code> we get an error. This happens because of the '<strong>Temporal Dead Zone</strong>'. I will not cover this topic in this blog but don't worry we are going to play more with <code>let</code> and <code>const</code> and Temporal Dead Zone in the next blog. Now let's understand hoisting from the eyes of <code>function</code>.</p>
<h2 id="heading-functional-hoisting-in-javascript">Functional Hoisting In JavaScript</h2>
<pre><code class="lang-javascript">funcOne();
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">funcOne</span>(<span class="hljs-params"></span>)</span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'hi! i am function one'</span>);
}
<span class="hljs-comment">// Output  : hi! i am function one</span>
</code></pre>
<p>What will be the output? Again, it's very simple, Right? We have used <code>functions</code> like it before so many times. But how does it possible to access a function even before declaring it. Have you remembered the last line of the second paragraph? So here is the answer, because in the case of <code>functions</code>, in Memory Creation Phase, JS Engine allocates the memory and the whole code inside that <code>function</code> as the value. Now when this <code>function</code> is invoked before or after the declaration of that function an Execution Context is created and in Memory Creation Phase inside this Execution Context, it will simply print the  '<strong>hi! i am function one</strong>' in the console and after that, this Execution Context will be deleted and the control will be transferred to Global Execution Context. Now if don't understand yet, just simply copy and paste the below code and open the console, you will find your answer.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(funcOne);
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">funcOne</span>(<span class="hljs-params"></span>)</span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'hi, i am function one'</span>);
}
<span class="hljs-built_in">console</span>.log(funcOne);
</code></pre>
<p>You will get output in the console as : </p>
<pre><code>ƒ <span class="hljs-selector-tag">funcOne</span>(){
    <span class="hljs-selector-tag">console</span><span class="hljs-selector-class">.log</span>(<span class="hljs-string">'hi, i am function one'</span>);
}
 ƒ <span class="hljs-selector-tag">funcOne</span>(){
    <span class="hljs-selector-tag">console</span><span class="hljs-selector-class">.log</span>(<span class="hljs-string">'hi, i am function one'</span>);
}
</code></pre><p>Now, you know how we are able to access the function even before declaring/initializing it. But, what if we write the same <code>function</code> using the <code>fat arrow</code> or anonymous function. So, let's find out our answer. We have our  code below,</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Using fat arrow function</span>
<span class="hljs-built_in">console</span>.log(funcOne);
<span class="hljs-keyword">var</span> funcOne = <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'hi, i am function one'</span>);
}
<span class="hljs-built_in">console</span>.log(funcOne);
funcOne();
</code></pre>
<pre><code><span class="hljs-comment">// Using anonymous function</span>
console.log(funcOne);
<span class="hljs-keyword">var</span> funcOne <span class="hljs-operator">=</span> <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
    console.log(<span class="hljs-string">'hi, i am function one'</span>);
}
console.log(funcOne);
funcOne();
</code></pre><p>And here I am asking for your answer again, so what will be your answer. Yes, you guessed it right, here <code>funcOne</code> will act as a <code>variable</code> and it will output in the console as : </p>
<pre><code><span class="hljs-literal">undefined</span>
ƒ (){
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'hi, i am function one'</span>);
}
hi, i am <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">one</span></span>
</code></pre><p>So, in both(using fat arrow and anonymous functions) the programs above, we have <code>funcOne</code> as a variable. So when JS Engine will scan these programs, it will allocate memory as well as the default value of <code>undefined</code> for line one. Now it will move to the next line and will assign the whole function to variable <code>funcOne</code>. In the second-last line, we are console logging the variable <code>funcOne</code> which holds the entire function in it, so it will print the whole code inside that function. Now, in the last line we are invoking <code>funcOne</code> which will now act as a function rather than a variable and again the whole cycle will repeat.</p>
<p>So, that's it guys in this blog. In the next blog, we will talk about the variable declared using keywords <code>let</code> and <code>const</code>, and also we will travel around the <code>Temporal Dead Zone</code>. Don't worry we will not die there. So, till then see you in the next blog.</p>
]]></content:encoded></item><item><title><![CDATA[JavaScript: Behind The Scene]]></title><description><![CDATA[Introduction
I think we all like to watch BTS(Behind The Scene), whether it is a BTS of a movie or it could be BTS of your favorite show. But have you ever imagined if we could watch behind the scene of a programming language?
Yes, you heard it right...]]></description><link>https://blogs.sobitprasad.com/javascript-behind-the-scene</link><guid isPermaLink="true">https://blogs.sobitprasad.com/javascript-behind-the-scene</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[javascript framework]]></category><category><![CDATA[fullstack]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[Programming Blogs]]></category><dc:creator><![CDATA[Sobit Prasad]]></dc:creator><pubDate>Mon, 14 Feb 2022 08:38:32 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1644732852831/Vi8qwLNQv.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3 id="heading-introduction">Introduction</h3>
<p>I think we all like to watch <strong>BTS(Behind The Scene)</strong>, whether it is a BTS of a movie or it could be BTS of your favorite show. But have you ever imagined if we could watch behind the scene of a<strong> programming language</strong>?</p>
<p>Yes, you heard it right we can see BTS of a programming language. So in this blog, we will see <strong><strong>how JavaScript actually works behind the scene?</strong></strong></p>
<h3 id="heading-what-happens-when-we-run-our-javascript-program">What happens when we run our JavaScript program?</h3>
<p>So when you run your beautiful code in JavaScript, an <strong>Execution Context</strong> is created. So if you are wondering what the heck is this Execution Context, you can think it of like the movie set where all the shots of the movies are to be taken. So everything in JavaScript happens inside this Execution Context.</p>
<p>In the Execution Context, there are two main components. </p>
<ol>
<li>Memory Component (also known as <strong>Variable Environment</strong>)</li>
<li>Code Component (also known as <strong>Thread of Execution</strong>)</li>
</ol>
<h4 id="heading-memory-component">Memory Component</h4>
<p>In Memory Component, all the values of the variables are assigned in a key-value pair as simple as that.</p>
<h4 id="heading-code-component">Code Component</h4>
<p>In Code Component, our code gets executed line by line in a specific order. We will understand it more deeply when we will talk about the phases that occur when we run our code. But for now, just keep in mind that when we run our code, an Execution Context is created and it has two components - memory and code component.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1644775324650/jFhQNGnBK3.png" alt="JavaScript Behind The Scene Banner (1).png" /></p>
<h3 id="heading-what-after-the-execution-context">What after the Execution Context?</h3>
<p>So far we know that when we run our code an Execution Context is created. Now, our code has to go through two beautiful phases and these phases are - </p>
<ul>
<li><strong>PHASE 1: MEMORY CREATION PHASE</strong></li>
</ul>
<p>In this phase, our codes get scanned and all the variables are assigned with a value of <code>undefined</code>
but in the case of <code>function</code>, it stores the whole code inside that function name. We will understand it later with the help of an example.</p>
<p><strong>PHASE 2: CODE EXECUTION PHASE</strong></p>
<p>In this phase, our codes run line by line in a specific order, and all the actual values of the variable
get replaced by <code>undefined</code> which was held earlier as a placeholder.</p>
<h3 id="heading-example-understanding-execution-context-with-the-help-of-an-example">EXAMPLE: Understanding Execution Context with the help of an example</h3>
<p>I know it might be a little overwhelming, but don't worry let's understand the whole concept with the help of an example. Suppose this is the code we want to execute.</p>
<pre><code><span class="hljs-keyword">var</span> a <span class="hljs-operator">=</span> <span class="hljs-number">7</span>;
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">cube</span>(<span class="hljs-params">n</span>)</span>{
   <span class="hljs-keyword">var</span> b <span class="hljs-operator">=</span> n<span class="hljs-operator">*</span>n<span class="hljs-operator">*</span>n;
   <span class="hljs-keyword">return</span> b;
}
<span class="hljs-keyword">var</span> c <span class="hljs-operator">=</span> cube(a);
</code></pre><p>Now when we run this code an Execution Context is created and inside the Execution Context it has to go through two phases - <strong>MEMORY CREATION PHASE</strong> and <strong>CODE EXECUTION PHASE</strong>. First, it will go through Memory Creation Phase and assign the memory to all the variables. It will assign <code>undefined</code> to variable <code>a</code> and <code>c</code> and also it will assign the whole code inside function <code>cube</code> to <code>cube</code>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1644779750898/I_XvkBuXc.png" alt="memory creation phase.png" /></p>
<p>Now, here comes the Second Phase i.e. the <strong>Code Execution Phase</strong>. In this phase, our code will run line by line. So, when it goes to the first line, it will assign <code>7</code> to variable <code>a</code>. Now, it will move to the next line and founds that there is nothing to execute so it will jump to the sixth line. Now, the sixth line is invoking the function <code>cube</code> with parameter <code>a</code> which holds the value 7. Now, when a new function is invoked, another execution context is created inside the previous one and again it will follow the same procedure.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1644818817910/xNnLcT5je.png" alt="execution-memory.png" /></p>
<p>Now in this execution context (i.e. the execution context inside the Global Execution Context), again it has to go through <strong>Memory Creation Phase</strong> and <strong>Code Execution Phase</strong>. In Memory Creation Phase, it will assign <code>undefined</code> to variables <code>n</code> and <code>b</code>. Now, it will move to the next phase i.e. the Code Execution Phase. In this phase, variable <code>n</code> will be assigned with value <code>a</code> because it was the parameter of the function <code>cube</code> with variable <code>c</code>, now <code>a</code> will be replaced by <code>7</code> which is taken from the Global Execution Context. Now finally the output of variable <code>b</code> i.e <code>343</code> will be returned to variable <code>c</code> in the Global Execution Context. Now after that, firstly the Local Execution Context will be deleted and after returning the value of variable <code>c</code>, the Global Execution Context will be deleted.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1644822858917/LJWGZDfWW.png" alt="final.png" /></p>
<p>Now, if you are wondering how JavaScript handles all this, I mean this is a lot. Suppose if we invoke a function inside another function and again inside another function, a number of 'Execution Context' will be created, but all this handles by JavaScript very beautifully. So how does it happen? Ladies and Gentlemen, give a big round of applauding to none other than our very dear<strong> CALLSTACK</strong>.</p>
<h3 id="heading-callstack-the-game-changer">CallStack:  The Game Changer</h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1644825567603/9sw8gh6Ff.png" alt="callstack.png" /></p>
<p>We know that JavaScript is a <strong>synchronous single-threaded</strong> programming language and thus it has only one CALLSTACK which means that it can perform only one command at a time in a specific order. <strong>So, what basically CALLSTACK does do?</strong> </p>
<p>CALLSTACK maintains the <strong>order of execution</strong> of EXECUTION CONTEXT which means that when we run our code the global execution context that is created at first will be pushed to the stack first and again if another function is invoked/called, it will be pushed at the top of CALLSTACK and again if another function is invoked it will be pushed to the top. Now when the task of the <code>function</code> at the top is completed it will be removed from the stack and at the end, the Global Execution Context is deleted.</p>
<p>This is how it looks Behind The Scene of JavaScript. Isn't it amazing? If you are reading till here, thank you so much for that, I appreciate it. Please give your suggestions/corrections below in the comment section, I will be very happy to know your ideas as well. Till then, see you in the next blog.</p>
]]></content:encoded></item></channel></rss>