<?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[Ashish Dev's Journal]]></title><description><![CDATA[Ashish Dev's Journal]]></description><link>https://blog.ashishkumarsaini.dev</link><generator>RSS for Node</generator><lastBuildDate>Tue, 09 Jun 2026 21:55:39 GMT</lastBuildDate><atom:link href="https://blog.ashishkumarsaini.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Expo Router vs React Navigation]]></title><description><![CDATA[What routing means in mobile applications]]></description><link>https://blog.ashishkumarsaini.dev/expo-router-vs-react-navigation</link><guid isPermaLink="true">https://blog.ashishkumarsaini.dev/expo-router-vs-react-navigation</guid><dc:creator><![CDATA[Ashish Kumar Saini]]></dc:creator><pubDate>Fri, 22 May 2026 20:37:46 GMT</pubDate><content:encoded><![CDATA[<p>What routing means in mobile applications</p>
]]></content:encoded></item><item><title><![CDATA[How Instagram, WhatsApp, Uber & Netflix Would Be Built Today Using Expo Router]]></title><description><![CDATA[Most of the react native tutorials teaches you how to build application or new screens but very few talks about the systems.
That is why the developers can easily build attractive screens but failed t]]></description><link>https://blog.ashishkumarsaini.dev/mobile-dev-architecture-with-expo</link><guid isPermaLink="true">https://blog.ashishkumarsaini.dev/mobile-dev-architecture-with-expo</guid><dc:creator><![CDATA[Ashish Kumar Saini]]></dc:creator><pubDate>Fri, 22 May 2026 20:32:44 GMT</pubDate><content:encoded><![CDATA[<p>Most of the react native tutorials teaches you how to build application or new screens but very few talks about the systems.</p>
<p>That is why the developers can easily build attractive screens but failed to manage the architecture when the application scales.</p>
<p>Making a small app is easy but a production scale application is completely different engineering challenge.</p>
<p>The architecture with:</p>
<ul>
<li><p>5 screens</p>
</li>
<li><p>1 developer</p>
</li>
<li><p>3 - 4 API calls</p>
</li>
</ul>
<p>will be completely get collapsed when application become:</p>
<ul>
<li><p>Hundred of screens</p>
</li>
<li><p>Millions of users</p>
</li>
<li><p>Multiple team members</p>
</li>
<li><p>Realtime systems</p>
</li>
<li><p>Offline support</p>
</li>
<li><p>Complex navigations</p>
</li>
<li><p>Background synchronisation</p>
</li>
</ul>
<p>That's why the big companies like Instagram, Whatsapp, User ... invest heavy in architecture engineering.</p>
<p>The UI is just a surface for interaction. The actual complexity in underneath.</p>
<p>Let's explore more about how modern large applications are structured, and how the architecture matters in React Native.</p>
<h2>Why Simple folder structure fails to scale</h2>
<p>Most beginner react native start like this:</p>
<pre><code class="language-javascript">/components
/screens
/navigation
/hooks
/utils
/services
</code></pre>
<p>At first, this structure feels organized but then the app grows. Suddenly:</p>
<ul>
<li><p><code>/components</code> has 400 files</p>
</li>
<li><p><code>/screens</code> becomes impossible to navigate</p>
</li>
<li><p>Logic might be duplicate</p>
</li>
<li><p>API calls logic are not organized</p>
</li>
<li><p>Navigation becomes tangled</p>
</li>
</ul>
<p>This happens because the structure is organized for small projects, not scalable systems.</p>
<p>Example:</p>
<pre><code class="language-javascript">/components
    Button.tsx
    MessageBubble.tsx
    FeedCard.tsx
</code></pre>
<p>These files belong to completely different domains:</p>
<ul>
<li><p>Button - Shared UI systems</p>
</li>
<li><p>MessageBubble - Messaging</p>
</li>
<li><p>FeedCard - Ratings</p>
</li>
</ul>
<p>As application scale, this creates:</p>
<ul>
<li><p>Tight coupling</p>
</li>
<li><p>Dependency confusion</p>
</li>
<li><p>Hard to refactor</p>
</li>
</ul>
<p>Now, you can see that the architecture has become more important than UI.</p>
<h2>Architecture Thinking vs Small-App Thinking</h2>
<p>Small app development focuses on:</p>
<p><strong>How do I make this screen work?</strong></p>
<p>Production engineering focuses on:</p>
<p><strong>How will this system survive growth?</strong></p>
<p>This difference actual change everything. Production engineering focuses on:</p>
<ul>
<li><p>Maintainability</p>
</li>
<li><p>Scalability</p>
</li>
<li><p>Developer experience</p>
</li>
<li><p>Performance</p>
</li>
<li><p>Reliability</p>
</li>
<li><p>Long-term evolution</p>
</li>
<li><p>Team collaboration</p>
</li>
<li><p>Feature isolation</p>
</li>
</ul>
<p>At scale, architecture becomes a business decision.</p>
<p>Because poor architecture eventually slows down the entire company.</p>
<h2>The Evolution of Mobile App Architecture</h2>
<p>Most apps evolve through stages:</p>
<h3>Beginner Architecture</h3>
<pre><code class="language-plaintext">/components
/screens
/navigation
</code></pre>
<p>Works fine for:</p>
<ul>
<li><p>Personal projects</p>
</li>
<li><p>MVP's</p>
</li>
<li><p>Small demos</p>
</li>
</ul>
<p>But fails for:</p>
<ul>
<li><p>Multiple developers can join</p>
</li>
<li><p>The feature will become interconnected</p>
</li>
<li><p>Business logic grows</p>
</li>
</ul>
<h3>Medium Scale Architecture</h3>
<p>Developer starts separating:</p>
<pre><code class="language-plaintext">/api
/store
/hooks
/navigation
/modules
</code></pre>
<p>This improves the organization of code.</p>
<p>But eventually:</p>
<ul>
<li><p>Features still depend on each other heavily</p>
</li>
<li><p>Shared state becomes more complex</p>
</li>
<li><p>Growing navigation is difficult to manage.</p>
</li>
</ul>
<h3>Production Features Architecture</h3>
<p>Large applications usually shift towards feature-based architecture.</p>
<p>Instead of organizing by file type:</p>
<pre><code class="language-plaintext">/components
/hooks/services
</code></pre>
<p>Example:</p>
<pre><code class="language-plaintext">/features
    /auth
    /feed
    /chat
    /profile
    /payments
</code></pre>
<p>This is one of the biggest architectural transitions in large scale enginerring.</p>
]]></content:encoded></item><item><title><![CDATA[Async/Await in JavaScript]]></title><description><![CDATA[As a Javascript developer, you have seen the application become more interactive and started handling more asynchronous operations like API calls, file readings, and timers.
Initially, developers rely]]></description><link>https://blog.ashishkumarsaini.dev/async-await-in-javascript</link><guid isPermaLink="true">https://blog.ashishkumarsaini.dev/async-await-in-javascript</guid><category><![CDATA[asynchronous JavaScript]]></category><category><![CDATA[async/await]]></category><dc:creator><![CDATA[Ashish Kumar Saini]]></dc:creator><pubDate>Fri, 22 May 2026 19:45:26 GMT</pubDate><content:encoded><![CDATA[<p>As a Javascript developer, you have seen the application become more interactive and started handling more asynchronous operations like API calls, file readings, and timers.</p>
<p>Initially, developers rely heavily on callbacks, the promises start improving the situation, and finally, async/await code make easier to handle the asynchronous operations.</p>
<p>In this article, you'll learn:</p>
<ol>
<li><p>Why async/await was introduced</p>
</li>
<li><p>How async functions work</p>
</li>
<li><p>The concept of the await keyword</p>
</li>
<li><p>Error handling in async code</p>
</li>
<li><p>Comparison with promises</p>
</li>
<li><p>Execution flow</p>
</li>
</ol>
<h2>Why Async/Await Was Introduced</h2>
<p>Before async/await, developers mainly used:</p>
<ol>
<li><p>Callbacks Promises<br />Callbacks often led to deeply nested code, sometimes called callback hell.</p>
<pre><code class="language-javascript">getUser(function(user) { 
    getPosts(user.id, function(posts) { 
        getComments(posts[0].id, function(comments) {
            console.log(comments);
        });
    });
});
</code></pre>
</li>
<li><p>Promises improved this by flattening the structure:</p>
<pre><code class="language-javascript">getUser()
  .then(user =&gt; getPosts(user.id))
  .then(posts =&gt; getComments(posts[0].id))
  .then(comments =&gt; console.log(comments))
  .catch(error =&gt; console.log(error));
</code></pre>
<p>While promises were cleaner, chaining multiple .then() calls could still become difficult to read.<br />That’s why async/await was introduced. It allows asynchronous code to look almost like synchronous code.</p>
</li>
</ol>
<h2>Async/Await Is Syntactic Sugar</h2>
<p>async/await is basically syntactic sugar over promises.</p>
<p>That means it does not replace promises internally. It simply provides a cleaner syntax for working with them.</p>
<p>This:</p>
<pre><code class="language-javascript">async function example() {
    return "Hello";
}
</code></pre>
<p>Is internally similar to:</p>
<pre><code class="language-javascript">function example() {
    return Promise.resolve("Hello");
} 
</code></pre>
<h2>How Async Functions Work</h2>
<p>An async function always returns a promise.</p>
<pre><code class="language-javascript">async function greet() {
    return "Hello World";
}

greet()
  .then(console.log);

// Output: Hello World
</code></pre>
<p>Even though we returned a string, JavaScript automatically wraps it inside a promise.</p>
<p><strong>Basic Async Function Example</strong></p>
<pre><code class="language-javascript">async function fetchData() {
  return "Data received";
}

fetchData().then(result =&gt; {
  console.log(result);
});

// Output: Data received
</code></pre>
<h2>Understanding the Await Keyword</h2>
<p>The <code>await</code> keyword pauses the execution of an async function until a promise resolves.</p>
<pre><code class="language-javascript">function delay() {
  return new Promise(resolve =&gt; {
    setTimeout(() =&gt; {
      resolve("Done!");
    }, 2000);
  });
}

async function run() {
  const result = await delay();
  console.log(result);
}

run();

// Output after 2 second: Done!
</code></pre>
<h2>How Await Improves Readability</h2>
<p>Without <code>await</code>:</p>
<pre><code class="language-javascript">fetchUser()
  .then(user =&gt; {
    return fetchPosts(user.id);
  })
  .then(posts =&gt; {
    console.log(posts);
  });
</code></pre>
<p>With <code>async/await</code>:</p>
<pre><code class="language-javascript">async function showPosts() {
  const user = await fetchUser();
  const posts = await fetchPosts(user.id);

  console.log(posts);
}
</code></pre>
<p>The second version looks much more natural and easier to follow.</p>
]]></content:encoded></item><item><title><![CDATA[Error Handling in JavaScript: try, catch, finally]]></title><description><![CDATA[While writing a Javascript code, no matter how carefully you have written the code but once the user input a invalid data and the API fails, the application might crash at runtime due to some edge cas]]></description><link>https://blog.ashishkumarsaini.dev/error-handling-in-javascript</link><guid isPermaLink="true">https://blog.ashishkumarsaini.dev/error-handling-in-javascript</guid><category><![CDATA[error handling]]></category><category><![CDATA[js-error-handling]]></category><category><![CDATA[error handling js]]></category><category><![CDATA[JavaScript]]></category><dc:creator><![CDATA[Ashish Kumar Saini]]></dc:creator><pubDate>Sat, 09 May 2026 18:55:15 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/696877fccb285855f0758646/fdc064af-bce3-432b-9dd4-f0218492d17b.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>While writing a Javascript code, no matter how carefully you have written the code but once the user input a invalid data and the API fails, the application might crash at runtime due to some edge case or unexpected behaviour.</p>
<p>That's why the error handling is important skills for every Javascript developer. Good error handling makes applications more stable, easier to debug, and much more user-friendly.</p>
<p>In this article we will understand how error works in Javascript and learn more about how to tackle those scenarios using try, catch and finally.</p>
<h2>What Are Errors in JavaScript?</h2>
<p>Errors are problems that occur while the code is running. These problems can stop the normal execution of the program.</p>
<p>For example:</p>
<pre><code class="language-javascript">console.log(userName);

// ReferenceError: userName is not defined
</code></pre>
<p>Here, JavaScript throws an error because of the variable does not exist.</p>
<p>Another example:</p>
<pre><code class="language-javascript">const user = null;

console.log(user.name);

// TypeError: Cannot read properties of null
</code></pre>
<p>These are called runtime errors because they happen while the program is running.</p>
<h2>Common Types of JavaScript Errors</h2>
<ol>
<li><p>ReferenceError<br />Occurs when a variable does not exist.</p>
<pre><code class="language-javascript">console.log(age);
</code></pre>
</li>
<li><p>TypeError<br />Occurs when a value is used incorrectly.</p>
<pre><code class="language-javascript">const num = 10;

num.toUpperCase();
</code></pre>
<p>Numbers do not have toUpperCase().</p>
</li>
<li><p>SyntaxError<br />Occurs when JavaScript syntax is invalid.</p>
<pre><code class="language-javascript">if(true {
    console.log("Hello");
}
</code></pre>
<p>Missing closing bracket.</p>
</li>
</ol>
<h2>Why Error Handling Matters</h2>
<p>Imagine a shopping website where a single error can crash the entire website. Once crashed, the user will immediately leaves the website without purchasing.</p>
<p>To handle this, developer has to handle the error gracefully. This means:</p>
<ul>
<li><p>Showing a meaningful message</p>
</li>
<li><p>Prevent app crashes</p>
</li>
<li><p>If once part of website is crashed, should be handled that it will not crash entire website</p>
</li>
<li><p>For developers, make debugging easier. Error handling also helps developers quickly identify problems during development.</p>
</li>
</ul>
<p>Without proper error handling, debugging large applications becomes extremely difficult.</p>
<h2>Using try and catch in JavaScript</h2>
<p>JavaScript provides try and catch blocks to safely handle errors.</p>
<p>Basic syntax:</p>
<pre><code class="language-javascript">try { 
// risky code 
} catch(error) { 
// handle error 
}
</code></pre>
<p>The code inside try block will get execute first. If any error occurs, the execution of try block code immediately stops and the control move to the catch block.</p>
<p>The error object now contains the error that occurred in the try block.</p>
<p>Example:</p>
<pre><code class="language-javascript">try {
  const user = null;

  console.log(user.name);
} catch(error) {
  console.log("Something went wrong");
  console.log(error.message);
}

// Output
// Something went wrong
// Cannot read properties of null
</code></pre>
<p>Instead of crashing the application, the error is handled properly.</p>
<h2>Understanding Graceful Failure</h2>
<p>Graceful failure means handling errors in a controlled way.</p>
<ul>
<li><p>Displaying the message "App Crashed!" to the user is a bad practice.</p>
</li>
<li><p>"Unable to load your profile. Please try again later." - Displaying a custom message like this is a good user experience. The user should never see the technical errors.</p>
</li>
</ul>
<p>That’s why developers use error handling to improve user experience.</p>
<h2>Understanding Error Object</h2>
<p>Inside catch, JavaScript provides an error object.</p>
<p>Example:</p>
<pre><code class="language-javascript">try { 
    console.log(data);
} catch(error) {
    console.log(error);
}
</code></pre>
<p>The error object contains useful information like:</p>
<ol>
<li><p>name</p>
</li>
<li><p>message</p>
</li>
<li><p>stack</p>
</li>
</ol>
<p>Example:</p>
<pre><code class="language-javascript">console.log(error.name); 
// ReferenceError

console.log(error.message);
// data is not defined
</code></pre>
<p>This information is very useful while debugging applications.</p>
<h2>The finally Block</h2>
<p>Sometimes we want code to run in both cases, whether an error occurs or not.</p>
<p>That’s where finally is used.</p>
<p>Syntax:</p>
<pre><code class="language-javascript">try {
    // code 
} catch(error) {
    // handle error 
} finally {
    // always runs
} 
</code></pre>
<p>Example:</p>
<pre><code class="language-javascript">try {
    console.log("Trying...");
    riskyFunction(); 
} catch(error) {
    console.log("Error handled"); 
} finally {
    console.log("Execution completed");
}

// Trying...
// Error handled
// Execution completed
</code></pre>
<p>The finally block always runs.</p>
<h3>Where is finally useful</h3>
<p>The finally block is commonly used for:</p>
<ol>
<li><p>Closing database connections</p>
</li>
<li><p>Stopping loaders/spinners</p>
</li>
<li><p>Cleaning resources</p>
</li>
<li><p>Resetting states</p>
</li>
</ol>
<p>Example:</p>
<pre><code class="language-javascript">try {
    console.log("Fetching data...");
} catch(error) {
    console.log("API failed");
} finally {
    console.log("Hide loading spinner");
}
</code></pre>
<p>Even if the API fails, the loading spinner will still stop.</p>
<h2>Throwing Custom Errors</h2>
<p>JavaScript also allows developers to create their own errors using throw. This is useful when we want to validate data manually.</p>
<p>Example" of throw const age = -5;</p>
<pre><code class="language-javascript">try {
    if(age &lt; 0) {
        throw new Error("Age cannot be negative"); 
    }
    console.log("Valid age"); 
} catch(error) {
    console.log(error.message); 
}
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">Age cannot be negative
</code></pre>
<p>Here, we manually created a custom error.</p>
<h3>Why Custom Errors Are Useful</h3>
<p>Custom errors help developers:</p>
<ol>
<li><p>Validate user input</p>
</li>
<li><p>Create meaningful messages</p>
</li>
<li><p>Improve debugging</p>
</li>
<li><p>Control application flow</p>
</li>
</ol>
<p>For example:</p>
<pre><code class="language-javascript">throw new Error("Password must contain 8 characters");
</code></pre>
<p>This message is much clearer than a generic error.</p>
<h2>Conclusion</h2>
<p>Errors are a normal part of programming. What matters is how we handle them.</p>
<p>JavaScript provides powerful tools like:</p>
<p>try catch finally throw</p>
<p>These features help developers build reliable and user-friendly applications.</p>
<p>Good error handling prevents crashes, improves debugging, and creates a smoother experience for users.</p>
<p>Instead of fearing errors, developers should learn how to handle them gracefully. That’s what makes applications truly production-ready.</p>
]]></content:encoded></item><item><title><![CDATA[Understanding this, call(), apply(), and bind() in JavaScript]]></title><description><![CDATA[JavaScript gives developers a lot of flexibility, but one thing that confuses almost everyone at first is this.
In this article, we’ll understand:

What this means in JavaScript

How this behaves in f]]></description><link>https://blog.ashishkumarsaini.dev/this-call-apply-and-bind-in-javascript</link><guid isPermaLink="true">https://blog.ashishkumarsaini.dev/this-call-apply-and-bind-in-javascript</guid><category><![CDATA[this keyword in javascript]]></category><category><![CDATA[call apply and bind methods]]></category><dc:creator><![CDATA[Ashish Kumar Saini]]></dc:creator><pubDate>Fri, 08 May 2026 21:07:02 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/696877fccb285855f0758646/12a6b805-42a5-45b6-b2e7-d5e3d939ce7e.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>JavaScript gives developers a lot of flexibility, but one thing that confuses almost everyone at first is <code>this</code>.</p>
<p>In this article, we’ll understand:</p>
<ul>
<li><p>What <code>this</code> means in JavaScript</p>
</li>
<li><p>How <code>this</code> behaves in functions and objects</p>
</li>
<li><p>What does call(), apply(), and bind() do and their differences</p>
</li>
<li><p>Simple real-world examples</p>
</li>
</ul>
<p>Let’s make it simple.</p>
<h2>What is <code>this</code> in JavaScript?</h2>
<p>The easiest way to understand the concept of <code>this</code>. Just remember one thing:</p>
<p><strong>This refers to the object that is calling the function.</strong></p>
<p>In simple words, whoever calls the function becomes <code>this</code> for the function.</p>
<h3>Inside Object</h3>
<p>Example:</p>
<pre><code class="language-javascript">const user = {
    name: 'Rahul',
    greet: function (){
        console.log(`Hello ${this.name}`)
    }
}

user.greet();
</code></pre>
<p>Here, <code>user</code> calls the greet function.</p>
<p>So, <code>this</code> -&gt; <code>user</code> for greet function.</p>
<pre><code class="language-javascript">const person1 = {
    name: "Rahul",
    greet() {
        console.log(`Hello ${this.name}`);
    }
};

const person2 = { name: "Aman", };

person2.greet = person1.greet;

person2.greet();
</code></pre>
<p>Here, as the person2.greet is initialized with person1.greet.</p>
<p>But still, as the person2 is calling the greet function, the output will be 'Hello Aman'</p>
<h3>Inside Normal Functions</h3>
<p>Let’s understand with a regular function example.</p>
<pre><code class="language-javascript">function show() { 
    console.log(this);
}

show();
</code></pre>
<p>In browsers, this usually prints <code>window</code>, because the show function is directly called from the global object (i.e. <code>window</code> for browser).</p>
<p>But in strict mode:</p>
<pre><code class="language-javascript">"use strict"

function show() {
    console.log(this);
}

show();
</code></pre>
<p>The output becomes <code>undefined</code>.</p>
<p>That’s because strict mode prevents JavaScript from automatically attaching this to the global object.</p>
<h2>What is call() in JavaScript?</h2>
<p><code>call()</code> lets you manually decide what this should be.</p>
<p>Syntax:</p>
<pre><code class="language-javascript">functionName.call(thisValue, arg1, arg2)
</code></pre>
<p>functionName.call(thisValue, arg1, arg2)</p>
<p>Example:</p>
<pre><code class="language-javascript">const user = { name: "Ashish", }

function greet(city) {
    console.log(`Hello \({this.name} from \){city}`) 
}

greet.call(user, "Delhi")
</code></pre>
<p>Output: Hello Ashish from Delhi</p>
<p>Here what happened, you can see the <code>greet</code> is not attached to the <code>user</code> object, but if I want to pass the <code>user</code> as a context to the <code>greet</code>, we can use <code>call()</code>.</p>
<p>call() is commonly used for:</p>
<ul>
<li><p>Function borrowing</p>
</li>
<li><p>Reusing methods</p>
</li>
<li><p>Setting custom this</p>
</li>
</ul>
<p>Example:</p>
<pre><code class="language-javascript">const person1 = {
    name: "Rahul",
    introduce() {
        console.log(`Hi, I am ${this.name}`)
    },
};

const person2 = { name: "Aman" };

person1.introduce.call(person2);
</code></pre>
<p>Output: Hi, I am Aman</p>
<p>Here, person2 borrowed the method from person1.</p>
<h2>What is apply() in JavaScript?</h2>
<p><code>apply()</code> works almost exactly like <code>call()</code>.</p>
<p>The only difference is that <code>apply()</code> it accepts arguments as an array.</p>
<p>Syntax:</p>
<pre><code class="language-javascript">functionName.apply(thisValue, [args]);
</code></pre>
<p>Example:</p>
<pre><code class="language-javascript">const user = { name: "Ashish" };

function greet(city, country) {
    console.log(`Hello \({this.name} from \){city}, ${country}`) 
}

greet.apply(user, ["Delhi", "India"]);
</code></pre>
<p>Output: Hello Ashish from Delhi, India</p>
<h2>call() vs apply()</h2>
<p>Both do the same thing:</p>
<ul>
<li><p>They immediately invoke the function</p>
</li>
<li><p>They manually set this</p>
</li>
</ul>
<p>The difference is only in how arguments are passed.</p>
<ul>
<li><p>call:</p>
<pre><code class="language-javascript">greet.call(user, "Delhi", "India");
</code></pre>
</li>
<li><p>apply:</p>
<pre><code class="language-javascript">greet.apply(user, ["Delhi", "India"]);
</code></pre>
</li>
</ul>
<h2>What is bind() in JavaScript?</h2>
<p><code>bind()</code> is slightly different than call and apply.</p>
<p>Instead of immediately calling the function, bind() returns a new function.</p>
<p>Syntax:</p>
<pre><code class="language-javascript">functionName.bind(thisValue);
</code></pre>
<p>Example:</p>
<pre><code class="language-javascript">const user = { name: "Ashish" };

function greet() {
    console.log(`Hello ${this.name}`);
}

const newFunction = greet.bind(user);

newFunction();
</code></pre>
<p>Output: Hello Ashish</p>
<p><strong>Why is bind() Useful?</strong></p>
<p>bind() is useful when you want to:</p>
<ul>
<li><p>Store a function</p>
</li>
<li><p>Pass functions around</p>
</li>
<li><p>Keep the correct this</p>
</li>
</ul>
<p>Example:</p>
<pre><code class="language-javascript">const user = {
    name: "Ashish",
    greet() {
        console.log(this.name) 
    },
}

const button = user.greet;

button();
</code></pre>
<p>This may lose the correct <code>this</code>.</p>
<p>Using <code>bind()</code>:</p>
<pre><code class="language-javascript">const button = user.greet.bind(user)

button()
</code></pre>
<p>Now this always points to user.</p>
<h2>Real Difference Between call, apply, and bind</h2>
<table>
<thead>
<tr>
<th>Method</th>
<th>Calls Function Immediately</th>
<th>Arguments Style</th>
<th>Returns New Function?</th>
</tr>
</thead>
<tbody><tr>
<td>call</td>
<td>Yes</td>
<td>Separate arguments</td>
<td>No</td>
</tr>
<tr>
<td>apply</td>
<td>Yes</td>
<td>Array of arguments</td>
<td>No</td>
</tr>
<tr>
<td>bind</td>
<td>No</td>
<td>Separate arguments</td>
<td>Yes</td>
</tr>
</tbody></table>
<h2>Simple Visual Understanding</h2>
<p>Function → Caller Relationship:</p>
<ul>
<li><p>this</p>
<pre><code class="language-plaintext">user.greet()

caller -&gt; user
this -&gt; user
</code></pre>
</li>
<li><p>call</p>
<pre><code class="language-plaintext">greet.call(user, 'Pankaj', 26);

Caller manually set to user2
this = user2
</code></pre>
</li>
<li><p>apply</p>
<pre><code class="language-plaintext">greet.apply(user, ["Delhi", "India"])

Caller manually set to user2, arguments passed as array
this = user2
</code></pre>
</li>
<li><p>bind</p>
<pre><code class="language-plaintext">const fn = greet.bind(user)

Creates a new function
this = user
</code></pre>
</li>
</ul>
<h2>Final Thoughts</h2>
<p>Understanding this is one of the biggest turning points in JavaScript.</p>
<p>Once you understand the concept of who is calling the function, how <code>call()</code>, <code>apply()</code> , and <code>bind()</code> control <code>this</code></p>
<p>JavaScript becomes much easier to read and debug.</p>
<p>The best way to master these concepts is to practice small examples repeatedly.</p>
<p>Start simple, experiment with different callers, and everything will begin to click naturally.  </p>
<p>Follow the series to learn more about Javascript.</p>
]]></content:encoded></item><item><title><![CDATA[Understanding the new Keyword in JavaScript]]></title><description><![CDATA[In JavaScript, the new keyword is used to create a new object from a constructor function.
Think of a constructor function like a blueprint, and new as the tool that builds an actual object from that ]]></description><link>https://blog.ashishkumarsaini.dev/understanding-the-new-keyword-in-javascript</link><guid isPermaLink="true">https://blog.ashishkumarsaini.dev/understanding-the-new-keyword-in-javascript</guid><category><![CDATA[new keyword]]></category><category><![CDATA[js-new-keyword]]></category><category><![CDATA[JavaScript]]></category><dc:creator><![CDATA[Ashish Kumar Saini]]></dc:creator><pubDate>Thu, 07 May 2026 22:04:37 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/696877fccb285855f0758646/b7c88841-1847-48a3-b523-7d69a87cd2bf.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In JavaScript, the <code>new</code> keyword is used to create a new object from a constructor function.</p>
<p>Think of a constructor function like a blueprint, and <code>new</code> as the tool that builds an actual object from that blueprint.</p>
<pre><code class="language-javascript">function User(name, age) {
  this.name = name;
  this.age = age;
}

const user1 = new User("Rahul", 22);

console.log(user1.name); // Rahul
console.log(user1.age);  // 22
</code></pre>
<p>Here, <code>User</code> is a constructor function, and <code>user1</code> is an object created from it.</p>
<p>When we write:</p>
<pre><code class="language-javascript">const user1 = new User("Rahul", 22);
</code></pre>
<p>JavaScript does a few things behind the scenes:</p>
<ol>
<li><p>Creates a new empty object.</p>
</li>
<li><p>Sets <code>this</code> to point to that new object.</p>
</li>
<li><p>Links the object to the constructor’s prototype.</p>
</li>
<li><p>Runs the constructor function.</p>
</li>
<li><p>Returns the newly created object.</p>
</li>
</ol>
<p>So internally, it feels something like this:</p>
<pre><code class="language-javascript">const user1 = {};
user1.name = "Rahul";
user1.age = 22;
</code></pre>
<p>But <code>new</code> does this in a proper JavaScript way, including prototype linking.</p>
<h3>Constructor Functions</h3>
<p>Constructor functions are normal functions, but they are usually written with a capital first letter.</p>
<pre><code class="language-javascript">function Car(brand, model) {
  this.brand = brand;
  this.model = model;
}
</code></pre>
<p>Now we can create multiple car objects:</p>
<pre><code class="language-javascript">const car1 = new Car("Toyota", "Fortuner");
const car2 = new Car("Honda", "City");

console.log(car1.brand); // Toyota
console.log(car2.brand); // Honda
</code></pre>
<p>Each object gets its own values, but both are created from the same constructor.</p>
<h3>How <code>new</code> Links Prototypes</h3>
<p>Every function in JavaScript has a <code>prototype</code> object.</p>
<p>When we create an object using <code>new</code> keyword, that new object gets linked to the constructor’s prototype.</p>
<pre><code class="language-javascript">function Person(name) {
  this.name = name;
}

Person.prototype.sayHello = function () {
  console.log(`Hello, my name is ${this.name}`);
};

const person1 = new Person("John");

person1.sayHello(); // Hello, my name is John
</code></pre>
<p>Here, <code>sayHello</code> is not directly inside <code>person1</code>. It comes from <code>Person.prototype</code>.</p>
<p>So the relation looks like this:</p>
<pre><code class="language-plaintext">Person constructor -&gt; Person.prototype -&gt; person1 object
</code></pre>
<p>Or in simple words:</p>
<pre><code class="language-plaintext">Constructor Function -&gt; Prototype -&gt; Instance Object
</code></pre>
<h3>Why This Is Useful</h3>
<p>Using prototypes helps us avoid repeating the same method inside every object.</p>
<p>Instead of creating a new copy of <code>sayHello</code> for every person, JavaScript stores it once in the prototype, and all instances can use it.</p>
<pre><code class="language-javascript">const person2 = new Person("Rahul");

person1.sayHello();
person2.sayHello();
</code></pre>
<p>Both objects can use the same method from the prototype.</p>
<h2><code>new</code> keyword with Classes in JavaScript</h2>
<p>Classes in JavaScript are a cleaner and more modern way to create constructor functions.</p>
<p>Behind the scenes, classes still work using prototypes and the <code>new</code> keyword.</p>
<h2>Creating Objects with Classes</h2>
<pre><code class="language-javascript">class User {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
}

const user1 = new User("Pankaj", 22);

console.log(user1.name); // Pankaj
console.log(user1.age);  // 22
</code></pre>
<p>Here:</p>
<ul>
<li><p><code>User</code> is a class</p>
</li>
<li><p><code>constructor()</code> runs automatically when <code>new</code> is used</p>
</li>
<li><p><code>user1</code> becomes an instance of the class</p>
</li>
</ul>
<p>Without <code>new</code>, classes cannot create instances.</p>
<pre><code class="language-javascript">const user1 = User("Pankaj");
</code></pre>
<p>This throws an error:</p>
<pre><code class="language-plaintext">Class constructor User cannot be invoked without 'new'
</code></pre>
<p>Because classes are designed specifically for object creation through <code>new</code>.</p>
<h3>Final Thought</h3>
<p>The <code>new</code> keyword is mainly responsible for creating object instances from constructor functions.</p>
<p>It creates a fresh object, connects it with the constructor’s prototype, and sets <code>this</code> to that object, and returns it.</p>
<p>So whenever you see this:</p>
<pre><code class="language-javascript">const obj = new Constructor();
</code></pre>
<p>You can read it as:</p>
<pre><code class="language-plaintext">Create a new object using this constructor blueprint.
</code></pre>
<p>Follow the series to learn more about Javascript.</p>
]]></content:encoded></item><item><title><![CDATA[Understanding this in JavaScript]]></title><description><![CDATA[If you have started learning Javascript, you might have already seen the this keyword. It might be so confusing at first, but it is required knowledge.
Honestly, almost every JavaScript developer gets]]></description><link>https://blog.ashishkumarsaini.dev/understanding-this-in-javascript</link><guid isPermaLink="true">https://blog.ashishkumarsaini.dev/understanding-this-in-javascript</guid><category><![CDATA[this in js]]></category><category><![CDATA[this keyword]]></category><category><![CDATA[JavaScript]]></category><dc:creator><![CDATA[Ashish Kumar Saini]]></dc:creator><pubDate>Thu, 07 May 2026 21:47:23 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/696877fccb285855f0758646/14a845a7-9359-4073-9698-e02880817620.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>If you have started learning Javascript, you might have already seen the <code>this</code> keyword. It might be so confusing at first, but it is required knowledge.</p>
<p>Honestly, almost every JavaScript developer gets confused about <code>this</code> at first. You don’t need to learn complicated internals or memorize weird rules to understand it.</p>
<p>A simple way to think about <code>this</code> is:</p>
<p><code>this</code> <strong>usually refers to whoever is calling the function.</strong></p>
<p>That is it.</p>
<p>Once this idea clicks, most examples start making sense.</p>
<h2>What does <code>this</code> actually represent?</h2>
<p><code>this</code> is a special keyword in JavaScript. The value of <code>this</code> depends on how the function is being called, instead of where it is written.</p>
<p>Only <strong>who is calling</strong> matters most of the time. The output changes based on the context.</p>
<h2><code>this</code> in the global context</h2>
<p>Let’s start simple. Try to run the code below at different places:</p>
<pre><code class="language-javascript">console.log(this);
</code></pre>
<p>If you run this inside the browser, you’ll see:</p>
<pre><code class="language-javascript">window
</code></pre>
<p>Because in the browser, the global object is <code>window</code>.</p>
<p>So basically:</p>
<pre><code class="language-javascript">this === window; // true
</code></pre>
<p>At the global level, <code>this</code> points to the global object.</p>
<h2><code>this</code> inside an object</h2>
<p>Now, let’s look at the most common use case of <code>this</code></p>
<pre><code class="language-javascript">const user = {
  name: "John",

  greet() {
    console.log(this.name);
  },
};

user.greet(); // John
</code></pre>
<p>Are you wondering why the output is "John"? Because <code>user</code> is calling <code>greet()</code>.</p>
<p>So inside that function, <code>this</code> represents the <code>user</code>.</p>
<p>Remember, <code>this</code> refers to whoever is calling, and again, the user here is calling the greet function.</p>
<p>Also, a very easy trick is to look to the left of the dot.</p>
<pre><code class="language-javascript">user.greet()
</code></pre>
<p>The thing before the dot is usually what <code>this</code> becomes.</p>
<h2><code>this</code> inside a normal function</h2>
<p>Now, let's see how <code>this</code> behaves inside the usual functions.</p>
<pre><code class="language-javascript">function showThis() {
  console.log(this);
}

showThis();
</code></pre>
<p>Here, no object is calling the function.</p>
<p>It’s just being called directly.</p>
<p>So, the output of <code>this</code> would be <code>undefined</code>. Because nobody is calling the function.</p>
<p>There’s no object connected to it.</p>
<h2>Same function, different <code>this</code></h2>
<p>This is where things become interesting.</p>
<pre><code class="language-javascript">function sayName() {
  console.log(this.name);
}

const student = {
  name: "Rahul",
  sayName,
};

const teacher = {
  name: "Priya",
  sayName,
};

student.sayName();
teacher.sayName();
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">Rahul
Priya
</code></pre>
<p>The function is exactly the same for both objects.</p>
<p>But the caller changes.</p>
<p>So <code>this</code> changes too.</p>
<pre><code class="language-javascript">student.sayName(); // this = student

teacher.sayName(); // this = teacher
</code></pre>
<p>This is the most important thing to remember about <code>this</code>.</p>
<h2><code>this</code> in classes</h2>
<p>If you have understood the above behaviour, <code>this</code> will be easier to understand in classes.</p>
<p>Example:</p>
<pre><code class="language-javascript">class User {
  constructor(name) {
    this.name = name;
  }

  greet() {
    console.log(`Hello ${this.name}`);
  }
}

const user1 = new User("John");

user1.greet(); // Hello John
</code></pre>
<p>Here, when a new object of the User class has been created with the arguments "John", a new this has been created.</p>
<p>So, this line:</p>
<pre><code class="language-javascript">this.name = name
</code></pre>
<p>becomes</p>
<pre><code class="language-javascript">user1.name // John
</code></pre>
<h2>Easiest way to understand <code>this</code></h2>
<p>Whenever you see <code>this</code>, ask:</p>
<blockquote>
<p>“Who is calling this function?”</p>
</blockquote>
<p>That question solves most confusion.</p>
<p>Example:</p>
<pre><code class="language-javascript">user.login(); // this -&gt; user;
</code></pre>
<p><code>user</code> is calling the function.</p>
<p>But, if only login function is called:</p>
<pre><code class="language-javascript">login(); // this -&gt; undefined
</code></pre>
<p>Nobody is calling it an object method.</p>
<p>So <code>this</code> becomes <code>undefined</code> in strict mode.</p>
<h2>Simple diagram idea</h2>
<p>You can visualize it like this:</p>
<pre><code class="language-plaintext">user  ─────► greet()

Inside greet():
this = user
</code></pre>
<p>Another one:</p>
<pre><code class="language-plaintext">No object ─────► showThis()

Inside showThis():
this = undefined
</code></pre>
<h2>Final thoughts</h2>
<p>The reason <code>this</code> feels confusing because its value changes.</p>
<p>But once you stop thinking about <em>where the function is written</em> and start focusing on <em>who is calling the function</em>, things become much clearer.</p>
<p>So remember this one line:</p>
<p><code>this</code> is usually the caller of the function</p>
<p>And that single idea will help you understand most <code>this</code> examples in JavaScript.</p>
]]></content:encoded></item><item><title><![CDATA[Spread vs Rest Operators in JavaScript]]></title><description><![CDATA[In ES6 (ECMAScript 2015), Javascript has introduced spread (...) and rest (...) operators. You might be wondering both looks same but the working and behaviour are completely different.
After this blo]]></description><link>https://blog.ashishkumarsaini.dev/spread-vs-rest-operators-in-javascript</link><guid isPermaLink="true">https://blog.ashishkumarsaini.dev/spread-vs-rest-operators-in-javascript</guid><category><![CDATA[rest in js]]></category><category><![CDATA[spread in js]]></category><category><![CDATA[Javascript Spread  vs Rest Operator]]></category><category><![CDATA[JavaScript]]></category><dc:creator><![CDATA[Ashish Kumar Saini]]></dc:creator><pubDate>Sun, 03 May 2026 15:03:06 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/696877fccb285855f0758646/8e8197d5-2095-49c0-959f-0aabec24ef91.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In ES6 (ECMAScript 2015), Javascript has introduced spread (<code>...</code>) and rest (<code>...</code>) operators. You might be wondering both looks same but the working and behaviour are completely different.</p>
<p>After this blog, you will get a crystal clear idea about expanding vs combining values using these operators.</p>
<h2>What is spread operator?</h2>
<p>The spread operator (<code>...</code>) is used to expand the values from the array, objects, or iterables into individual values.</p>
<ul>
<li><p><strong>Expanding objects:</strong></p>
<pre><code class="language-javascript">const user = {id: 101, name: 'John', age: 22};

const updatedUser = {...user, city: 'Delhi'};

console.log(user);
// {id: 101, name: 'John', age: 22}

console.log(updatedUser);
// {id: 101, name: 'John', age: 22, city: 'Delhi'}
</code></pre>
<p>Here, we have expanded user details into another object using the spread operator.</p>
<p>So, a <code>updatedUser</code> will have user + city values.</p>
<p>But, if the user already contains the city value, then updatedUser will have the override value.</p>
<pre><code class="language-javascript">const user = {id: 101, name: 'John', age: 22, city: 'Delhi'};

const updatedUser = {...user, city: 'Jaipur'};

console.log(user);
// {id: 101, name: 'John', age: 22, city: 'Delhi'}

console.log(updatedUser);
// {id: 101, name: 'John', age: 22, city: 'Jaipur'}
</code></pre>
</li>
<li><p><strong>Expanding arrays:</strong></p>
<pre><code class="language-javascript">const nums = [1, 2, 3];

const newNums = [...nums, 4, 5];

console.log(newNums); // [1, 2, 3, 4, 5]
</code></pre>
<p>Here, <code>...nums</code> expands into <code>1, 2, 3</code>. So, <code>newNums</code> will contain both <code>nums</code> values and new values (4, 5).</p>
</li>
</ul>
<h2>What is the Rest Operator?</h2>
<p>The rest operator (<code>...</code>) is used to collect multiple values into a single array or object.</p>
<p>Example with Function Parameters</p>
<pre><code class="language-javascript">function sum(...numbers) {
  return numbers.reduce((acc, curr) =&gt; acc + curr, 0);
}

console.log(sum(1, 2, 3, 4)); // 10
</code></pre>
<p>Here, <code>...numbers</code> collects all arguments into the array</p>
<p>Example with Destructuring</p>
<pre><code class="language-javascript">const [first, ...restValues] = [10, 20, 30, 40];

console.log(first); // 10
console.log(rest);  // [20, 30, 40]
</code></pre>
<p>The remaining elements are collected into restValues.</p>
<h2>Differences between Spread vs Rest</h2>
<table>
<thead>
<tr>
<th>Feature</th>
<th>Spread Operator</th>
<th>Rest Operator</th>
</tr>
</thead>
<tbody><tr>
<td>Purpose</td>
<td>Expands values</td>
<td>Collects values</td>
</tr>
<tr>
<td>Usage</td>
<td>Arrays, objects</td>
<td>Function params, destructuring</td>
</tr>
<tr>
<td>Direction</td>
<td>Inside → Outside</td>
<td>Outside → Inside</td>
</tr>
<tr>
<td>Output</td>
<td>Individual elements</td>
<td>Individual elements</td>
</tr>
</tbody></table>
<h2>Practical Use Cases</h2>
<ol>
<li><p>Copying the Arrays (Immutable Updates)</p>
<pre><code class="language-javascript">const original = [1, 2, 3];
const copy = [...original];
</code></pre>
</li>
<li><p>Merging the Arrays</p>
<pre><code class="language-javascript">const numbers1 = [1, 2];
const numbers2 = [3, 4];

const merged = [...numbers1, ...numbers2]; // [1,2,3,4]
</code></pre>
</li>
<li><p>Cloning and Updating the objects</p>
<pre><code class="language-javascript">const user = {name: 'John', age: 21};

const updatedUser = {...user, age: 22};
</code></pre>
</li>
<li><p>Flexible Functions Arguments</p>
<pre><code class="language-javascript">function print(...args){
    console.log(args); // print all the values -&gt; 1, 2, 4
}

print(1, 2, 4);
</code></pre>
</li>
<li><p>Extract/Remove any properties using rest</p>
<pre><code class="language-javascript">const user = {name: 'John', age: 21, email: 'abc@email.com'};

const {email, ...remainingProperties} = user;

console.log(remainingProperties); 
// {name: 'John', age: 21};
</code></pre>
</li>
</ol>
<h2>Visual Understanding</h2>
<pre><code class="language-plaintext">Spread Operator
[1, 2, 3] -&gt; ...nums -&gt; 1, 2, 3

Rest Operator
1, 2, 3 -&gt; ...nums -&gt; [1, 2, 3]
</code></pre>
<h2>When to Use What?</h2>
<p>Use the spread operator when you want to</p>
<ul>
<li><p>Copy or merge arrays/objects</p>
</li>
<li><p>Pass multiple values</p>
</li>
</ul>
<p>Use the rest operator when you want to:</p>
<ul>
<li><p>Handle an unknown number of arguments</p>
</li>
<li><p>Extract remaining values</p>
</li>
</ul>
<h2>Final Thoughts</h2>
<p>Even though spread and rest share the same syntax (<code>...</code>).</p>
<p>Their purpose is opposite:</p>
<ul>
<li><p>Spread → breaks things apart</p>
</li>
<li><p>Rest → groups things together</p>
</li>
</ul>
<p>Mastering this distinction will make your JavaScript code cleaner, more flexible, and easier to maintain.</p>
<p>Follow series to learn more about Javascript.</p>
]]></content:encoded></item><item><title><![CDATA[Destructuring in JavaScript]]></title><description><![CDATA[JavaScript gives us a feature called destructuring. It makes working with arrays and objects much cleaner and less repetitive.
If you have ever written code like this:
const user = { name: "Ashish" ag]]></description><link>https://blog.ashishkumarsaini.dev/destructuring-in-javascript</link><guid isPermaLink="true">https://blog.ashishkumarsaini.dev/destructuring-in-javascript</guid><category><![CDATA[destructuring in JavaScript]]></category><category><![CDATA[js]]></category><category><![CDATA[array js]]></category><category><![CDATA[objects-in-js]]></category><dc:creator><![CDATA[Ashish Kumar Saini]]></dc:creator><pubDate>Sat, 02 May 2026 22:09:08 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/696877fccb285855f0758646/7a6dffdb-a58a-44e6-a435-834c94928186.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>JavaScript gives us a feature called destructuring. It makes working with arrays and objects much cleaner and less repetitive.</p>
<p>If you have ever written code like this:</p>
<pre><code class="language-javascript">const user = { name: "Ashish" age: 22 };

const name = user.name;
const age = user.age;
</code></pre>
<p>You already know the pain of writing the same object while extracting each value from the object</p>
<p>Let’s fix that.</p>
<h2>What is destructuring?</h2>
<p>Destructuring is a syntax which is introduced in ES6 (ECMAScript 2015), that allows to extract values from arrays or objects into variables in a simple, shorter, and cleaner way.</p>
<p>Update the same example using destructuring:</p>
<pre><code class="language-javascript">const user = { name: "Ashish" age: 22 };

const {name, age} = user;
</code></pre>
<p>Now JavaScript does the work for you. You do not have to write <a href="http://user.name"><code>user.name</code></a> over.</p>
<h2>Destructuring Objects</h2>
<p>Object destructuring is based on keys (property names).</p>
<p>Before ES6,</p>
<pre><code class="language-javascript">const user = {
  name: "Ashish",
  age: 22
};

const name = user.name;
const age = user.age;
</code></pre>
<p>After (Destructuring):</p>
<pre><code class="language-javascript">const { name, age } = user;
</code></pre>
<p><strong>Renaming Variables</strong>: We can also rename the variables on the go, while destructuring.</p>
<pre><code class="language-javascript">const { name: username } = user;
</code></pre>
<p><strong>Default Values:</strong> We can also assign the default values while destructuring objects</p>
<pre><code class="language-javascript">const user = {
  name: "Ashish"
};

const { name, age = 18 } = user;

console.log(age); // 18
</code></pre>
<h2>Destructuring Arrays</h2>
<p>Array destructuring works based on position (also called index).</p>
<p>Before ES6,</p>
<pre><code class="language-javascript">const colors = ['red', 'blue', 'pink'];

const first = colors[0];
const second = colors[1];
const third = colors[2];
</code></pre>
<p>After ES6, destructuring is much easier.</p>
<pre><code class="language-javascript">const colors = ['red', 'blue', 'pink'];

const [first, second, third] = colors;
</code></pre>
<p>Just in case, we do not want a second color:</p>
<pre><code class="language-javascript">const colors = ['red', 'blue', 'pink'];

const [first, , third] = colors;
</code></pre>
<p>This is fine for one or a maximum of 2 indexes, but we should not skip multiple indexes by keeping empty for so many positions in between. In that case, we can use the older approach <code>const color = colors[10];</code></p>
<h2>Why Use Destructuring?</h2>
<ul>
<li><p>Less Repetitive Code</p>
</li>
<li><p>Cleaner and more readable</p>
</li>
</ul>
<h2>Final Thoughts</h2>
<p>Destructuring is one of those features that:</p>
<ul>
<li><p>Reduces boilerplate</p>
</li>
<li><p>Improves readability</p>
</li>
<li><p>Makes your code feel more modern</p>
</li>
</ul>
<p>Start using it in small places, and soon it’ll become second nature.</p>
<p>Follow series to learn more about Javascript.</p>
]]></content:encoded></item><item><title><![CDATA[Callbacks in JavaScript: Why They Exist]]></title><description><![CDATA[Javascript is a very powerful language not just because if what is can do, but how it actually does the things. One of the core and fundamental concept of Javascript is callbacks which is widely used ]]></description><link>https://blog.ashishkumarsaini.dev/callbacks-in-javascript</link><guid isPermaLink="true">https://blog.ashishkumarsaini.dev/callbacks-in-javascript</guid><category><![CDATA[callbacks]]></category><category><![CDATA[callback in js]]></category><category><![CDATA[JavaScript]]></category><dc:creator><![CDATA[Ashish Kumar Saini]]></dc:creator><pubDate>Sat, 02 May 2026 21:37:55 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/696877fccb285855f0758646/12890e26-3720-43dc-9827-012d9d61beb5.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Javascript is a very powerful language not just because if what is can do, but how it actually does the things. One of the core and fundamental concept of Javascript is callbacks which is widely used in production.</p>
<p>Let's break it down.</p>
<h2>Function as values</h2>
<p>Javascript is one of the language which supports functions as values.</p>
<p>In programming, a language is said to treat functions as values when it supports first class functions. This means functions can be assigned to variables, passed as arguments to other functions, and returned from other functions, just like any other data type.</p>
<p>Examples:</p>
<ul>
<li><p>Stored in variables</p>
<pre><code class="language-javascript">// Regular functions
function message(name){
    return `Hey ${name}!`;
}

const greet = message;
console.log(greet('Rahul')); // Hey Rahul!

//Arrow functions
const sum = (a, b) =&gt; {
    return a + b;
}

console.log(sum(1, 2)); // 3
</code></pre>
</li>
<li><p>Pass them in arguments</p>
<pre><code class="language-javascript">function calculate(num1, num2, action){
    return action(num1, num2)
}

function sum(value1, value2){
    return value1 + value2;
}

function difference(value1, value2){
    return value1 - value2;
}

calculate(3, 2, sum);       // return 5
calculate(3, 2, difference) // return 1
</code></pre>
</li>
<li><p>Return functions from another functions</p>
<pre><code class="language-javascript">function greet(name){
    function message(){
        return `Welcome ${name}!`;
    }
    
    return message;
}

const messageFunction = greet('Rahul'); 
messageFunction(); // Welcome Rahul
</code></pre>
</li>
</ul>
<h2>What is a callback function?</h2>
<p>A callback function is a simple function that is passed to another function to be executed later.</p>
<pre><code class="language-javascript">// functio
function processAction(callback){
    const message ='Machine is  ';
    callback(message);    
}

function brewCoffee(message){
    console.log(`${message}: brewing coffee!`)
}

function startingMachine(message){
    console.log(`${message}: starting!`)
}


processAction(startingMachine); // Machine is starting!
processAction(brewCoffee);      // Machine is brewing coffee!
</code></pre>
<p>In the above example, what happened is</p>
<ul>
<li><p><code>processAction</code> -function accepting another function as a callback.</p>
</li>
<li><p><code>brewCoffee</code> - a function that will be passed later as a callback</p>
</li>
<li><p><code>startingMachine</code> - a function that will be passed later as a callback</p>
</li>
</ul>
<p>Now,</p>
<ul>
<li><p>when <code>processAction(startingMachine)</code> is called with <code>startingMachine</code> as callback, it has been called with <code>'Machine is'</code>. That string is passed to startMachine function argument and printed as 'Machine is starting!'.</p>
</li>
<li><p>Same for <code>processAction(brewCoffee)</code></p>
</li>
</ul>
<h2>Why Do We Use Callbacks?</h2>
<p>Callbacks are specially used in asynchronous programming.</p>
<p>Javascript has a behaviour of not waiting for long operations until we program them to wait (Example: API calls). Callbacks are used in such cases that when the execution is completed/failed, callbacks are fired.</p>
<pre><code class="language-javascript">console.log('Start')

setTimeout(() =&gt; {
  console.log("This runs later");
}, 2000);

console.log('End');

/*
* Output
*
*
*    Start
*    End
*    This runs later
*
*/
</code></pre>
<p>Here, <code>setTimeout</code> has a callback function that is executed after 2 seconds.</p>
<h2>Common use cases</h2>
<ol>
<li><p><strong>Array Methods</strong><br />You have seen the callbacks in the pre-defined methods of the array. One of them is array.map.  </p>
<pre><code class="language-javascript">const arr = [1, 2, 3, 4, 5];

const doubledArr = array.map((num)=&gt; num * 2);

console.log(doubledArr); // [2, 4, 6, 8, 10]
</code></pre>
<p>Here, <code>num =&gt; num * 2</code> is a callback.</p>
</li>
<li><p><strong>Event Handling</strong><br />If you have worked with DOM event handlers, you must have seen <code>addEventHandler</code>.  </p>
<pre><code class="language-javascript">const button = document.getElementById('btn');

button.addEventHandler('click', () =&gt; {
    console.log('Button clicked!');
});
</code></pre>
<p>In above example, when the button is clicked, <code>'Button clicked!'</code> will be printed. Here, two arguments has been passed to <code>addEventHandler</code></p>
<ul>
<li><p><code>'click'</code> -&gt; string</p>
</li>
<li><p>callback with <code>console.log('Button clicked!')</code></p>
</li>
</ul>
</li>
<li><p><strong>Async Operations</strong><br />In JS, we fetch data from an API, which is also an example of asynchronous programming.</p>
<pre><code class="language-javascript">const fetchData = (callback) =&gt; {
    fetch('api-endpoint')
        .then((data) =&gt; callback(data))
}

const callAfterComplete = (data) =&gt; {
    console.log(data);
}

fetchData(callAfterComplete);
</code></pre>
</li>
</ol>
<h2>Understanding Problem: Callback Hell</h2>
<p>Callback hell is nothing, just nested callbacks. When callbacks depend on each other, they can become deeply nested and hard to manage.</p>
<pre><code class="language-javascript">getData(function(x){
    getMoreData(x, function(y){
        getMoreMoreData(y, function(z){ 
            ...
        });
    });
});
</code></pre>
<p>Here,</p>
<ul>
<li><p>getData will execute and will be called with the callback having <code>x</code> argument.</p>
</li>
<li><p>Only if the <code>getData</code> is executed successfully, the inner function <code>getMoreData</code> will execute with arguments - <code>x</code> and a function with <code>y</code>.</p>
</li>
<li><p>Only if the <code>getMoreData</code> is executed successfully, the inner function getMoreMoreData will execute with arguments - <code>y</code> and a function with <code>z</code>.</p>
</li>
</ul>
<p><strong>Issues in callback hell</strong></p>
<ol>
<li><p>Structure grows horizontally like a pyramid, which reduces code readability.</p>
</li>
<li><p>Make debugging complex and error handling difficult.</p>
</li>
</ol>
<h2>Final Thoughts</h2>
<p>Callbacks are simple in concept but incredibly powerful:</p>
<ul>
<li><p>They enable async behavior</p>
</li>
<li><p>They make functions reusable</p>
</li>
<li><p>They form the base for modern JS patterns</p>
</li>
</ul>
<p>But like any tool, they need to be used wisely—especially when nesting starts to grow.</p>
]]></content:encoded></item><item><title><![CDATA[String Polyfills and Common Interview Questions in JavaScript]]></title><description><![CDATA[In Javascript, strings are used everywhere, but many developers do not know how they actually work behind the scenes.
When you call a method like .toUpperCase() on a string primitive, JavaScript creat]]></description><link>https://blog.ashishkumarsaini.dev/string-polyfills-and-common-interview-questions</link><guid isPermaLink="true">https://blog.ashishkumarsaini.dev/string-polyfills-and-common-interview-questions</guid><category><![CDATA[js strings]]></category><category><![CDATA[js-polyfills]]></category><category><![CDATA[stringpolyfills]]></category><dc:creator><![CDATA[Ashish Kumar Saini]]></dc:creator><pubDate>Tue, 21 Apr 2026 21:34:54 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/696877fccb285855f0758646/9bab08a8-273d-4a05-8b2b-3580a9c7172c.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In Javascript, strings are used everywhere, but many developers do not know how they actually work behind the scenes.</p>
<p>When you call a method like <code>.toUpperCase()</code> on a string primitive, JavaScript creates a temporary wrapper object (using the <code>String</code> constructor) so the method can be executed. Once the operation is done, that object is immediately discarded, and the result is returned as a primitive.</p>
<h2>What Are String Methods?</h2>
<p>String methods are the built-in functions that are used to manipulate and update the string.</p>
<p>Here are some of the string methods:</p>
<ul>
<li><p><code>toUpperCase()</code></p>
</li>
<li><p><code>toLowerCase()</code></p>
</li>
<li><p><code>slice()</code></p>
</li>
<li><p><code>substring()</code></p>
</li>
<li><p><code>includes()</code></p>
</li>
<li><p><code>split()</code></p>
</li>
<li><p><code>trim()</code></p>
</li>
</ul>
<p>These methods don’t modify the original string (because strings are immutable). Instead, they return a new string.</p>
<h2>How string method work internally?</h2>
<p>Let's take an example <code>toUpperCase</code> and understand how it works.</p>
<p>When you call <code>string.toUpperCase()</code></p>
<pre><code class="language-javascript">const str = 'Hello';

str.toUpperCase();
</code></pre>
<ol>
<li><p>Javascript iterate over each character</p>
</li>
<li><p>Convert that character into uppercase</p>
</li>
<li><p>Build a new string</p>
</li>
</ol>
<blockquote>
<p>Think of execution like this</p>
<p>Input String → Process Each Character → Apply Logic → Return New String</p>
</blockquote>
<h2>What are polyfills?</h2>
<p>Polyfills are a custom implementation of the built-in functions. It is mostly used to create the same functionality that built-in functions offer.</p>
<h3>Why Developers Write Polyfills?</h3>
<ul>
<li><p>Provide support for new methods in older browsers</p>
</li>
<li><p>Understanding internal logic</p>
</li>
<li><p>To practice the built-in methods logic by creating them of their own</p>
</li>
</ul>
<h3>Polyfill Examples</h3>
<p>Let's implement some polyfills for string methods</p>
<ol>
<li><p><strong>string.toLowerCase()</strong><br />Here I will be writing a custom polyfill for toLowerCase.</p>
<pre><code class="language-javascript">if(!String.prototype.toLowerCase){
    String.prototype.toLowerCase = function () {
        let result = "";

        // this refer to string on which method is called
        for (let char of this) {
            const code = char.charCodeAt(0);

            // a-z → A-Z
            if (code &gt;= 97 &amp;&amp; code &lt;= 122) {
                result += String.fromCharCode(code - 32);
            } else {
                result += char;
            }
        }

        return result;
    };
}
</code></pre>
<p>This will only work if the browser doesn't support <code>string.toLowerCase</code>, it will use the polyfill <code>toLowerCase</code></p>
</li>
<li><p><code>string.includes</code></p>
<pre><code class="language-javascript">if(!String.prototype.includes){
    String.prototype.myIncludes = function(searchString) {
        return this.indexOf(searchString) !== -1;
    };
}
</code></pre>
</li>
</ol>
<h2>Common String Interview Questions</h2>
<p>If you're preparing for interviews, these are must-practice:</p>
<ol>
<li><p>Reverse a String function without using built-in methods<br />Logic: Iterate over the string and append the new string with each character in an order so that the last character comes first.</p>
</li>
<li><p>Check Palindrome<br />Logic: Reverse and create a new string. Check if both strings are equal or not.</p>
</li>
<li><p>Count Characters<br />Logic: Use a "Map" or an object to store counts as you iterate through the string.</p>
</li>
<li><p>Anagram Detection: Do two strings contain the same characters?<br />Logic: Sort both strings and compare them.</p>
</li>
</ol>
<h2>Why Understanding Built-in Behavior Matters</h2>
<p>Most developers stop at using methods. But in an interview, the interviewer tests:</p>
<ul>
<li><p>How things work internally</p>
</li>
<li><p>Your problem-solving ability</p>
</li>
<li><p>Your understanding of edge cases</p>
</li>
</ul>
<p>Understanding internals helps you in writing better code, debugging faster, and performing well in interviews.</p>
<p>Example questions:</p>
<ol>
<li><p>How does slice() differ from substring()?</p>
</li>
<li><p>Why are strings immutable?</p>
</li>
<li><p>How would you optimize a string search?</p>
</li>
</ol>
<h2>Conclusion</h2>
<p>If you want to stand out as a developer:</p>
<p>Don’t just use methods — understand them, practice writing polyfills, and solve real interview problems.</p>
<p>That’s where real growth happens.</p>
<p>Follow the series to learn more about Javascript.</p>
]]></content:encoded></item><item><title><![CDATA[Map and Set in JavaScript]]></title><description><![CDATA[While working in Javascript, you have mostly worked with objects and arrays. But there are some limitations when used for large data or applying complex operations.
Problems in Objects

Object must ha]]></description><link>https://blog.ashishkumarsaini.dev/map-and-set-in-javascript</link><guid isPermaLink="true">https://blog.ashishkumarsaini.dev/map-and-set-in-javascript</guid><category><![CDATA[map in js]]></category><category><![CDATA[set in js]]></category><category><![CDATA[map and set in javascript]]></category><category><![CDATA[JavaScript]]></category><dc:creator><![CDATA[Ashish Kumar Saini]]></dc:creator><pubDate>Tue, 21 Apr 2026 19:21:16 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/696877fccb285855f0758646/32af7866-67cb-4028-936b-d40e94dd3d44.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>While working in Javascript, you have mostly worked with objects and arrays. But there are some limitations when used for large data or applying complex operations.</p>
<h2>Problems in Objects</h2>
<ul>
<li><p>Object must have a key as a string. If you use a number, it will automatically be used as a string.</p>
</li>
<li><p>Objects inherit properties from their prototypes. For example: Object.<em>keys</em> is a predefined property that should not be used as a key. This may lead to unexpected bugs.</p>
</li>
<li><p>You cannot directly iterate over the object's values/keys. You have to use object.keys() or object.entries() to do iteration.</p>
</li>
<li><p>Order of insertion is not maintained.</p>
</li>
</ul>
<h2>Problems with Arrays</h2>
<ul>
<li><p>Removing a specific value from an array requires another iteration to find the position of the value in the array.</p>
</li>
<li><p>The array might have duplicate values. In some cases the developer doesn't want to insert duplicate values into the array. To achieve the same, they need to iterate over the whole array to check if the value already exists.</p>
</li>
</ul>
<h2>Understanding Map and Set</h2>
<h3>What is Map?</h3>
<p>Map is a built-in datatype in Javascript. It is used to store key-value pairs. It is like an object with some extra powers.</p>
<ol>
<li><p>Key can be of any type (string, number, array...)</p>
</li>
<li><p>Key should be unique</p>
</li>
<li><p>Maintain insertion order. This means if you iterate over a map, it will be the same order in which they are inserted.</p>
</li>
</ol>
<p><strong>Map Methods:</strong></p>
<ol>
<li><p>Insert value,<br />To insert a value in map, use <code>map.set(key, value)</code>.<br />Examples:</p>
<pre><code class="language-javascript">const employee = new Map();

employee.set("id", 101);
employee.set("name", "Rahul");
</code></pre>
</li>
<li><p>Get a value<br />To get a value, use <code>map.get(key)</code></p>
<pre><code class="language-javascript">const employee = new Map();

employee.set("id", 101);
employee.set("name", "Rahul");

const employeeName = employee('name');

console.log(employeeName); // Rahul
</code></pre>
</li>
<li><p>Check if value exisits, use <code>map.has(key)</code>, return boolean state.</p>
<pre><code class="language-javascript">const employee = new Map();

employee.set("id", 101);
employee.set("name", "Rahul");

console.log(employee.has('name'));   // true
console.log(employee.has('salary')); // false
</code></pre>
</li>
<li><p>Delete a value, use <code>map.delete(key)</code></p>
<pre><code class="language-javascript">const employee = new Map();

employee.set("id", 101);
employee.set("name", "Rahul");

employee.delete("id");

console.log(employee.has("id")); // false
</code></pre>
</li>
</ol>
<h2>What is Set?</h2>
<p>A set is also a built-in datatype in Javascript used to store unique values. It is more like an array, but with the power of uniqueness.</p>
<ul>
<li><p>Store unique values</p>
</li>
<li><p>Store only values, not keys</p>
</li>
<li><p>Maintain insertion order</p>
</li>
</ul>
<p><strong>Set methods:</strong></p>
<ol>
<li><p>Insert a value, use <code>set.add(value)</code>.</p>
<pre><code class="language-javascript">const set = new Set();

set.add(42);
set.add(42);
set.add(13);

for (const item of set) {
  console.log(item);
  // Expected output: 42
  // Expected output: 13
}
</code></pre>
</li>
<li><p>Check if the value exists, use <code>set.has(key)</code>, return a boolean state.</p>
<pre><code class="language-javascript">const set = new Set();

set.add(42);
set.add(13);

console.log(set.has(42));   // true
console.log(set.has(40)); // false
</code></pre>
</li>
<li><p>Delete a value, use <code>set.delete(value)</code>, returns a boolean value indicating if the value is deleted successfully.</p>
<pre><code class="language-javascript">const set = new Set();

set.add(42);
set.add(13);

console.log(set.delete(42)); // true
console.log(set.delete(40)); // false

console.log(set) // Set(1) {13}
</code></pre>
</li>
</ol>
<p>Both Map and Set have other methods like <code>values</code>, <code>entries</code>, <code>size</code> and <code>forEach</code> for iteration. Here I have explained to you the necessary methods for insertion and deletion of values.</p>
<h2>Comparison between Map and Object</h2>
<table>
<thead>
<tr>
<th>Feature</th>
<th>Map</th>
<th>Object</th>
</tr>
</thead>
<tbody><tr>
<td>Key Types</td>
<td>Any Type</td>
<td>String only</td>
</tr>
<tr>
<td>Order of values</td>
<td>Maintained</td>
<td>Not guaranteed</td>
</tr>
<tr>
<td>Performance</td>
<td>Optimized for insertion and removal</td>
<td>No optimization</td>
</tr>
<tr>
<td>Iteration</td>
<td>Has in-built methods</td>
<td>Need other methods</td>
</tr>
</tbody></table>
<h2>Comparison between Set and Array</h2>
<table>
<thead>
<tr>
<th>Features</th>
<th>Set</th>
<th>Array</th>
</tr>
</thead>
<tbody><tr>
<td>Unique Values</td>
<td>Yes</td>
<td>No</td>
</tr>
<tr>
<td>Maintained Order</td>
<td>Yes</td>
<td>Yes</td>
</tr>
<tr>
<td>Search</td>
<td>Faster with <code>has</code> method</td>
<td>Slower with <code>includes</code> method</td>
</tr>
</tbody></table>
<h2>When to Use Map?</h2>
<p>Use Map when:</p>
<ul>
<li><p>You need key-value storage</p>
</li>
<li><p>Keys are not just strings</p>
</li>
<li><p>Frequent add/remove operations</p>
</li>
<li><p>You care about insertion order</p>
</li>
</ul>
<p>Example:</p>
<ul>
<li><p>Caching data</p>
</li>
<li><p>Storing user sessions</p>
</li>
<li><p>Mapping objects to values</p>
</li>
</ul>
<h2>When to Use Set?</h2>
<p>Use Set when:</p>
<ul>
<li><p>You need <strong>unique values</strong></p>
</li>
<li><p>You want to <strong>remove duplicates</strong></p>
</li>
<li><p>Fast lookup is required</p>
</li>
</ul>
<p>Example:</p>
<ul>
<li><p>Unique tags</p>
</li>
<li><p>Removing duplicate IDs</p>
</li>
<li><p>Tracking visited items</p>
</li>
</ul>
<h2>Conclusion</h2>
<ul>
<li><p>Use Map when you need a better version of objects</p>
</li>
<li><p>Use Set when you need uniqueness without extra logic</p>
</li>
<li><p>Avoid forcing everything into Objects &amp; Arrays</p>
</li>
</ul>
<p>Follow Javascript series for more updates 🙂</p>
]]></content:encoded></item><item><title><![CDATA[Template Literals in JavaScript]]></title><description><![CDATA[Before ES6, JavaScript developers used string concatenation with the + operator
const name = "Vishal";

const age = 30;

const message = "My name is " + name + " and I am " + age + " years old.";

con]]></description><link>https://blog.ashishkumarsaini.dev/template-literals-in-javascript</link><guid isPermaLink="true">https://blog.ashishkumarsaini.dev/template-literals-in-javascript</guid><category><![CDATA[#javascript-template-literals]]></category><category><![CDATA[template literals]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[string interpolation]]></category><category><![CDATA[js strings]]></category><dc:creator><![CDATA[Ashish Kumar Saini]]></dc:creator><pubDate>Mon, 20 Apr 2026 20:39:26 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/696877fccb285855f0758646/e3a23311-00b1-42b2-a179-09b4d039146f.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Before ES6, JavaScript developers used string concatenation with the + operator</p>
<pre><code class="language-javascript">const name = "Vishal";

const age = 30;

const message = "My name is " + name + " and I am " + age + " years old.";

console.log(message); // My name is Vishal and I am 30 years old.
</code></pre>
<p>But there are various difficulties or problems developers face while performing string concatenations:</p>
<ul>
<li><p>Hard to read strings</p>
</li>
<li><p>String gets too long</p>
</li>
<li><p>Cluttered code</p>
</li>
<li><p>Difficulty in managing dynamic values</p>
</li>
</ul>
<p>As the application grows, it becomes messier and increases the risk of errors.</p>
<p>After ES6, this has been resolved using Template Literals.</p>
<h2>What Are Template Literals?</h2>
<p>Template literals are the modern way to work with string concatenations in JavaScript. They use backticks (<code>``</code> ) instead of quotes (<code>''</code>/<code>""</code>).</p>
<p>Example:</p>
<pre><code class="language-javascript">const name = "Vishal";

const age = 30;

const message = `My name is \({name} and I am \){age} years old.`;

console.log(message); // My name is Vishal and I am 30 years old.
</code></pre>
<p>Use of template literals instead of quotes allows:</p>
<ul>
<li><p>multi-line strings<br />Example:</p>
<pre><code class="language-javascript">const message = `This is a 
                 string to show template literals
                 multiline.`;

console.log(message);
// This is a string to show template literals multiline.
</code></pre>
</li>
<li><p>Embedding variables or operations. Instead of using the + operator, you can inject a variable using ${}.<br />Example:</p>
<pre><code class="language-javascript">const number = 3;
const message = `Square of \({number} is \){ number ** 2 }.`;

console.log(message); // Square of 3 is 9.
</code></pre>
</li>
</ul>
<h2>Benefits of using Template Literals</h2>
<ul>
<li><p>Cleaner and more readable</p>
</li>
<li><p>No need for +</p>
</li>
<li><p>Easier to maintain</p>
</li>
</ul>
<h2>Before vs After (Comparison)</h2>
<table>
<thead>
<tr>
<th>Before (Old way)</th>
<th>After (New Way)</th>
</tr>
</thead>
<tbody><tr>
<td>Concatenation</td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
</tr>
</tbody></table>
<p>❌ Old Way (Concatenation) const product = "Laptop"; const price = 50000;</p>
<p>const text = "The price of " + product + " is Rs. " + price + "."; ✅ New Way (Template Literals) const text = <code>The price of \({product} is Rs. \){price}.</code>;</p>
<p>👉 Clearly more readable and modern!</p>
<p>📄 Multi-line Strings Made Easy</p>
<p>Before template literals, multi-line strings were awkward:</p>
<p>❌ Old Way const text = "This is line one.\n" + "This is line two."; ✅ Template Literals const text = <code>This is line one. This is line two.</code>;</p>
<p>🎯 No special characters, no concatenation—just write naturally.</p>
<h2>Real-World Use Cases</h2>
<ol>
<li><p>Dynamic Messages const user = "Ashish"; console.log(<code>Welcome back, ${user}!</code>);</p>
</li>
<li><p>HTML Templates (Very Common) const title = "JavaScript Basics";</p>
<pre><code class="language-javascript">const html = `${title}`;
</code></pre>
</li>
<li><p>Logging and Debugging</p>
<pre><code class="language-javascript">const count = 5;

console.log(`Total items: ${count}`); 
</code></pre>
</li>
<li><p>Expressions Inside Strings: You can even run JavaScript inside ${}:</p>
<pre><code class="language-javascript">const a = 5;
const b = 10;

console.log(Sum is ${a + b});
</code></pre>
</li>
</ol>
<h2>Why Template Literals Matter?</h2>
<ul>
<li><p>Improves code readability</p>
</li>
<li><p>Reduces syntax noise</p>
</li>
<li><p>Makes dynamic strings easy to write</p>
</li>
<li><p>Widely used in modern frameworks (React, Node.js)</p>
</li>
</ul>
<h2>Final Thoughts</h2>
<p>Template literals are one of the simplest yet most powerful features in modern JavaScript.</p>
<p>Once you start using them: 👉 You’ll rarely go back to + concatenation.</p>
<p>Check out more blogs and follow our Javascript series to learn more.</p>
]]></content:encoded></item><item><title><![CDATA[Understanding Object-Oriented Programming in Javascript]]></title><description><![CDATA[Object-oriented programming is a concept of writing code in which we organize everything around objects.
An object is a combination of

Properties

Methods


Instead of writing separate variables and ]]></description><link>https://blog.ashishkumarsaini.dev/understanding-object-oriented-programming-in-javascript</link><guid isPermaLink="true">https://blog.ashishkumarsaini.dev/understanding-object-oriented-programming-in-javascript</guid><category><![CDATA[JS OOPS]]></category><category><![CDATA[OOP In JavaScript]]></category><category><![CDATA[js]]></category><category><![CDATA[classes in javascript]]></category><dc:creator><![CDATA[Ashish Kumar Saini]]></dc:creator><pubDate>Sat, 18 Apr 2026 19:04:30 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/696877fccb285855f0758646/91bfd74e-8923-4d6d-ac4b-24ab93af7d6d.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Object-oriented programming is a concept of writing code in which we organize everything around objects.</p>
<p>An object is a combination of</p>
<ol>
<li><p>Properties</p>
</li>
<li><p>Methods</p>
</li>
</ol>
<p>Instead of writing separate variables and functions, we bundle them together.</p>
<h2>Real-World Analogy: Blueprint → Objects</h2>
<p>Let’s understand object-oriented programming with a simple example:</p>
<p>Imagine you are a car manufacturer.</p>
<p>You first create a <strong>blueprint</strong> (design)</p>
<ul>
<li>Then you use that blueprint to create multiple cars</li>
</ul>
<p>👉 In JavaScript:</p>
<ul>
<li><p>Blueprint = <strong>Class</strong></p>
</li>
<li><p>Car = <strong>Object (Instance)</strong></p>
</li>
</ul>
<p>So instead of rewriting code again and again, we define a class once and reuse it.</p>
<hr />
<h2>🧱 What is a Class in JavaScript?</h2>
<p>A <strong>class</strong> is a blueprint used to create objects.</p>
<p>It defines:</p>
<ul>
<li><p>What properties an object will have</p>
</li>
<li><p>What actions it can perform</p>
</li>
</ul>
<h3>Example:</h3>
<pre><code class="language-javascript">class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }

  greet() {
    console.log(`Hi, my name is ${this.name}`);
  }
}
</code></pre>
<hr />
<h2>🧪 Creating Objects (Instances)</h2>
<p>We use the <code>new</code> keyword to create objects from a class.</p>
<pre><code class="language-javascript">const person1 = new Person("Ashish", 25);
const person2 = new Person("Rahul", 30);

person1.greet(); // Hi, my name is Ashish
person2.greet(); // Hi, my name is Rahul
</code></pre>
<p>👉 Each object:</p>
<ul>
<li><p>Has its own data</p>
</li>
<li><p>Shares the same structure and methods</p>
</li>
</ul>
<hr />
<h2>⚙️ Understanding the Constructor</h2>
<p>The <strong>constructor</strong> is a special method inside a class.</p>
<h3>Key Points:</h3>
<ul>
<li><p>It runs automatically when an object is created</p>
</li>
<li><p>It initializes object properties</p>
</li>
</ul>
<pre><code class="language-javascript">constructor(name, age) {
  this.name = name;
  this.age = age;
}
</code></pre>
<p>👉 <code>this</code> refers to the current object.</p>
<hr />
<h2>🔧 Methods Inside a Class</h2>
<p>Methods define what an object can do.</p>
<pre><code class="language-javascript">greet() {
  console.log(`Hi, my name is ${this.name}`);
}
</code></pre>
<p>👉 Methods are shared across all instances (memory efficient).</p>
<hr />
<h2>🔒 Basic Idea of Encapsulation</h2>
<p>Encapsulation means:</p>
<p>👉 <strong>Keeping data and methods together and controlling access</strong></p>
<h3>Real-world example:</h3>
<p>Think of a car:</p>
<ul>
<li><p>You don’t directly control the engine</p>
</li>
<li><p>You use steering, brakes, accelerator</p>
</li>
</ul>
<p>Same in code:</p>
<ul>
<li><p>Internal data is hidden</p>
</li>
<li><p>Access is controlled via methods</p>
</li>
</ul>
<h3>Simple Example:</h3>
<pre><code class="language-javascript">class BankAccount {
  constructor(balance) {
    this.balance = balance;
  }

  deposit(amount) {
    this.balance += amount;
  }

  getBalance() {
    return this.balance;
  }
}
</code></pre>
<p>👉 We interact using methods instead of directly modifying data.</p>
<hr />
<h2>♻️ Why Use OOP?</h2>
<p>OOP helps you write better code:</p>
<ul>
<li><p>✅ Reusable (write once, use many times)</p>
</li>
<li><p>✅ Organized (structured code)</p>
</li>
<li><p>✅ Scalable (easy to expand)</p>
</li>
<li><p>✅ Maintainable (easy to debug and update)</p>
</li>
</ul>
<hr />
<h2>🧠 Class vs Object (Quick Comparison)</h2>
<table>
<thead>
<tr>
<th>Concept</th>
<th>Meaning</th>
</tr>
</thead>
<tbody><tr>
<td>Class</td>
<td>Blueprint</td>
</tr>
<tr>
<td>Object</td>
<td>Real instance created from class</td>
</tr>
</tbody></table>
<hr />
<h2>🎯 Assignment</h2>
<p>Try this yourself 👇</p>
<h3>Task:</h3>
<p>Create a <code>Student</code> class with:</p>
<ul>
<li><p>Properties: <code>name</code>, <code>age</code></p>
</li>
<li><p>Method: <code>printDetails()</code></p>
</li>
</ul>
<h3>Example Solution:</h3>
<pre><code class="language-javascript">class Student {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }

  printDetails() {
    console.log(`Name: \({this.name}, Age: \){this.age}`);
  }
}

const student1 = new Student("Aman", 20);
const student2 = new Student("Neha", 22);

student1.printDetails();
student2.printDetails();
</code></pre>
<hr />
<h2>🧩 Visual Understanding (Conceptual)</h2>
<pre><code class="language-plaintext">Class (Blueprint)
      ↓
Create using new
      ↓
Objects (Instances)
</code></pre>
<p>Example:</p>
<pre><code class="language-plaintext">Car (Class)
  ↓
car1, car2, car3 (Objects)
</code></pre>
<hr />
<h2>📌 Common Mistakes Beginners Make</h2>
<p>❌ Forgetting <code>new</code> keyword ❌ Not using <code>this</code> properly ❌ Thinking each object has separate methods (they are shared) ❌ Confusing class with object</p>
<hr />
<h2>🧠 Final Thoughts</h2>
<p>OOP is not just a concept—it’s a <strong>way of thinking</strong>.</p>
<p>Once you understand:</p>
<ul>
<li><p>Class</p>
</li>
<li><p>Object</p>
</li>
<li><p>Constructor</p>
</li>
<li><p>Methods</p>
</li>
</ul>
<p>You can build real-world applications much more easily 🚀</p>
<hr />
<p>Happy Coding! 💻</p>
]]></content:encoded></item><item><title><![CDATA[Array Flatten in Javascript]]></title><description><![CDATA[You have read in the previous blog on datatypes that an array is a non-primitive data type that can contain various data types.
But have you ever wondered what would happen if an array contained anoth]]></description><link>https://blog.ashishkumarsaini.dev/array-flatten-in-javascript</link><guid isPermaLink="true">https://blog.ashishkumarsaini.dev/array-flatten-in-javascript</guid><category><![CDATA[flatten array]]></category><category><![CDATA[array js]]></category><category><![CDATA[array method js]]></category><category><![CDATA[JavaScript]]></category><dc:creator><![CDATA[Ashish Kumar Saini]]></dc:creator><pubDate>Thu, 26 Mar 2026 19:29:20 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/696877fccb285855f0758646/638f3690-8db6-46aa-a628-326d881b16a2.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>You have read in the previous blog on datatypes that an array is a non-primitive data type that can contain various data types.</p>
<p>But have you ever wondered what would happen if an array contained another array? How are we going to handle this?</p>
<p>Understanding nested arrays and handling operations on them is an important skill, especially for problem-solving and is usually asked in interviews as well.</p>
<h2>What are nested arrays?</h2>
<p>If an array contains a nested array, it is called a nested array.</p>
<p>Example:</p>
<pre><code class="language-javascript">const nestedArray = [1, 2, 3, [4, 5, 6], 7, [8, [9, 10]]];
</code></pre>
<p>The above example might be confusing to see. Let me break it down to see multiple array properly.</p>
<pre><code class="language-javascript">const nestedArray = [
    1,
    2,
    3,
    [4, 5, 6],
    7,
    [
        8, 
        [9, 10]
    ]
]
</code></pre>
<p>Now the values on each index can be seen clearly.</p>
<p>Values with respective index:</p>
<ul>
<li><p><code>0</code> -&gt; <code>1</code> (<code>number</code>)</p>
</li>
<li><p><code>1</code> -&gt; <code>2</code> (<code>number</code>)</p>
</li>
<li><p><code>2</code> -&gt; <code>3</code> (<code>number</code>)</p>
</li>
<li><p><code>3</code> -&gt; <code>[4, 5, 6]</code> (<code>array</code>)</p>
</li>
<li><p><code>4</code> -&gt; <code>7</code> (<code>number</code>)</p>
</li>
<li><p><code>5</code> -&gt; <code>[8, [9, 10]]</code> (<code>nested array</code>)</p>
</li>
</ul>
<h2>Why is flattening an array used?</h2>
<p>Flattening an array means converting a multidimensional array to a single-dimensional array.</p>
<ul>
<li><p>Extracting values from all nested arrays</p>
</li>
<li><p>Arrange them in a single array</p>
</li>
</ul>
<p>This is an important concept needed when:</p>
<ol>
<li><p>Easier data processing</p>
</li>
<li><p>Useful in APIs and transforming data</p>
</li>
<li><p>Common in real-world scenarios (e.g., comments, categories with products)</p>
</li>
</ol>
<p>Example:</p>
<pre><code class="language-javascript">const categories = [
    ["p1", "p2", "p3"],
    ["p4", "p5"]
];
</code></pre>
<p>After flattening:</p>
<pre><code class="language-javascript">const products = ["p1", "p2", "p3", "p4", "p5"];
</code></pre>
<h2>Different approaches to flatten arrays</h2>
<p>There are multiple ways to flatten an array:</p>
<h3>Using in-build flat() method</h3>
<p>An array has an in-built method <code>flat()</code>. This is the most common and simple approach.</p>
<pre><code class="language-javascript">const array = [1, 2, [3, 4], [5, 6]];

const flatArr = arr.flat(Infinity);

console.log(flatArr); // [1, 2, 3, 4, 5, 6, 7]
</code></pre>
<h3>Using Recursion</h3>
<p>Recursion is a way to call the same function repeatedly.</p>
<pre><code class="language-javascript">const array = [1, 2, [3, 4], [5, 6]];

function flattenArray(arr) {
    let result = [];

    for (let item of arr) {
        if (Array.isArray(item)) {
            result = result.concat(flattenArray(item));
        } else {
            result.push(item);
        } 
    }

    return result; 
};

console.log(flattenArray([1, [2, [3, 4], 5]])); // [1, 2, 3, 4, 5]
</code></pre>
<h3>Using reduce()</h3>
<pre><code class="language-javascript">const array = [1, 2, [3, 4], [5, 6]];

const flattenArray = (arr) =&gt; {
    return arr.reduce((acc, item) =&gt; {
        if (Array.isArray(item)) {
            return acc.concat(flattenArray(item));
        }
        
        return acc.concat(item); 
    }, []); 
};

console.log(flattenArray([1, [2, [3, 4]]])); // [1, 2, 3, 4, 5]
</code></pre>
<h2>Common Interview Scenarios</h2>
<p>You may be asked:</p>
<ol>
<li><p>Flatten only one level arr.flat(1);</p>
</li>
<li><p>Flatten up to depth n</p>
</li>
<li><p>Don’t use built-in methods. Use recursion or a stack approach.</p>
</li>
</ol>
<p>Try to practice in any Javascript code editor.</p>
<h2>Conclusion</h2>
<p>Flattening arrays is a fundamental concept in JavaScript that helps you:</p>
<ul>
<li><p>Work with complex data structures</p>
</li>
<li><p>Improve problem-solving skills</p>
</li>
<li><p>Prepare for coding interviews</p>
</li>
</ul>
<p>Start with <code>flat()</code> for simplicity, but master recursion for interviews.</p>
]]></content:encoded></item><item><title><![CDATA[Understanding Object in JS]]></title><description><![CDATA[When you start learning Javascript, array helps you to store the list of data. But is there a possibility of storing structured information like details of an employee?

name

age

salary


That’s whe]]></description><link>https://blog.ashishkumarsaini.dev/understanding-object-in-js</link><guid isPermaLink="true">https://blog.ashishkumarsaini.dev/understanding-object-in-js</guid><category><![CDATA[JS Objects]]></category><category><![CDATA[Objects]]></category><category><![CDATA[JavaScript]]></category><dc:creator><![CDATA[Ashish Kumar Saini]]></dc:creator><pubDate>Mon, 23 Mar 2026 04:49:47 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/696877fccb285855f0758646/4eed3e81-4cd9-4e0e-971b-6db3668b0272.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>When you start learning Javascript, array helps you to store the list of data. But is there a possibility of storing structured information like details of an employee?</p>
<ol>
<li><p>name</p>
</li>
<li><p>age</p>
</li>
<li><p>salary</p>
</li>
</ol>
<p>That’s where objects come in.</p>
<h2>What Are Objects?</h2>
<p>An object is a collection of data stored in key-value pairs.</p>
<p>Think of it like a real-world entity.</p>
<p>Example: A person has:</p>
<ul>
<li><p>name</p>
</li>
<li><p>age</p>
</li>
<li><p>city</p>
</li>
</ul>
<p>In JavaScript, we represent this using an object:</p>
<pre><code class="language-javascript">const person = {
  name: "Ashish",
  age: 25,
  city: "Delhi"
};
</code></pre>
<p>Here:</p>
<ul>
<li><p><code>name</code>, <code>age</code>, <code>city</code> are keys</p>
</li>
<li><p><code>"Ashish"</code>, <code>25</code>, <code>"Delhi"</code> are their values</p>
</li>
</ul>
<h2>Why Do We Need Objects?</h2>
<p>Arrays store data using indexes:</p>
<pre><code class="language-javascript">const user = ["Ashish", 25, "Delhi"];
</code></pre>
<p>But this is confusing. What if I don't know on which index the value actually exists?</p>
<p>Objects solve this by using keys:</p>
<pre><code class="language-javascript">person.name
</code></pre>
<p>You can directly access the value by using its key name.</p>
<h2>Creating Objects</h2>
<p>You can create an object using curly braces <code>{}</code>:</p>
<pre><code class="language-javascript">const student = {
  name: "John",
  age: 20,
  course: "BCA"
};
</code></pre>
<h2>Accessing Properties</h2>
<h3>1. Dot Notation</h3>
<p>The object values can be accessed using . (<code>dot</code>) notation:</p>
<pre><code class="language-javascript">console.log(student.name); // John
</code></pre>
<h3>2. Bracket Notation</h3>
<p>The object values can also be accessed using [] (bracket) notation. Inside the bracket, the key name will be specified as a string.</p>
<pre><code class="language-javascript">console.log(student["age"]); // 20
</code></pre>
<h2>Dot notation vs Bracket notation</h2>
<ul>
<li><p>Dot notation → simple and common</p>
</li>
<li><p>Bracket notation → useful when the key is dynamic</p>
</li>
</ul>
<pre><code class="language-javascript">const key = "course";
console.log(student.course) // BCA
console.log(student[key]);  // BCA
</code></pre>
<h2>Updating Object Properties</h2>
<p>Updating object value is simple and uses only dots. Just specify the . and keyname with the assignment operator and value</p>
<pre><code class="language-javascript">student.age = 21;
console.log(student.age); // 21
</code></pre>
<p>Breakdown:</p>
<ul>
<li><p><code>age</code> -&gt; key</p>
</li>
<li><p><code>=</code> -&gt; assignment operator</p>
</li>
<li><p><code>21</code> -&gt; value</p>
</li>
</ul>
<h2>Adding New Properties</h2>
<p>New properties can also be added using the same approach for updating the object.</p>
<pre><code class="language-javascript">student.city = "Mumbai";

console.log(student);
</code></pre>
<p>If the city doesn't exisits in object, it will add new property. Otherwise update exisiting.</p>
<h2>Deleting Properties</h2>
<p>Object properties can be deleted using delete keyword following with object property name.</p>
<pre><code class="language-javascript">delete student.course;

console.log(student);
</code></pre>
<h2>Looping Through Object Keys</h2>
<p>To loop through an object, we use <code>for...in</code>:</p>
<pre><code class="language-javascript">for (let key in student) {
  console.log(key, student[key]);
}

// Output:
// name Rahul
// age 21
// city Mumbai
</code></pre>
<h2>Array vs Object (Simple Comparison)</h2>
<table>
<thead>
<tr>
<th>Feature</th>
<th>Array</th>
<th>Object</th>
</tr>
</thead>
<tbody><tr>
<td>Structure</td>
<td>Ordered list</td>
<td>Key-value pairs</td>
</tr>
<tr>
<td>Access</td>
<td>Index (0, 1, 2)</td>
<td>Key (name, age)</td>
</tr>
<tr>
<td>Use Case</td>
<td>List of items</td>
<td>Structured data</td>
</tr>
<tr>
<td>Example</td>
<td><code>["a", "b"]</code></td>
<td><code>{ name: "Ashish" }</code></td>
</tr>
</tbody></table>
<h2>Visual Representation (Mental Model)</h2>
<p>Think of an object like a labeled box:</p>
<pre><code class="language-plaintext">person = {
  name → "Ashish"
  age  → 25
  city → "Delhi"
}
</code></pre>
<p>Each value is stored with a label (key).</p>
<h2>Assignment (Practice)</h2>
<p>Create a student object and perform the following:</p>
<ol>
<li><p>Create an object named "employee"</p>
</li>
<li><p>Add name, id, and salary fields</p>
</li>
<li><p>Update the salary of the employee object.</p>
</li>
<li><p>Loop through the employee object to print all properties.</p>
</li>
</ol>
<blockquote>
<p>Practice by converting real-life things (car, phone, user profile) into objects.</p>
</blockquote>
<h2>Conclusion</h2>
<p>Objects are one of the most important concepts in JavaScript.</p>
<p>They help you:</p>
<ul>
<li><p>Organize data in key-value format</p>
</li>
<li><p>Make code more readable</p>
</li>
<li><p>Represent real-world entities</p>
</li>
</ul>
<p>Once you’re comfortable with objects, you’ll find it much easier to work with APIs, JSON data, and real applications.  </p>
<p>Follow and learn more about Javascript!</p>
]]></content:encoded></item><item><title><![CDATA[Arrow Functions in JavaScript (Beginner-Friendly Guide)]]></title><description><![CDATA[Why arrow functions?
Before arrow functions, writing a function felt like writing duplicate code again and again.
Function Before Arrow Functions:
function add(a, b) {
  return a + b;
}

Arrow functio]]></description><link>https://blog.ashishkumarsaini.dev/arrow-functions-in-javascript</link><guid isPermaLink="true">https://blog.ashishkumarsaini.dev/arrow-functions-in-javascript</guid><category><![CDATA[js-arrow]]></category><category><![CDATA[js-arrow-functions]]></category><category><![CDATA[JavaScript]]></category><dc:creator><![CDATA[Ashish Kumar Saini]]></dc:creator><pubDate>Mon, 23 Mar 2026 04:16:51 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/696877fccb285855f0758646/df9b52f8-3678-415d-8585-0dac364068c0.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2>Why arrow functions?</h2>
<p>Before arrow functions, writing a function felt like writing duplicate code again and again.</p>
<p>Function Before Arrow Functions:</p>
<pre><code class="language-javascript">function add(a, b) {
  return a + b;
}
</code></pre>
<p>Arrow function syntax:</p>
<pre><code class="language-javascript">const add = (a, b) =&gt; a + b;
</code></pre>
<p>Benefits of using arrow functions:</p>
<ol>
<li><p>Clear Syntax</p>
</li>
<li><p>Easier to read</p>
</li>
<li><p>Less Code than normal functions</p>
</li>
</ol>
<p>That's why you can see arrow functions are widely used in modern Javascript.</p>
<h2>What Are Arrow Functions?</h2>
<p>Arrow functions were introduced in ES6 (ES2015) to make code easier and more readable. It is a shorter way of writing functions.</p>
<h3>Basic Arrow Function Syntax</h3>
<pre><code class="language-javascript">const functionName = (parameters) =&gt; {
    // write function logic here  
};
</code></pre>
<p>Example:</p>
<pre><code class="language-javascript">const greet = () =&gt; {
  console.log("Hello!");
};
</code></pre>
<h3>Arrow Function with One Parameter</h3>
<p>If there is only one parameter, you can skip the parentheses.</p>
<pre><code class="language-javascript">const square = num =&gt; {
  return num * num;
};
</code></pre>
<h3>Arrow Function with Multiple Parameters</h3>
<p>If there are <strong>multiple parameters</strong>, parentheses are required.</p>
<pre><code class="language-javascript">const add = (a, b) =&gt; {
  return a + b;
};
</code></pre>
<h2>Implicit Return vs Explicit Return</h2>
<h3>Explicit Return (using <code>return</code>)</h3>
<p>Explicit return in arrow functions means it uses the return keyword inside the function body to return the final result. It is used when the function's body requires multiple statements to calculate the result.</p>
<pre><code class="language-javascript">const multiply = (a, b) =&gt; {
  return a * b;
};
</code></pre>
<h3>Implicit Return (no <code>return</code> keyword)</h3>
<p>The function result can also be returned without the return keyword by removing the function curly braces. This approach will only be applicable where the function will calculate the value in a single statement.</p>
<pre><code class="language-javascript">const multiply = (a, b) =&gt; a * b;
</code></pre>
<h2>Converting Normal Function → Arrow Function</h2>
<p>Normal Function:</p>
<pre><code class="language-javascript">function greet(name) {
  return "Hello " + name;
}
</code></pre>
<p>Arrow Function:</p>
<pre><code class="language-javascript">const greet = name =&gt; "Hello " + name;
</code></pre>
<h2>Arrow Function vs Normal Function</h2>
<table>
<thead>
<tr>
<th>Feature</th>
<th>Normal Function</th>
<th>Arrow Function</th>
</tr>
</thead>
<tbody><tr>
<td>Syntax</td>
<td>Longer</td>
<td>Shorter</td>
</tr>
<tr>
<td><code>this</code></td>
<td>Own <code>this</code></td>
<td>Inherits <code>this</code></td>
</tr>
<tr>
<td>Use Case</td>
<td>General-purpose</td>
<td>Short functions, callbacks</td>
</tr>
</tbody></table>
<blockquote>
<p>For beginners: Use arrow functions for short and simple tasks</p>
</blockquote>
<h2>Simple Examples</h2>
<ul>
<li>Greeting</li>
</ul>
<pre><code class="language-javascript">const greet = name =&gt; "Hello " + name;
</code></pre>
<ul>
<li>Addition</li>
</ul>
<pre><code class="language-javascript">const add = (a, b) =&gt; a + b;
</code></pre>
<ul>
<li>Square</li>
</ul>
<pre><code class="language-javascript">const square = num =&gt; num * num;
</code></pre>
<p>Using an Arrow Function with <code>map()</code></p>
<pre><code class="language-javascript">const numbers = [1, 2, 3, 4];

const squares = numbers.map(num =&gt; num * num);

console.log(squares); // [1, 4, 9, 16]
</code></pre>
<h2>Assignment</h2>
<p>Try these on your own 👇</p>
<ol>
<li><p>Write a normal function to calculate the square of a number</p>
</li>
<li><p>Rewrite it using an arrow function</p>
</li>
<li><p>Create an arrow function that checks if a number is even or odd</p>
</li>
<li><p>Use an arrow function inside <code>map()</code> on an array</p>
</li>
</ol>
<h2>Arrow Function Breakdown</h2>
<pre><code class="language-javascript">const add = (a, b) =&gt; a + b;
</code></pre>
<ul>
<li><p><code>const add</code> → function name</p>
</li>
<li><p><code>(a, b)</code> → parameters</p>
</li>
<li><p><code>=&gt;</code> → arrow syntax</p>
</li>
<li><p><code>a + b</code> → returned value</p>
</li>
</ul>
<h2>Conclusion</h2>
<ul>
<li><p>Arrow functions make your code.</p>
</li>
<li><p>Cleaner</p>
</li>
<li><p>Shorter</p>
</li>
<li><p>More modern</p>
</li>
</ul>
<p>Follow the series for more blogs!</p>
]]></content:encoded></item><item><title><![CDATA[Javascript Function Declaration vs Function Expression: What’s the Difference?]]></title><description><![CDATA[While you start writing programs for real world problems, you might have notices that there are many actions which need to be perform multiple times. For that you might have write duplicate code at se]]></description><link>https://blog.ashishkumarsaini.dev/javascript-function</link><guid isPermaLink="true">https://blog.ashishkumarsaini.dev/javascript-function</guid><category><![CDATA[js functions]]></category><category><![CDATA[JavaScript]]></category><dc:creator><![CDATA[Ashish Kumar Saini]]></dc:creator><pubDate>Sat, 21 Mar 2026 13:07:48 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/696877fccb285855f0758646/a22dc3df-d503-467f-b716-28b45d731478.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>While you start writing programs for real world problems, you might have notices that there are many actions which need to be perform multiple times. For that you might have write duplicate code at separate places in the code.</p>
<p>That’s where functions come in.</p>
<h2>What are functions? Why we need functions?</h2>
<p>Functions are a piece of code written that can perform a specific task. There are a code blocks which can be reusable at multiple places.</p>
<p>Instead of writing same logic to separate places you can it inside a function and use it where ever you need it.</p>
<h3>Real life analogy</h3>
<p>Imagine a coffee machine ☕️</p>
<p>Actions perform in a coffee machine:</p>
<ol>
<li><p>Press the button</p>
</li>
<li><p>Grinding</p>
</li>
<li><p>Brewing</p>
</li>
<li><p>Filtering</p>
</li>
<li><p>Gives coffee</p>
</li>
</ol>
<p>These are all the separate methods done by the coffee machine.</p>
<p>Examples: Without function:</p>
<pre><code class="language-javascript">const sum1 = 1 + 2; // 3
const sum2 = 2 + 3; // 5
const sum3 = 3 + 4; // 7
const sum4 = 4 + 5; // 9
</code></pre>
<p>You can see we have the write the logic to add the number multiple times. Instead of this we can write a function sum which can return the sum of two number. We just had to provide the two numbers to the functions.</p>
<p>Examples: With function:</p>
<pre><code class="language-javascript">function sum (number1, number2){
    return number1 + number2;
}

const sum1 = sum(1, 2); // 3
const sum2 = sum(2, 3); // 5
const sum2 = sum(3, 4); // 7
const sum2 = sum(4, 5); // 9
</code></pre>
<h2>How to create functions?</h2>
<p>We can create functions by different ways:</p>
<ol>
<li><p>Function Declaration Syntax</p>
</li>
<li><p>Function Expression Syntax</p>
</li>
</ol>
<p>Let's discuss them one by one:</p>
<h2>Function Declaration Syntax</h2>
<p>This is the most common way of creating the functions:</p>
<pre><code class="language-javascript">function sum (number1, number2) {
    return number1 + number2
}
</code></pre>
<p>Key points:</p>
<ol>
<li><p><code>function</code> keyword</p>
</li>
<li><p>name of the functions (<code>sum</code>)</p>
</li>
<li><p>Can be called anywhere (explained more later in this blog)</p>
</li>
</ol>
<h2>Function Expression Syntax</h2>
<p>In this approach, a function is stored in a variable:</p>
<pre><code class="language-javascript">const sum = function (number1, number2) {
    return number1 + number2
}
</code></pre>
<p>Key points:</p>
<ol>
<li><p>Function is declared using <code>function</code> keyword.</p>
</li>
<li><p>Function has no name.</p>
</li>
<li><p>Function reference is stored in a variable. A variable should have a name.</p>
</li>
<li><p>Can be called using the variables. In this case, you can call <code>sum()</code> as it stores the reference of the function. Ideally, the function is called</p>
</li>
</ol>
<h3>Declaration vs Expression (Side-by-Side)</h3>
<table>
<thead>
<tr>
<th>Feature</th>
<th>Function Declaration</th>
<th>Function Expression</th>
</tr>
</thead>
<tbody><tr>
<td>Syntax</td>
<td><code>function add() {}</code></td>
<td><code>const add = function() {}</code></td>
</tr>
<tr>
<td>Hoisting</td>
<td>✅ Fully hoisted</td>
<td>❌ Not fully hoisted</td>
</tr>
<tr>
<td>Usage before definition</td>
<td>✅ Works</td>
<td>❌ Error</td>
</tr>
<tr>
<td>Common use</td>
<td>General functions</td>
<td>Callbacks, dynamic logic</td>
</tr>
</tbody></table>
<h2>Hoisting in Functions</h2>
<p>Let's first understand what hoisting is:</p>
<p>Hoisting means: javascript moves declarations to the top before execution.</p>
<p>Example:</p>
<pre><code class="language-javascript">console.log(number1); // undefined

var number1 = 10;
</code></pre>
<p>You might be wondering that <code>console.log(number1)</code> should give an error instead of printing <code>undefined</code>. In Javascript, this is possible because of the concept of <strong>hoisting.</strong></p>
<p>Now try to run the logic below in the browser console dev tool or by creating a JS file and running it using <code>node &lt;filename.js&gt;</code>.</p>
<pre><code class="language-javascript">console.log(number2);
// ReferenceError: Cannot access 'number2' before initialization

const number2 = 20;
</code></pre>
<pre><code class="language-javascript">console.log(number3);
// ReferenceError: Cannot access 'number3' before initialization


const number3 = 30;
</code></pre>
<p>Now, you can see the error while executing this code.</p>
<p>Same applicable on the function.</p>
<p>Hoisting works in declaration syntax:</p>
<pre><code class="language-javascript">const result = sum(1, 2);
console.log(result); // 3

function sum (number1, number2){
    return number1 + number2;
}
</code></pre>
<p>Hoisting doesn't work in declaration syntax:</p>
<pre><code class="language-javascript">const result = sum(1, 2);
console.log(result);
// ReferenceError: Cannot access 'sum' before initialization

const sum = function (number1, number2){
    return number1 + number2;
}
</code></pre>
<h2>When to Use What?</h2>
<h3>Use Function Declaration when:</h3>
<ul>
<li><p>You want simple, reusable functions</p>
</li>
<li><p>You need to call it anywhere in your code</p>
</li>
<li><p>You want a cleaner structure</p>
</li>
</ul>
<h3>Use Function Expression when:</h3>
<ul>
<li><p>You’re passing functions as arguments (callbacks)</p>
</li>
<li><p>You want more control over execution</p>
</li>
<li><p>You’re working with modern patterns (like arrow functions) (Arrow functions we can study in the next blog)</p>
</li>
</ul>
<h2>Execution flow of function call</h2>
<p>You can also read about Javascript code execution in detail in the blog "<strong>Understanding JavaScript Global &amp; Local Execution Context".</strong></p>
<p>For functions, we can understand it stepwise. When a JS code is been executed:</p>
<ol>
<li><p>Javascript scans all the code</p>
</li>
<li><p>Hoist function declaration on top</p>
</li>
<li><p>Start execution line by line</p>
</li>
<li><p>When executing the code, if the function called is hoisted, it will execute that function.</p>
</li>
</ol>
<h2>Assignment (Try It Yourself)</h2>
<ol>
<li><p>Write a function declaration that multiplies two numbers and returns the result.</p>
</li>
<li><p>Write the same logic using a function expression approach.</p>
</li>
<li><p>Call both the functions and try to re-run the logic by updating the values passed to the variable.</p>
</li>
<li><p>Call both the functions before they are defined and try to observe the output (error/result).</p>
</li>
</ol>
<h2>Conclusion</h2>
<p>Functions are the building blocks of any program. You should know that the functions are used for:</p>
<ol>
<li><p>Reusability</p>
</li>
<li><p>Combining Logic</p>
</li>
<li><p>Make code clean and readable</p>
</li>
</ol>
<p>Follow my Javacript series to learn more!</p>
]]></content:encoded></item><item><title><![CDATA[JavaScript Array Methods Every Beginner Should Know]]></title><description><![CDATA[When working with JavaScript, arrays are everywhere. They store lists of items like numbers, names, tasks, or products. But storing data is just the beginning. We often need to add items, remove items]]></description><link>https://blog.ashishkumarsaini.dev/javascript-array-methods</link><guid isPermaLink="true">https://blog.ashishkumarsaini.dev/javascript-array-methods</guid><category><![CDATA[jsarraymethods]]></category><category><![CDATA[jsarray]]></category><category><![CDATA[js-basic]]></category><dc:creator><![CDATA[Ashish Kumar Saini]]></dc:creator><pubDate>Tue, 17 Mar 2026 20:13:32 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/696877fccb285855f0758646/69fab99d-9ef7-4cd9-b701-04105d88ebf6.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>When working with JavaScript, arrays are everywhere. They store lists of items like numbers, names, tasks, or products. But storing data is just the beginning. We often need to add items, remove items, change values, or filter data.</p>
<p>JavaScript has built-in array methods that simplify these tasks.</p>
<p>In this article, we will explore some of the most useful array methods with simple examples:</p>
<ul>
<li><p>push() and pop()</p>
</li>
<li><p>shift() and unshift()</p>
</li>
<li><p>map()</p>
</li>
<li><p>filter()</p>
</li>
<li><p>reduce()</p>
</li>
<li><p>forEach()</p>
</li>
</ul>
<p>You can try all examples directly in your browser console or Node.js.</p>
<p>Lets first understand the methods which are used to add or remove the data in an array:</p>
<h2>push()</h2>
<p>The push() method adds a new element to the end of an array.</p>
<p>Example:</p>
<pre><code class="language-javascript">let fruits = ["Apple", "Banana"];

const newLength = fruits.push("Mango");

console.log(newLength) // 3
console.log(fruits); // ["Apple","Banana","Mango"]
</code></pre>
<p>It returns the updated length of array.</p>
<p>Push is generally used when adding a new item to a list, such as adding a task to a to-do list.</p>
<h2>pop()</h2>
<p>The pop() is used to remove the last element from the array.</p>
<p>Example:</p>
<pre><code class="language-javascript">const items = ["Shoe", "Tshirt", "Trouser"];

const popItem = items.pop();

console.log(popItem); // 'Trouser'
console.log(items);   // ["Shoe", "Tshirt"]
</code></pre>
<p>It returns the element that is removed.</p>
<h2>shift()</h2>
<p>The shift() method removes the first element of an array.</p>
<p>Example:</p>
<pre><code class="language-javascript">const items = ["Shoe", "Tshirt", "Trouser"];

const shiftItem = items.shift();

console.log(shiftItem); // "Shoe"
console.log(items);     // ["Tshirt", "Trouser"]
</code></pre>
<p>It returns the item which is removed. This works same as Queues in real life</p>
<h2>unshift()</h2>
<p>The unshift() method adds an item to the start of the array.</p>
<p>Example:</p>
<pre><code class="language-javascript">const items = ["Shoe", "Tshirt", "Trouser"];

const popItem = items.unshift("Shirt");

console.log(popItem); // 4
console.log(items);   // [ 'Shirt', 'Shoe', 'Tshirt', 'Trouser' ]
</code></pre>
<p>It returns the new length of the array.</p>
<p>Let's understand the methods that are used to perform iteration (loop) on an array</p>
<h2>forEach()</h2>
<p>forEach() is used to perform an action on each element of an array.</p>
<p>It accepts a callback function that accepts three arguments, provided by forEach itself.</p>
<ul>
<li><p>value: element of array</p>
</li>
<li><p>index: position of element in array</p>
</li>
<li><p>array: complete array</p>
</li>
</ul>
<p>forEach() runs a function for every item in the array.</p>
<p>Example:</p>
<pre><code class="language-javascript">const numbers = [1, 2, 3]

numbers.forEach((num) =&gt; {
    console.log(num);
});

Output:
1
2
3
</code></pre>
<h2>Traditional Loop vs forEach()</h2>
<p>for loop:</p>
<pre><code class="language-javascript">let numbers = [1, 2, 3];

for (let i = 0; i &lt; numbers.length; i++) {
    console.log(numbers[i]);
}
</code></pre>
<p>vs</p>
<p>forEach:</p>
<pre><code class="language-javascript">let numbers = [1, 2, 3];

numbers.forEach(function(num) { 
    console.log(num); 
});
</code></pre>
<p>As we can see in the above example, forEach is more cleaner and easier to read and use.</p>
<h2>map()</h2>
<p>map() creates a new array by updating each element based on the logic inside the callback.</p>
<blockquote>
<p>Assume map() to be turning a crate of fruit into a crate of juices.</p>
<p>The number of juice will remain same as the number of fruits.</p>
</blockquote>
<p>It accepts a callback function that accepts three arguments, provided by map itself.</p>
<ul>
<li><p>value: element of array</p>
</li>
<li><p>index: position of element in array</p>
</li>
<li><p>array: complete array</p>
</li>
</ul>
<p>Example:</p>
<pre><code class="language-javascript">const numbers = [1, 2, 3];

const doubledNumbers = numbers.map((num) =&gt; {
    return num * 2;
});

console.log(doubledNumbers);

Output: [2, 4, 6] // updated values

console.log(numbers);

Output: [1, 2, 3] // remains same
</code></pre>
<p>map() returns an updated elements array. Also, it doesn't update the original array.</p>
<h2>filter()</h2>
<p>filter() creates a new array that only includes elements that satisfy the condition inside the callback function.</p>
<p>It accepts a callback function that accepts three arguments, provided by filter itself.</p>
<ul>
<li><p>value: element of array</p>
</li>
<li><p>index: position of element in array</p>
</li>
<li><p>array: complete array</p>
</li>
</ul>
<p>Example:</p>
<pre><code class="language-javascript">const numbers = [3, 7, 10, 2];

const filteredNumbers = numbers.filter((num) =&gt; {
    if(num &gt; 5){
        return true;
    }
    
    return false;
});

console.log(filtersNumbers);

Output: [7, 10]
</code></pre>
<p>So, returned array only includes those values for which callback return true.</p>
<h3>How filter() work?</h3>
<p>Here:</p>
<ul>
<li><p>For 3, the callback returns false. <code>filteredNumbers</code> doesn't contain 3</p>
</li>
<li><p>For 7, the callback returns true. <code>filteredNumbers</code> contain 7</p>
</li>
<li><p>For 10, the callback returns true. <code>filteredNumbers</code> contain 10</p>
</li>
<li><p>For 2, the callback returns false. <code>filteredNumbers</code> doesn't contain 2</p>
</li>
</ul>
<h2>reduce()</h2>
<p>reduce() combines all values of an array into a single value.</p>
<blockquote>
<p>Reduce is like combining flour, eggs, and sugar to bake one single cake.</p>
</blockquote>
<p>Common use cases include:</p>
<ul>
<li><p>total sum</p>
</li>
<li><p>calculating totals</p>
</li>
<li><p>combining data</p>
</li>
</ul>
<p>Example:</p>
<pre><code class="language-javascript">let numbers = [5, 10, 20];

let total = numbers.reduce((accumulator, value) =&gt; {
 return accumulator + value; 
}, 0);

console.log(total);

Output: 35
</code></pre>
<p>Returns the single value after the final calculation.</p>
<h3>How reduce() works?</h3>
<p>Sometimes, reduce is very confusing for beginners.</p>
<table>
<thead>
<tr>
<th>value</th>
<th>accumulator</th>
<th>calculation</th>
<th>initialValue</th>
</tr>
</thead>
<tbody><tr>
<td>5</td>
<td>0</td>
<td>0 + 5 = 5</td>
<td>5</td>
</tr>
<tr>
<td>10</td>
<td>5</td>
<td>5 + 10 = 15</td>
<td>15</td>
</tr>
<tr>
<td>20</td>
<td>15</td>
<td>15 + 20 = 35</td>
<td>35</td>
</tr>
</tbody></table>
<p>Visual Idea for reduce()<br />[5, 10, 15]</p>
<p>Step 1 → 0 + 5 = 5<br />Step 2 → 5 + 10 = 15<br />Step 3 → 15 + 15 = 30</p>
<p>Final Result = 30</p>
<h2>Assignment for Practice</h2>
<p>Try this in your browser console.</p>
<ul>
<li><p>Try map()</p>
<ol>
<li><p>Create an array</p>
</li>
<li><p>Double each number using map()</p>
</li>
<li><p>Console the output and observe by updating the array.</p>
</li>
</ol>
</li>
<li><p>Try filter()</p>
<ol>
<li><p>Apply filter() method on map() output</p>
</li>
<li><p>Filter numbers greater than 10</p>
</li>
</ol>
</li>
<li><p>Try reduce()</p>
<ol>
<li><p>Create an array</p>
</li>
<li><p>Add those numbers using reduce() method.</p>
</li>
<li><p>Check the output and retry after updating the values and number of values in array.</p>
</li>
</ol>
</li>
</ul>
<h2>Final Thoughts</h2>
<p>Array methods make JavaScript more powerful and readable.</p>
<p>Instead of writing long loops, you can use:</p>
<ul>
<li><p>map() to change data</p>
</li>
<li><p>filter() to select data</p>
</li>
<li><p>reduce() to combine data</p>
</li>
<li><p>forEach() to loop through items</p>
</li>
</ul>
<p>These methods are commonly used in modern JavaScript, React, and backend development.</p>
<p>The best way to learn them is simple: open your console and experiment with them.</p>
<p>Follow Javascript Series to learn more!</p>
]]></content:encoded></item><item><title><![CDATA[JS Internals: Understanding JavaScript Global & Local Execution Context]]></title><description><![CDATA[Let’s first look at a real-world scenario before jumping into JavaScript.
Imagine a wooden furniture factory that manufactures different types of furniture. To better understand the process, let’s see]]></description><link>https://blog.ashishkumarsaini.dev/javascript-global-local-execution-context</link><guid isPermaLink="true">https://blog.ashishkumarsaini.dev/javascript-global-local-execution-context</guid><category><![CDATA[js exection]]></category><category><![CDATA[Global execution context]]></category><dc:creator><![CDATA[Ashish Kumar Saini]]></dc:creator><pubDate>Sat, 14 Mar 2026 22:57:06 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/696877fccb285855f0758646/5221eff6-eb6d-47d7-9c34-c4b20750b041.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Let’s first look at a real-world scenario before jumping into JavaScript.</p>
<p>Imagine a wooden furniture factory that manufactures different types of furniture. To better understand the process, let’s see how the factory works internally.</p>
<p>The factory uses several types of wood. For simplicity, let’s assume the following types are used:</p>
<ol>
<li><p>Sagwan</p>
</li>
<li><p>Mango</p>
</li>
<li><p>Sheesham</p>
</li>
</ol>
<p>Inside the factory, the work is divided into multiple departments</p>
<ol>
<li><p>Cutting</p>
</li>
<li><p>Framing</p>
</li>
<li><p>Polishing</p>
</li>
<li><p>Cushion</p>
</li>
<li><p>Quality Assurance</p>
</li>
</ol>
<p>There is a centralized execution chain of the factory on which the departments work, and each department performs its task in a specific order in the execution chain.</p>
<img src="https://cdn.hashnode.com/uploads/covers/696877fccb285855f0758646/be9c78b8-ba05-4b5d-999c-892d1d9f56fe.png" alt="" style="display:block;margin:0 auto" />

<p>The entire factory has a central board on which it is mentioned:</p>
<ul>
<li><p>The order of departments working inside the factory</p>
</li>
<li><p>What needs to be done</p>
</li>
</ul>
<img src="https://cdn.hashnode.com/uploads/covers/696877fccb285855f0758646/e8194020-7e32-41e3-99c2-442a7515babe.png" alt="" style="display:block;margin:0 auto" />

<p>Inside the department, there will definitely be so many works which are working one by one for their individual task. So, each department also has its own board (or blackboard) where two things are written:</p>
<ul>
<li><p>The order of individual tasks to be done inside the department</p>
</li>
<li><p>The actual tasks that need to be performed in that department</p>
</li>
</ul>
<img alt="" style="display:block;margin:0 auto" />

<p>There is also a manager in the factory whose job is to:</p>
<ul>
<li><p>Monitor the progress of the work</p>
</li>
<li><p>Ensure that each department performs its task in the correct order</p>
</li>
</ul>
<p>Let's combine the diagrams to see the full factory view:</p>
<img src="https://cdn.hashnode.com/uploads/covers/696877fccb285855f0758646/903ce76a-744f-4da8-8638-503ee2df075c.png" alt="" style="display:block;margin:0 auto" />

<p>Now the factory receives an order to build a wooden sofa with Sagwan wood.</p>
<p>Steps:</p>
<ol>
<li><p>The very first step is to analyze the wood that has been received.</p>
</li>
<li><p>On the central factory blackboard:</p>
<ul>
<li><p>What to be done: Build a sofa with a specific size mentioned</p>
</li>
<li><p>Order of work done: Cutting -&gt; Framing -&gt; Polishing -&gt; Cushion -&gt; QA</p>
</li>
</ul>
</li>
<li><p>Wood comes to the Cutting department. On the Cutting department blackboard:</p>
<ul>
<li><p>What to be done: Cut the wood into a smaller size as mentioned</p>
</li>
<li><p>Order of work: Cut big wood logs -&gt; Cutting into smaller chunks</p>
</li>
</ul>
</li>
<li><p>Chunks of wood come to the Framing department. On the Framing department blackboard:</p>
<ol>
<li><p>What to be done: Frame the received pieces of wood into the given size</p>
</li>
<li><p>Order of work: Smoothen the wood -&gt; Frame into the size of the sofa -&gt; Finishing</p>
</li>
</ol>
</li>
<li><p>A framed sofa comes to the Polishing department. On the Polishing department blackboard:</p>
<ol>
<li><p>What to be done: Polish the received sofa frame</p>
</li>
<li><p>Order of work: Apply polish -&gt; Rubbing</p>
</li>
</ol>
</li>
<li><p>A polished sofa comes to the Cushion department. On the Cushion department blackboard:</p>
<ol>
<li><p>What to be done: Apply a cushion on the sofa frame</p>
</li>
<li><p>Order of work: Cutting cushion -&gt; Stitching and pasting</p>
</li>
</ol>
</li>
<li><p>A final piece comes to the QA department. On the QA department blackboard:</p>
<ol>
<li><p>What to be done: Check the quality and overall sofa</p>
</li>
<li><p>Order of work: Checking the quality</p>
</li>
</ol>
</li>
</ol>
<p>All of these steps are done under the supervision of the manager and if any process fails in between, the manager can ask the department to do the work again properly.</p>
<p>Things to remember:</p>
<ol>
<li><p>The tasks done are executed on the execution chain. The execution chain is inside the factory</p>
</li>
<li><p>There are some sub-tasks inside the department, which are inside the department. But the space allotted to the department is inside the factory, So those subtasks are also belong to the factory.</p>
</li>
</ol>
<p>Javascript program execution works the same way. To understand this, let's replace a few terms with Javascript terminology.</p>
<img alt="" style="display:block;margin:0 auto" />

<p>Here,</p>
<ul>
<li><p>Wood types -&gt; Data types</p>
</li>
<li><p>Factory -&gt; Global Execution Context</p>
</li>
<li><p>Global Execution has two phases:</p>
<ul>
<li><p>Code Phase / Thread Phase</p>
</li>
<li><p>Memory Phase</p>
</li>
</ul>
</li>
<li><p>Departments -&gt; Functions, Functions has its own Local Execution Context, which further has two phases:</p>
<ul>
<li><p>Code Phase / Thread Phase</p>
</li>
<li><p>Memory Phase</p>
</li>
</ul>
</li>
<li><p>Manager -&gt; Call Stack, who is responsible for maintaining the order of execution of the functions.</p>
</li>
</ul>
<p><strong>So, whenever a JS code has been executed:</strong></p>
<ol>
<li><p>A global execution context is created (also known as the Creation Phase).</p>
</li>
<li><p>Declare the variables and store the definition of functions inside the Memory of the Global Execution Context (also known as Memory Phase).</p>
</li>
<li><p>Now the execution of code starts line by line, which checks the current value of the variables in the memory and reads the definitions of the functions from the memory (also known as Code Phase).</p>
</li>
<li><p>If there is any function in the code:</p>
<ol>
<li><p>Create the Local Execution Context for the function.</p>
</li>
<li><p>Declare the variables in Local Execution Context (also known as Memory Phase for Local Context).</p>
</li>
<li><p>Execute the code of the function line by line.</p>
</li>
<li><p>Once all the code inside the function is executed completely, it returns the value to the Global Context</p>
</li>
</ol>
</li>
<li><p>Global Execution Context executes the remaining code until all the code is executed.</p>
</li>
</ol>
<p><strong>Let's take an example to understand the flow:</strong></p>
<p>Here is a small code snippet:</p>
<pre><code class="language-javascript">var value1 = 10;
var value2 = 20;

function sum(sumNum1, sumNum2, sumNum3) {
    return sumNum1 + sumNum2 + sumNum3;
}

function calculate(calcNum1, calcNum2) {
  	var calcNum3 = 30;
    var total = sum(calcNum1, calcNum2, calcNum3);
    return total;
}

var result = calculate(value1, value2);
console.log(result);
</code></pre>
<p>Steps in which JS code is executed:</p>
<h3><strong>Global Execution context (Factory)</strong></h3>
<ol>
<li><p><strong>Creation Phase</strong><br />Global Execution Context is created<br />(<em>Blackboard for the factory is ready</em>)  </p>
<p>global is assigned to <code>this</code> (Global can vary depending on the environment in which the code is running. In the browser, it will be a window object.)</p>
<pre><code class="language-javascript">Global Execution Context Memory
________________________________________________________
| window: global object                                |
| this: window                                         |
--------------------------------------------------------
</code></pre>
</li>
<li><p><strong>Memory Phase</strong>: Variable and Function Definition get stored in Global Memory<br />(<em>What to be done, the size, and the material of the sofa are now mentioned on the blackboard</em>)  </p>
<p><code>value1</code> is declared in memory with a value <code>undefined</code><br /><code>value2</code> is declared in memory with a value <code>undefined</code><br />The declaration of the <code>sum</code> function is stored in memory.<br />The declaration of the <code>calculate</code> function is stored in memory.<br /><code>result</code> is declared in the memory with a value <code>undefined</code></p>
<pre><code class="language-javascript">Global Execution Context Memory
________________________________________________________
| window: global object                                |
| this: window                                         |
|                                                      |
| value1: undefined                                    |
| value2: undefined                                    |
| sum: fn()                                            |
| calculate: fn()                                      |
| result: undefined                                    |
--------------------------------------------------------
</code></pre>
</li>
<li><p><strong>Execution Phase</strong>: Execution of code line by line. Execution is done by the JS engine on main thread.<br />(<em>Sofa building process starts now</em>)  </p>
<p>The value of <code>value1</code> is initialized as <code>10</code>.<br />The value of <code>value2</code> is initialized as <code>20</code>.<br />The <code>calculate</code> function is called, so a new <strong>Local Execution Context</strong> is created and pushed onto the <strong>Call Stack</strong>.</p>
<pre><code class="language-javascript">Global Execution Context Memory
________________________________________________________
| window: global object                                |
| this: window                                         |
|                                                      |
| value1: 10                                           |
| value2: 20                                           |
| sum: fn()                                            |
| calculate: fn()                                      |
| result: undefined                                    |
--------------------------------------------------------
</code></pre>
<ol>
<li><p><strong>Creation Phase:</strong> Local Execution Context is created for calculate<br />(<em>Blackboard for the Department is ready</em>)  </p>
<p><code>calcNum1</code> is declared in memory with a value <code>10</code><br /><code>calcNum2</code> is declared in memory with a value <code>20</code></p>
<pre><code class="language-javascript">Global Execution Context Memory
________________________________________________________
| window: global object                                |
| this: window                                         |
|                                                      |
| value1: 10                                           |
| value2: 20                                           |
| sum: fn()                                            |
| calculate: fn()                                      |
|                                                      |
| Local Execution Context Memory for calculate()       |
| ---------------------------------------------------- |
| | this: window                                     | |
| | calcNum1: 10                                     | |
| | calcNum2: 20                                     | |
| | total: undefined                                 | |
| ---------------------------------------------------- |
|                                                      |
| result: undefined                                    |
--------------------------------------------------------
</code></pre>
</li>
<li><p><strong>Memory Phase</strong>: Variable and Function Definition get stored in Local Memory<br />(<em>What to be done and the used things are now mentioned on the department blackboard</em>)  </p>
<p><code>calcNum3</code> is declared in memory with a value <code>undefined</code><br /><code>total</code> is declared in memory with a value <code>undefined</code></p>
<pre><code class="language-javascript">Global Execution Context Memory
________________________________________________________
| window: global object                                |
| this: window                                         |
|                                                      |
| value1: 10                                           |
| value2: 20                                           |
| sum: fn()                                            |
| calculate: fn()                                      |
|                                                      |
| Local Execution Context Memory for calculate()       |
| ---------------------------------------------------- |
| | this: window                                     | |
| | calcNum1: 10                                     | |
| | calcNum2: 20                                     | |
| | calcNum3: undefined                              | |
| | total: undefined                                 | |
| ---------------------------------------------------- |
|                                                      |
| result: undefined                                    |
--------------------------------------------------------
</code></pre>
</li>
<li><p><strong>Execution Phase</strong>: Execution inside <code>calculate</code> function. Execution of code line by line on main thread.  </p>
<p>The value of <code>calcNum3</code> is initialized as <code>30</code>.<br />The <code>sum</code> function is called, so a new <strong>Local Execution Context</strong> is created and pushed onto the <strong>Call Stack</strong>.</p>
<pre><code class="language-javascript">Global Execution Context Memory
________________________________________________________
| window: global object                                |
| this: window                                         |
|                                                      |
| value1: 10                                           |
| value2: 20                                           |
| sum: fn()                                            |
| calculate: fn()                                      |
|                                                      |
| Local Execution Context Memory for calculate()       |
| ---------------------------------------------------- |
| | this: window                                     | |
| | calcNum1: 10                                     | |
| | calcNum2: 20                                     | |
| | calcNum3: undefined                              | |
| | total: undefined                                 | |
| ---------------------------------------------------- |
|                                                      |
| result: undefined                                    |
--------------------------------------------------------
</code></pre>
<h3>Local Execution Context (Departments)</h3>
<ol>
<li><p><strong>Creation Phase:</strong> Local Execution Context is created for sum<br />(<em>Blackboard for the Sub-Department is ready</em>)  </p>
<p><code>sumNum1</code> is declared in memory with a value <code>10</code><br /><code>sumNum2</code> is declared in memory with a value <code>20</code><br /><code>sumNum3</code> is declared in memory with a value <code>30</code></p>
<pre><code class="language-javascript">Global Execution Context Memory
________________________________________________________
| window: global object                                |
| this: window                                         |
|                                                      |
| value1: 10                                           |
| value2: 20                                           |
| sum: fn()                                            |
| calculate: fn()                                      |
|                                                      |
| Local Execution Context Memory for calculate()       |
| ---------------------------------------------------- |
| | this: window                                     | |
| | calcNum1: 10                                     | |
| | calcNum2: 20                                     | |
| | calcNum3: undefined                              | |
| | total: undefined                                 | |
| |                                                  | |
| | Local Execution Context Memory for sum()         | |
| | ________________________________________________ | |
| | | this: window                                 | | |
| | | sumNum1: 10                                  | | |
| | | sumNum2: 20                                  | | |
| | | sumNum3: 30                                  | | |
| | ------------------------------------------------ | |
| ---------------------------------------------------- |
|                                                      |
| result: undefined                                    |
--------------------------------------------------------
</code></pre>
</li>
<li><p><strong>Memory Phase:</strong> SInce there is no variable value needs to be assigned to memory. Nothing will happen for sum function in this phase.</p>
</li>
<li><p><strong>Execution Phase:</strong> Sum of 3 variables has been returned by sum function.</p>
</li>
<li><p>The execution context for <strong>sum</strong> is now destroyed.</p>
</li>
</ol>
</li>
<li><p><strong>Execution Phase</strong>: Back to execution of calculate function<br />The value of <code>total</code> is now been updated to <code>60</code>  </p>
<pre><code class="language-javascript">Global Execution Context Memory
________________________________________________________
| window: global object                                |
| this: window                                         |
|                                                      |
| value1: 10                                           |
| value2: 20                                           |
| sum: fn()                                            |
| calculate: fn()                                      |
|                                                      |
| Local Execution Context Memory for calculate()       |
| ---------------------------------------------------- |
| | this: window                                     | |
| | calcNum1: 10                                     | |
| | calcNum2: 20                                     | |
| | calcNum3: undefined                              | |
| | total: 60                                        | |
| ---------------------------------------------------- |
|                                                      |
| result: undefined                                    |
--------------------------------------------------------
</code></pre>
</li>
<li><p><strong>Execution Phase</strong>: The value of <code>total</code> is now been returned and the Local Context for <code>calculate</code> is now destroyed.</p>
</li>
</ol>
</li>
<li><p><strong>Execution Phase</strong>: Back to execution of global context<br />The value of <code>result</code> is now been updated to <code>60</code>  </p>
<pre><code class="language-javascript">Global Execution Context Memory
________________________________________________________
| window: global object                                |
| this: window                                         |
|                                                      |
| value1: 10                                           |
| value2: 20                                           |
| sum: fn()                                            |
| calculate: fn()                                      |
|                                                      |
| result: 60                                           |
--------------------------------------------------------
</code></pre>
</li>
<li><p><strong>Execution Phase</strong>: console.log reads result from memory and prints <code>60</code></p>
</li>
</ol>
<h2>Call Stack (Manager)</h2>
<p>The Call Stack works like a stack of tasks.</p>
<p>When a function is called, its execution context is pushed onto the stack.</p>
<p>When the function finishes execution, it is popped from the stack.</p>
<h2>Single thread</h2>
<p>You have heard about that Javascript is single thread language.</p>
<p>That means:</p>
<ul>
<li><p>Global code runs on main thread</p>
</li>
<li><p>When execution of code contains a function</p>
<ul>
<li><p>A local context is created</p>
</li>
<li><p>That context is pushed into Call stack</p>
</li>
<li><p>The main thread now start executing the function logic</p>
</li>
<li><p>After execution, the local context is removed and destroyed</p>
</li>
</ul>
</li>
<li><p>No other thread is created while execution other than main thread.</p>
</li>
</ul>
<blockquote>
<p>Function create execution context, not threads</p>
</blockquote>
<h2>Assignment for practice</h2>
<p>Install Node.js (runtime environment) and VSCode (code editor)</p>
<p>Open VSCode, create a file <code>practice.js</code> and copy the above code into that file.</p>
<p>Click on Terminal -&gt; New Terminal from the menu bar on top.</p>
<p>From select terminal, selected "Javascript Debug Terminal".</p>
<img src="https://cdn.hashnode.com/uploads/covers/696877fccb285855f0758646/f152b8e4-c03e-48e7-b6e8-f8cc73a8bd74.png" alt="" style="display:block;margin:0 auto" />

<p>Add breakpoints by clicking on the gutter (the space). Red dot indicate that the breakpoint is added on that line.</p>
<img src="https://cdn.hashnode.com/uploads/covers/696877fccb285855f0758646/2c07ed69-2207-49a9-81d2-81c59179f0a8.png" alt="" style="display:block;margin:0 auto" />

<p>Now, run <code>node practice.js</code> . Make sure you are in the same folder inside the terminal.</p>
<p>Try to play around with the next breakpoint button and observe the values of the context section.</p>
<img src="https://cdn.hashnode.com/uploads/covers/696877fccb285855f0758646/a46f40b4-49f1-415d-8ccf-10f6e9622b47.png" alt="" style="display:block;margin:0 auto" />

<h2>Conclusion</h2>
<p>JavaScript executes code using Execution Contexts and the Call Stack.</p>
<p>The Global Execution Context runs first, and every function call creates a new Local Execution Context.</p>
<p>These contexts are managed by the Call Stack to ensure that code executes in the correct order.  </p>
<p>Follow the series to learn more about Javascript.</p>
]]></content:encoded></item></channel></rss>