<?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[Shkaai]]></title><description><![CDATA[Shkaai]]></description><link>https://blog.shwetacodes.pro</link><generator>RSS for Node</generator><lastBuildDate>Tue, 14 Apr 2026 22:36:48 GMT</lastBuildDate><atom:link href="https://blog.shwetacodes.pro/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Async/Await in JavaScript: Writing Cleaner Asynchronous Code]]></title><description><![CDATA[In this article we'll understand the async-await keyword of JavaScript. Before understanding what something is, it is always a good idea to know why it exist at all. So to answer that question look at]]></description><link>https://blog.shwetacodes.pro/async-await-in-javascript-writing-cleaner-asynchronous-code</link><guid isPermaLink="true">https://blog.shwetacodes.pro/async-await-in-javascript-writing-cleaner-asynchronous-code</guid><category><![CDATA[ChaiCode]]></category><category><![CDATA[JavaScript]]></category><dc:creator><![CDATA[Shweta Nigam]]></dc:creator><pubDate>Mon, 13 Apr 2026 09:33:42 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/67aa11e6e2231673d3db79d1/dfd5711b-31f6-4814-a2f9-d1e6bec4fa33.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In this article we'll understand the async-await keyword of JavaScript. Before understanding what something is, it is always a good idea to know why it exist at all. So to answer that question look at this code which isn't using async-await keyword:</p>
<pre><code class="language-js">function fetchUser() {
  fetch("https://api.example.com/user")
    .then(response =&gt; response.json())
    .then(data =&gt; {
      console.log("User:", data);
      return fetch(`https://api.example.com/posts/${data.id}`);
    })
    .then(response =&gt; response.json())
    .then(posts =&gt; {
      console.log("Posts:", posts);
    })
    .catch(err =&gt; {
      console.log("Error:", err);
    });
}
</code></pre>
<p>At first glance, this might look fine. But as the logic grows:</p>
<ul>
<li><p>Multiple <code>.then()</code> chains make it harder to follow</p>
</li>
<li><p>Error handling becomes less intuitive</p>
</li>
<li><p>Code readability decreases</p>
</li>
</ul>
<p>This is exactly why async/await was introduced</p>
<hr />
<h2>Why Async/Await Was Introduced</h2>
<p>Async/await is syntactic sugar over Promises.</p>
<p>It doesn’t replace Promises — it simply provides a cleaner and more readable way to write asynchronous code.</p>
<h3>Problems it solves:</h3>
<ul>
<li><p>Deep <code>.then()</code> chaining</p>
</li>
<li><p>Callback-like nesting</p>
</li>
<li><p>Difficult debugging in complex flows</p>
</li>
</ul>
<hr />
<h2>How Async Functions Work</h2>
<p>An <code>async</code> function always returns a Promise.</p>
<pre><code class="language-js">async function greet() {
  return "Hello";
}
</code></pre>
<p>This is equivalent to:</p>
<pre><code class="language-js">function greet() {
  return Promise.resolve("Hello");
}
</code></pre>
<p>Even if you return a normal value, JavaScript wraps it inside a Promise.</p>
<hr />
<h2>Await Keyword Concept</h2>
<p>The <code>await</code> keyword can only be used inside an async function.</p>
<p>It pauses execution until a Promise is resolved.</p>
<pre><code class="language-js">async function fetchUser() {
  let response = await fetch("https://api.example.com/user");
  let data = await response.json();

  console.log("User:", data);

  let postResponse = await     fetch(`https://api.example.com/posts/${data.id}`);
  let posts = await postResponse.json();

  console.log("Posts:", posts);
}
</code></pre>
<h3>What changed?</h3>
<ul>
<li><p>No <code>.then()</code> chaining</p>
</li>
<li><p>Step-by-step execution</p>
</li>
<li><p>Much easier to read and understand</p>
</li>
</ul>
<p>It looks like synchronous code, but it’s still asynchronous under the hood.</p>
<hr />
<h2>Error Handling with Async Code</h2>
<p>Instead of <code>.catch()</code>, async/await uses <code>try...catch</code>.</p>
<pre><code class="language-js">async function fetchUser() {
  try {
    let response = await fetch("https://api.example.com/user");
    let data = await response.json();

    let postResponse = await fetch(`https://api.example.com/posts/${data.id}`);
    let posts = await postResponse.json();

    console.log(posts);
  } catch (error) {
    console.log("Error:", error.message);
  }
}
</code></pre>
<h3>Why this is better:</h3>
<ul>
<li><p>Cleaner structure</p>
</li>
<li><p>Centralized error handling</p>
</li>
<li><p>Similar to synchronous programming</p>
</li>
</ul>
<hr />
<h2>Comparison with Promises</h2>
<h3>Using Promises:</h3>
<pre><code class="language-js">fetch("https://api.example.com/data")
  .then(res =&gt; res.json())
  .then(data =&gt; console.log(data))
  .catch(err =&gt; console.log(err));
</code></pre>
<h3>Using Async/Await:</h3>
<pre><code class="language-js">async function getData() {
  try {
    let res = await fetch("https://api.example.com/data");
    let data = await res.json();
    console.log(data);
  } catch (err) {
    console.log(err);
  }
}
</code></pre>
<h3>Key Differences:</h3>
<table>
<thead>
<tr>
<th>Feature</th>
<th>Promises</th>
<th>Async/Await</th>
</tr>
</thead>
<tbody><tr>
<td>Syntax</td>
<td><code>.then()</code> chains</td>
<td>Clean &amp; linear</td>
</tr>
<tr>
<td>Readability</td>
<td>Medium</td>
<td>High</td>
</tr>
<tr>
<td>Error Handling</td>
<td><code>.catch()</code></td>
<td><code>try...catch</code></td>
</tr>
</tbody></table>
<hr />
<h2>Why Async/Await Improves Readability</h2>
<ul>
<li><p>Code flows <strong>top-to-bottom</strong></p>
</li>
<li><p>Less nesting</p>
</li>
<li><p>Easier to debug</p>
</li>
<li><p>More intuitive for beginners</p>
</li>
</ul>
<p>You write async code the same way you think about it.</p>
<hr />
<h2>Final Thoughts</h2>
<p>Async/await is one of the most important features in modern JavaScript.</p>
<ul>
<li><p>It is built on top of Promises</p>
</li>
<li><p>Makes asynchronous code cleaner</p>
</li>
<li><p>Reduces complexity in real-world applications</p>
</li>
</ul>
<hr />
<h2>Quick Summary</h2>
<ul>
<li><p><code>async</code> → makes a function return a Promise</p>
</li>
<li><p><code>await</code> → pauses execution until Promise resolves</p>
</li>
<li><p>Works only inside async functions</p>
</li>
<li><p>Uses <code>try...catch</code> for error handling</p>
</li>
<li><p>Improves readability significantly</p>
</li>
</ul>
<hr />
<p>Once you start using async/await, going back to <code>.then()</code> chains will feel unnecessarily complicated</p>
<p>.</p>
]]></content:encoded></item><item><title><![CDATA[Error Handling in JavaScript: Try, Catch, Finally]]></title><description><![CDATA[In this article we'll understand error handling in JavaScript using try, catch, and finally. Errors are something every developer faces, no matter how experienced they are. Sometimes code breaks unexp]]></description><link>https://blog.shwetacodes.pro/error-handling-in-javascript-try-catch-finally</link><guid isPermaLink="true">https://blog.shwetacodes.pro/error-handling-in-javascript-try-catch-finally</guid><category><![CDATA[ChaiCode]]></category><category><![CDATA[JavaScript]]></category><dc:creator><![CDATA[Shweta Nigam]]></dc:creator><pubDate>Tue, 24 Mar 2026 05:58:46 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/67aa11e6e2231673d3db79d1/37b00790-2b87-4f8b-b40a-c4aa2b06ad26.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In this article we'll understand error handling in JavaScript using try, catch, and finally. Errors are something every developer faces, no matter how experienced they are. Sometimes code breaks unexpectedly and if we don’t handle it properly, it can crash the whole application. That’s why JavaScript gives us tools to handle these situations in a controlled way. If you've ever seen your app stop working because of a small mistake, this is exactly what helps you avoid that. Let’s break it down in a simple way so you can use it confidently.</p>
<h3>What errors are in JavaScript</h3>
<p>Errors in JavaScript are situations where something goes wrong while executing code. It could be due to wrong syntax, accessing something that doesn’t exist, or unexpected values.</p>
<p>In simple words, error are unexpected situations and outputs.</p>
<p>Example:</p>
<pre><code class="language-js">console.log(x); // ReferenceError: x is not defined
</code></pre>
<p>There are different types of errors like:</p>
<ul>
<li><p>Syntax Error (wrong code structure)</p>
</li>
<li><p>Reference Error (variable not defined)</p>
</li>
<li><p>Type Error (wrong data usage)</p>
</li>
</ul>
<h3>Using try and catch blocks</h3>
<p>The try block lets you write code that might cause an error, and the catch block handles that error without breaking the program.</p>
<pre><code class="language-js">try {
  let result = JSON.parse("invalid json");
} catch (error) {
  console.log("Something went wrong:", error.message);
}
</code></pre>
<p>So instead of crashing, your program safely handles the issue.</p>
<h3>The finally block</h3>
<p>The finally block always runs, no matter what happens — whether an error occurs or not.</p>
<pre><code class="language-js">try {
  console.log("Trying...");
} catch (err) {
  console.log("Error occurred");
} finally {
  console.log("This always runs");
}
</code></pre>
<p>This is useful for cleanup tasks like closing connections or stopping loaders.</p>
<h3>Throwing custom errors</h3>
<p>You can also create your own errors using throw. This helps when you want to manually stop execution based on conditions.</p>
<pre><code class="language-js">function withdraw(amount) {
  if (amount &gt; 1000) {
    throw new Error("Limit exceeded");
  }
  return "Success";
}
</code></pre>
<p>This gives you control over when and why errors should happen.</p>
<h3>Why error handling matters</h3>
<p>Error handling is important because:</p>
<ul>
<li><p>It prevents your app from crashing</p>
</li>
<li><p>Helps in debugging issues</p>
</li>
<li><p>Improves user experience</p>
</li>
<li><p>Makes code more reliable and predictable</p>
</li>
</ul>
<p>Without it, even a small issue can break the entire flow of your application.</p>
<p>At the end, error handling is not just about fixing errors, it’s about managing them smartly. Using try, catch, and finally properly can make your code much more stable and professional.</p>
<h3>Summary</h3>
<p>In this article we understood how error handling works in JavaScript using try, catch, and finally. Errors are common but handling them properly makes your application stronger. Try is used to write risky code, catch handles the error, and finally runs no matter what. We also saw how to throw custom errors when needed. Once you start using these concepts, your code will become safer and easier to manage.</p>
]]></content:encoded></item><item><title><![CDATA[Spread vs Rest Operators in JavaScript]]></title><description><![CDATA[In this article we'll understand the spread operator and rest operator. Why do we need to know the different in the first place? Well because they both are denoted with same thing and that is 'three d]]></description><link>https://blog.shwetacodes.pro/spread-vs-rest-operators-in-javascript</link><guid isPermaLink="true">https://blog.shwetacodes.pro/spread-vs-rest-operators-in-javascript</guid><category><![CDATA[ChaiCode]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[Spread operator]]></category><category><![CDATA[Rest operator]]></category><dc:creator><![CDATA[Shweta Nigam]]></dc:creator><pubDate>Tue, 24 Mar 2026 05:42:40 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/67aa11e6e2231673d3db79d1/51f3657b-f339-404a-9c15-391d7cd1acf0.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In this article we'll understand the spread operator and rest operator. Why do we need to know the different in the first place? Well because they both are denoted with same thing and that is 'three dots'. If you're someone who face confusion between them, don't worry then you are not alone. We'll solve the mystery of these <code>...</code> so that you won't feel confuse about them ever.</p>
<h3>What spread operator does</h3>
<p>The spread operator is used to "expand" values. It takes something like an array or object and spreads out its elements one by one.</p>
<p>Think of it like opening a packed box and laying everything out.</p>
<p>Example with array:</p>
<pre><code class="language-javascript">const arr = [1, 2, 3];
const newArr = [...arr];

console.log(newArr); // [1, 2, 3]
</code></pre>
<p>Example with function:</p>
<pre><code class="language-javascript">const nums = [5, 10, 15];

function sum(a, b, c) {
  return a + b + c;
}

console.log(sum(...nums)); // 30
</code></pre>
<p>Here spread takes the array and passes values individually.</p>
<h3>What rest operator does</h3>
<p>The rest operator does the opposite. Instead of expanding, it collects values into a single structure.</p>
<p>Think of it like packing multiple items into one box.</p>
<p>Example:</p>
<pre><code class="language-javascript">function collect(...args) {
  console.log(args);
}

collect(1, 2, 3, 4); // [1, 2, 3, 4]
</code></pre>
<p>Here all arguments are collected into one array called args.</p>
<p>Another example:</p>
<pre><code class="language-javascript">const [first, ...rest] = [10, 20, 30, 40];

console.log(first); // 10
console.log(rest);  // [20, 30, 40]
</code></pre>
<h3>Differences between spread and rest</h3>
<p>Even though both use <code>...</code>, their behaviour depends on where they are used.</p>
<p>Spread:</p>
<ul>
<li><p>Expands values</p>
</li>
<li><p>Used when passing or copying data</p>
</li>
<li><p>Mostly seen on right side</p>
</li>
</ul>
<p>Rest:</p>
<ul>
<li><p>Collects values</p>
</li>
<li><p>Used in function parameters or destructuring</p>
</li>
<li><p>Mostly seen on left side</p>
</li>
</ul>
<p>Simple way to remember:<br />Spread = open things<br />Rest = gather things</p>
<h3>Using spread with arrays and objects</h3>
<p>Spread with arrays:</p>
<pre><code class="language-javascript">const a = [1, 2];
const b = [3, 4];

const combined = [...a, ...b];
console.log(combined); // [1, 2, 3, 4]
</code></pre>
<p>Copy array:</p>
<pre><code class="language-javascript">const original = [1, 2, 3];
const copy = [...original];
</code></pre>
<p>Spread with objects:</p>
<pre><code class="language-javascript">const user = { name: "Alex", age: 20 };

const updatedUser = { ...user, age: 21 };

console.log(updatedUser);

// output:
// { name: "Alex", age: 21 };
</code></pre>
<p>Merge objects:</p>
<pre><code class="language-javascript">const a = { x: 1 };
const b = { y: 2 };

const merged = { ...a, ...b };
console.log(merged)

//output:
// {x:1,y:2}
</code></pre>
<h3>Practical use cases</h3>
<ol>
<li>Copying data without mutation</li>
</ol>
<p>[ note: Spread operator is not recommended with nested array and objects, as they copy only first layer. ]</p>
<pre><code class="language-javascript">const arr = [1, 2, 3];
const newArr = [...arr];
</code></pre>
<ol>
<li>Merging arrays</li>
</ol>
<pre><code class="language-javascript">const all = [...arr1, ...arr2];
</code></pre>
<ol>
<li>Passing dynamic arguments</li>
</ol>
<pre><code class="language-javascript">Math.max(...numbers);
</code></pre>
<ol>
<li>Removing properties using rest</li>
</ol>
<pre><code class="language-javascript">const user = { id: 1, name: "Sam", password: "1234" };

const { password, ...safeUser } = user;
console.log(safeUser);
</code></pre>
<ol>
<li>Handling unknown number of function arguments</li>
</ol>
<pre><code class="language-javascript">function sum(...nums) {
  return nums.reduce((a, b) =&gt; a + b, 0);
}
</code></pre>
<p>At the end, both spread and rest are simple once you understand their intention. Same syntax, different behaviour. Just remember one expands and the other collects, and you will never mix them up again.</p>
]]></content:encoded></item><item><title><![CDATA[String Polyfills and Common Interview Methods in JavaScript]]></title><description><![CDATA[JavaScript strings look simple on the surface, but they hide a lot of interesting behavior underneath. As developers, we use string methods like slice(), includes(), and trim() almost every day withou]]></description><link>https://blog.shwetacodes.pro/string-polyfills-and-common-interview-methods-in-javascript</link><guid isPermaLink="true">https://blog.shwetacodes.pro/string-polyfills-and-common-interview-methods-in-javascript</guid><category><![CDATA[ChaiCode]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[interview]]></category><dc:creator><![CDATA[Shweta Nigam]]></dc:creator><pubDate>Fri, 20 Mar 2026 07:16:41 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/67aa11e6e2231673d3db79d1/0f84bb03-d724-4e0d-bbab-820d5b70c8eb.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>JavaScript strings look simple on the surface, but they hide a lot of interesting behavior underneath. As developers, we use string methods like <code>slice()</code>, <code>includes()</code>, and <code>trim()</code> almost every day without thinking twice. They make our work easier, cleaner, and more readable. But in interviews and deeper problem-solving scenarios, just knowing how to use them is not enough.</p>
<p>In this blog, we’ll break down what string methods really are, why developers write polyfills, how to implement common string utilities on your own, and the types of string problems you’ll often face in interviews. The goal is simple: move from just using JavaScript to actually understanding it.</p>
<h2>What string methods are</h2>
<p>String methods are built-in functions that JavaScript gives us to work with text. Instead of manually looping through characters or writing complex logic, we can directly use methods like toUpperCase(), slice(), includes(), trim(), etc.</p>
<p>For example:</p>
<pre><code class="language-javascript">const name = "hello world";
console.log(name.toUpperCase()); // HELLO WORLD
</code></pre>
<p>These methods are already optimized and tested, so in real-world development we mostly rely on them instead of reinventing the wheel.</p>
<p>But interviews are different. There, you are often asked to implement these methods yourself to check your understanding.</p>
<h2>Why developers write polyfills</h2>
<p>A polyfill is basically your own implementation of a built-in method.</p>
<p>Why would someone do that?</p>
<p>First, older browsers may not support newer methods. For example, includes() was not supported in very old browsers, so developers wrote polyfills to make it work everywhere.</p>
<p>Second, interviews. Interviewers want to see if you actually understand how things work behind the scenes instead of just using them.</p>
<p>Third, learning. Writing a polyfill forces you to think deeply about edge cases, loops, indexing, and behavior.</p>
<p>So instead of this:</p>
<pre><code class="language-javascript">"hello".includes("ell");
</code></pre>
<p>You might be asked to implement your own version.</p>
<h3>Implementing simple string utilities</h3>
<p>Let’s look at how we can build some basic string methods ourself.</p>
<ol>
<li>Custom includes()</li>
</ol>
<pre><code class="language-javascript">
function myIncludes(str, search) { 
for (let i = 0; i &lt;= str.length - search.length; i++) { 
let found = true;
for (let j = 0; j &lt; search.length; j++) {
  if (str[i + j] !== search[j]) {
    found = false;
    break;
  }
}

if (found) return true;
}

return false; 
}
</code></pre>
<ol>
<li><p>Custom reverse string</p>
<pre><code class="language-javascript">function reverseString(str) {
 let result = "";

for (let i = str.length - 1; i &gt;= 0; i--) {
 result += str[i]; 
}

return result; }
</code></pre>
</li>
</ol>
<p>3. Custom trim()</p>
<pre><code class="language-javascript">function myTrim(str) { 
let start = 0;
let end = str.length - 1;

while (str[start] === " ") start++; 
while (str[end] === " ") end--;

return str.slice(start, end + 1); 
}
</code></pre>
<p>When you write these, you start understanding how strings are just sequences of characters and how indexing works internally.</p>
<h2>Common interview string problems</h2>
<p>String questions are extremely common in interviews because they test logic, edge cases, and problem-solving.</p>
<p>Some popular ones:</p>
<ol>
<li>Check palindrome</li>
</ol>
<pre><code class="language-javascript">function isPalindrome(str) { 
let left = 0; 
let right = str.length - 1;

while (left &lt; right) {
 if (str[left] !== str[right]) return false;
 left++;
 right--; 
}

return true; 
}
</code></pre>
<ol>
<li><p><strong>Count characters</strong></p>
<pre><code class="language-javascript">function charCount(str) {
  const map = {};

  for (let char of str) {
    map[char] = (map[char] || 0) + 1;
  }

  return map;
}
</code></pre>
</li>
<li><p>Find first non-repeating character</p>
<pre><code class="language-javascript">function firstUnique(str) { 
const map = {};

for (let char of str) { 
map[char] = (map[char] || 0) + 1; 
}

for (let char of str) {
if (map[char] === 1) return char; 
}

return null; }
</code></pre>
</li>
<li><p>Anagram check</p>
</li>
</ol>
<pre><code class="language-javascript">function isAnagram(a, b) { 
if (a.length !== b.length) return false;

const count = {};

for (let char of a) { 
count[char] = (count[char] || 0) + 1; 
}

for (let char of b) { 
if (!count[char]) return false; count[char]--; 
}

return true; }
</code></pre>
<p>These problems are not about memorizing solutions, but understanding patterns like frequency maps, two pointers, and traversal.</p>
<p><strong>Importance of understanding built-in behavior</strong></p>
<p>Most developers use built-in methods daily, but very few understand how they actually behave.</p>
<p>For example:</p>
<ul>
<li><p>slice() does not modify the original string</p>
</li>
<li><p>substring() handles negative values differently</p>
</li>
<li><p>trim() removes only whitespace, not all characters</p>
</li>
<li><p>Strings are immutable in JavaScript</p>
</li>
</ul>
<p>If you don’t know these details, you can easily make mistakes.</p>
<p>Understanding internals helps you:</p>
<ul>
<li><p>Debug faster</p>
</li>
<li><p>Write optimized code</p>
</li>
<li><p>Handle edge cases better</p>
</li>
<li><p>Perform well in interviews</p>
</li>
</ul>
<p>It also builds strong fundamentals, which is what companies actually look for.</p>
<h2>Final thought</h2>
<p>Using string methods is easy. Understanding them is what makes you strong. If you can both use a method and implement it yourself, you are no longer just a user of JavaScript, you actually understand how it works.</p>
]]></content:encoded></item><item><title><![CDATA[Understanding the 'this' Keyword in JavaScript]]></title><description><![CDATA[The this keyword is one of the most misunderstood concepts in JavaScript, but the core idea is simple. The value of this depends on how a function is called, not where it is written. It represents the]]></description><link>https://blog.shwetacodes.pro/understanding-the-this-keyword-in-javascript</link><guid isPermaLink="true">https://blog.shwetacodes.pro/understanding-the-this-keyword-in-javascript</guid><category><![CDATA[ChaiCode]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[this keyword in javascript]]></category><dc:creator><![CDATA[Shweta Nigam]]></dc:creator><pubDate>Fri, 20 Mar 2026 05:55:27 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/67aa11e6e2231673d3db79d1/e5a1ea07-3e52-4035-a2a2-880360c28666.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>The <code>this</code> keyword is one of the most misunderstood concepts in JavaScript, but the core idea is simple. The value of <code>this</code> depends on how a function is called, not where it is written. It represents the <mark class="bg-yellow-200 dark:bg-yellow-500/30">current execution context</mark>, meaning the object that is invoking the function at that moment.</p>
<h2>What <code>this</code> represents</h2>
<p><code>this</code> refers to the object that is currently executing the function. It is determined at runtime, so the same function can have different values of <code>this</code> depending on how it is called.</p>
<h2><code>this</code> in global context</h2>
<p>In the global scope:</p>
<pre><code class="language-javascript">console.log(this);
</code></pre>
<p>In the browser, this will refer to the <code>window</code> object. In Node.js, it typically refers to an empty object or the global object depending on the environment. The idea is that when there is no specific caller, <code>this</code> defaults to the global context.</p>
<h2><code>this</code> inside objects</h2>
<p>When a function is called as a method of an object, <code>this</code> refers to that object.</p>
<pre><code class="language-javascript">const user = {
  name: "Alexa",
  greet: function () {
    console.log(this.name);
  }
};

user.greet();
</code></pre>
<p>In this case, <code>this</code> refers to <code>user</code>, so the output is "Alexa". The object before the dot decides what <code>this</code> is.</p>
<h2><code>this</code> inside functions</h2>
<p>When a normal function is called on its own, it does not have an owner object.</p>
<pre><code class="language-javascript">function greet() {
  console.log(this);
}

greet();
</code></pre>
<p>In the browser, this will refer to the global object. In strict mode, it will be <code>undefined</code>. This happens because the function is not being called by any object. And in node.js we'll get reference to global object, similarly <code>undefined</code> in strict mode.</p>
<h2>Arrow function behaviour</h2>
<p>Arrow functions behave differently because they do not have their own <code>this</code>. Instead, they inherit <code>this</code> from the surrounding scope.</p>
<pre><code class="language-javascript">const user = {
  name: "Alexa",
  greet: () =&gt; {
    console.log(this.name);
  }
};

user.greet();
</code></pre>
<p>Here, <code>this</code> does not refer to <code>user</code>. It refers to whatever the surrounding context is, which is usually the global scope, so the result is <code>undefined</code>.</p>
<h2>How calling context changes <code>this</code></h2>
<p>The most important thing to understand is that <code>this</code> changes based on how a function is called.</p>
<pre><code class="language-javascript">const user1 = {
  name: "Alexa",
  greet() {
    console.log(this.name);
  }
};

const user2 = {
  name: "Sam"
};

user2.greet = user1.greet;

user2.greet();
</code></pre>
<p>Even though the function was originally defined in <code>user1</code>, when it is called using <code>user2</code>, <code>this</code> refers to <code>user2</code>, so the output is "Sam".</p>
<p>Another example:</p>
<pre><code class="language-javascript">const user = {
  name: "Alexa",
  greet() {
    console.log(this.name);
  }
};

const fn = user.greet;
fn();
</code></pre>
<p>Here, the function is called without an object, so <code>this</code> becomes undefined (or global in non-strict mode), and the result is not what you might expect.</p>
<h2>Final understanding</h2>
<p>The value of <code>this</code> is not fixed. It is determined by how a function is called. In the global context, it refers to the global object. Inside object methods, it refers to the object calling the method. Inside normal functions, it defaults to global or undefined depending on strict mode. Arrow functions do not have their own <code>this</code> and instead inherit it from their surrounding scope. Once you focus on how a function is invoked, understanding <code>this</code> becomes much clearer.</p>
]]></content:encoded></item><item><title><![CDATA[The new Keyword in JavaScript]]></title><description><![CDATA[In this article we'll learn about another magical keyword of JavaScript, the new keyword. The new keyword is used to create objects from constructor functions. Instead of manually creating an object e]]></description><link>https://blog.shwetacodes.pro/the-new-keyword-in-javascript</link><guid isPermaLink="true">https://blog.shwetacodes.pro/the-new-keyword-in-javascript</guid><category><![CDATA[ChaiCode]]></category><dc:creator><![CDATA[Shweta Nigam]]></dc:creator><pubDate>Fri, 20 Mar 2026 05:30:50 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/67aa11e6e2231673d3db79d1/9bbc16ce-e5fe-4376-8667-e87612172106.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In this article we'll learn about another magical keyword of JavaScript, the <code>new</code> keyword. The <code>new</code> keyword is used to create objects from constructor functions. Instead of manually creating an object every time, <code>new</code> helps automate the process and gives you a clean way to create multiple similar objects.</p>
<p>At a high level, when you use <code>new</code>, JavaScript does a few things behind the scenes:</p>
<ul>
<li><p>creates a brand new empty object</p>
</li>
<li><p>links that object to a prototype</p>
</li>
<li><p>runs the constructor function with <code>this</code> pointing to that new object</p>
</li>
<li><p>returns the object</p>
</li>
</ul>
<p>This is why <code>new</code> is so powerful — it bundles multiple steps into one simple line.</p>
<h2>Constructor functions</h2>
<p>A constructor function is just a normal function, but by convention it starts with a capital letter and is meant to be used with <code>new</code>.</p>
<p>Example:</p>
<pre><code class="language-javascript">function User(name, age) {
  this.name = name;
  this.age = age;
}
</code></pre>
<p>This function doesn’t return anything explicitly, but when used with <code>new</code>, it will create and return an object.</p>
<h2>Object creation process</h2>
<p>Let’s say we do this:</p>
<pre><code class="language-javascript">const user1 = new User("Alex", 25);
</code></pre>
<p>Here’s what actually happens step by step:</p>
<ol>
<li>JavaScript creates an empty object:</li>
</ol>
<pre><code class="language-javascript">{}
</code></pre>
<ol>
<li><p>It sets the prototype of this object to <code>User.prototype</code></p>
</li>
<li><p>It calls the constructor:</p>
</li>
</ol>
<pre><code class="language-javascript">User.call(newObject, "Alex", 25);
</code></pre>
<p>So inside the function:</p>
<pre><code class="language-javascript">this.name = "Alex";
this.age = 25;
</code></pre>
<ol>
<li>Finally, it returns the object</li>
</ol>
<p>So <code>user1</code> becomes:</p>
<pre><code class="language-javascript">{
  name: "Alex",
  age: 25
}
</code></pre>
<h2>How <code>new</code> links prototypes</h2>
<p>This is where things get interesting.</p>
<p>Every function in JavaScript has a <code>prototype</code> property. When you use <code>new</code>, the created object is internally linked to that prototype.</p>
<pre><code class="language-javascript">User.prototype.greet = function () {
  console.log("Hello " + this.name);
};
</code></pre>
<p>Now:</p>
<pre><code class="language-javascript">const user1 = new User("Alex", 25);
user1.greet();
</code></pre>
<p>Even though <code>greet</code> is not inside the object itself, JavaScript looks up the prototype chain and finds it.</p>
<p>So the link looks like this:</p>
<pre><code class="language-javascript">user1 -&gt; User.prototype -&gt; Object.prototype
</code></pre>
<p>This is called the prototype chain.</p>
<h2>Instances created from constructors</h2>
<p>Each time we use <code>new</code>, we create a new instance.</p>
<pre><code class="language-javascript">const user1 = new User("Alexa", 25);
const user2 = new User("Sam", 30);
</code></pre>
<p>Both are separate objects:</p>
<pre><code class="language-javascript">user1 !== user2
</code></pre>
<p>But they share the same prototype:</p>
<pre><code class="language-plaintext">user1.__proto__ === user2.__proto__
</code></pre>
<p>This is efficient because methods are not duplicated for every object -- they live in one place (the prototype).</p>
<h2>Final understanding</h2>
<p>The <code>new</code> keyword is basically a shortcut for creating objects in a structured way. It handles object creation, sets up the prototype chain, binds <code>this</code>, and returns the object automatically. Constructor functions define the blueprint, and each call with <code>new</code> creates a new instance that follows that blueprint while sharing common behaviour through prototypes.</p>
]]></content:encoded></item><item><title><![CDATA[Callbacks in JavaScript: Why They Exist]]></title><description><![CDATA[In this article we'll explore the concept of callbacks in JavaScript along with simple code examples that will help us understand it more easily.
A callback function is a function that is passed into ]]></description><link>https://blog.shwetacodes.pro/callbacks-in-javascript-why-they-exist</link><guid isPermaLink="true">https://blog.shwetacodes.pro/callbacks-in-javascript-why-they-exist</guid><category><![CDATA[ChaiCode]]></category><dc:creator><![CDATA[Shweta Nigam]]></dc:creator><pubDate>Wed, 18 Mar 2026 17:01:26 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/67aa11e6e2231673d3db79d1/51f36e23-8c4c-4395-b493-8ceb78fc1260.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In this article we'll explore the concept of callbacks in JavaScript along with simple code examples that will help us understand it more easily.</p>
<p>A callback function is a function that is passed into another function as an argument and then executed later inside that function. In JavaScript, functions are treated like normal values. This means we can store them in variables, pass them to other functions, and even return them from functions. Because of this feature, one function can receive another function and decide when to execute it. The function that gets passed is called a <strong>callback function</strong>.</p>
<pre><code class="language-javascript">function greet(name, callback) {
  console.log("Hello " + name);
  callback();
}

function sayBye() {
  console.log("Bye!");
}

greet("Sam", sayBye);
</code></pre>
<p>In this example, <code>sayBye</code> is passed into the <code>greet</code> function and executed inside it. Since it is called back by another function, it is known as a callback.</p>
<h2>Why Callbacks Are Used in Asynchronous Programming</h2>
<p>Callbacks are heavily used in <strong>asynchronous programming</strong>. JavaScript runs on a single thread, which means it can only perform one operation at a time. However, many tasks in web development take time, such as fetching data from an API, reading files, or waiting for timers.</p>
<p>If JavaScript waited for each of these tasks to finish before moving forward, the application would freeze. Instead, JavaScript starts the task and continues executing other code. Once the task finishes, a callback function is executed. This allows the program to remain responsive.</p>
<p>A simple example is using <code>setTimeout</code>.</p>
<pre><code class="language-javascript">console.log("Start");

setTimeout(function () {
  console.log("Timer finished");
}, 2000);

console.log("End");
</code></pre>
<p>The function passed to <code>setTimeout</code> is the callback. JavaScript schedules it to run after 2 seconds while continuing to execute the rest of the code. That is why the output becomes:</p>
<p>Start<br />End<br />Timer finished</p>
<h2>Passing Functions as Arguments</h2>
<p>One powerful concept in JavaScript is that functions can be passed as arguments. Since functions are values, they can be sent into other functions to control how those functions behave.</p>
<pre><code class="language-javascript">function processNumber(num, operation) {
  operation(num);
}

function double(n) {
  console.log(n * 2);
}

function square(n) {
  console.log(n * n);
}

processNumber(5, double);
processNumber(5, square);
</code></pre>
<p>In this example, the <code>processNumber</code> function remains the same, but its behavior changes depending on the callback that is passed. This makes code more flexible and reusable.</p>
<h2>Callback Usage in Common Scenarios</h2>
<p>Callbacks appear in many real-world JavaScript situations. One of the most common examples is event handling. When a user clicks a button, types in an input field, or scrolls a page, a callback function runs in response to that event.</p>
<pre><code class="language-javascript">button.addEventListener("click", function () {
  console.log("Button clicked");
});
</code></pre>
<p>The function passed to <code>addEventListener</code> is a callback that runs whenever the click event happens.</p>
<p>Callbacks are also used in:</p>
<ul>
<li><p>Timers like <code>setTimeout</code> and <code>setInterval</code></p>
</li>
<li><p>API requests</p>
</li>
<li><p>File operations in Node.js</p>
</li>
<li><p>Handling user interactions in the browser</p>
</li>
</ul>
<p>Because asynchronous tasks are everywhere in web development, callbacks became a fundamental part of JavaScript programming.</p>
<h2>Basic Problem of Callback Nesting</h2>
<p>Although callbacks are useful, they can sometimes lead to messy code when multiple asynchronous operations depend on each other. This situation is known as callback nesting, often referred to as callback hell.</p>
<pre><code class="language-javascript">loginUser(function () {
  getUserProfile(function () {
    getPosts(function () {
      console.log("All data loaded");
    });
  });
});
</code></pre>
<p>Here each step waits for the previous one to complete, which forces the code into deeper levels of nesting. As the number of operations increases, the code becomes harder to read, maintain, and debug.</p>
<p>Because of this problem, modern JavaScript introduced <strong>Promises</strong> and later <strong>async/await</strong>, which allow developers to handle asynchronous operations in a cleaner and more structured way.</p>
<p>And saved our eyes and brain!</p>
]]></content:encoded></item><item><title><![CDATA[Template Literals in JavaScript]]></title><description><![CDATA[In JavaScript, working with strings is very common. Developers often need to combine text with variables, create dynamic messages, or write multi-line strings. Earlier versions of JavaScript relied he]]></description><link>https://blog.shwetacodes.pro/template-literals-in-javascript</link><guid isPermaLink="true">https://blog.shwetacodes.pro/template-literals-in-javascript</guid><category><![CDATA[ChaiCode]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[template literals]]></category><dc:creator><![CDATA[Shweta Nigam]]></dc:creator><pubDate>Tue, 17 Mar 2026 15:44:34 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/67aa11e6e2231673d3db79d1/305b0708-0c65-4177-a088-c611c22dfa8d.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In JavaScript, working with strings is very common. Developers often need to combine text with variables, create dynamic messages, or write multi-line strings. Earlier versions of JavaScript relied heavily on string concatenation, which often made code difficult to read and maintain. Template literals were introduced in modern JavaScript to make string handling easier and more expressive.</p>
<p>In this article we will understand the problems with traditional string concatenation, learn the syntax of template literals, see how variables can be embedded inside strings, explore multi-line strings, and understand some practical use cases.</p>
<h2>Problems with Traditional String Concatenation</h2>
<p>Before template literals were introduced, JavaScript developers commonly used the <code>+</code> operator to combine strings and variables.</p>
<p>Example:</p>
<pre><code class="language-javascript">const name = "Ravi"; 
const age = 25;

const message = "My name is " + name + " and I am " + age + " years old."; console.log(message);
</code></pre>
<p>While this works, the code becomes harder to read when many variables are involved.</p>
<p>Example:</p>
<pre><code class="language-javascript">const product = "Laptop";
const price = 60000;

const text = "The price of " + product + " is " + price + " rupees.";
</code></pre>
<p>As the string grows longer, the concatenation operators make the code cluttered. This approach also becomes inconvenient when creating multi-line strings because developers had to manually include newline characters like \n.</p>
<h3>Template Literal Syntax</h3>
<p>Template literals were introduced in modern JavaScript to make string creation simpler and cleaner. Instead of using single quotes or double quotes, template literals use backticks.</p>
<p>Example:</p>
<pre><code class="language-javascript">const message = `Hello World`;
console.log(message);
</code></pre>
<p>The backtick character allows us to create dynamic strings more easily.</p>
<p>Template literals support additional features such as embedding variables and writing multi-line strings without special characters.</p>
<h3>Embedding Variables in Strings</h3>
<p>One of the most useful features of template literals is the ability to insert variables directly inside a string. This is done using the ${} syntax.</p>
<p>Example:</p>
<pre><code class="language-javascript">const name = "Ravi";
const age = 25;
const message = `My name is \({name} and I am \){age} years old.`; console.log(message);
</code></pre>
<p>This approach is easier to read compared to string concatenation because the variables appear directly within the sentence structure.</p>
<p>We can also include expressions inside the curly braces.</p>
<p>Example:</p>
<pre><code class="language-javascript">const a = 5;
const b = 10;

const result = The sum of \({a} and \){b} is ${a + b}.; 
console.log(result);
</code></pre>
<p>JavaScript evaluates the expression inside ${} and inserts the result into the string.</p>
<h3>Multi-line Strings</h3>
<p>Creating multi-line strings used to require newline characters or concatenation.</p>
<p>Example using older syntax:</p>
<pre><code class="language-javascript">const text = `"This is line one.\n" + "This is line two.\n" + "This is line three."`;
</code></pre>
<p>Template literals allow us to write multi-line strings naturally.</p>
<p>Example:</p>
<pre><code class="language-javascript">const text = `This is line one.
 This is line two.
 This is line three.`;

console.log(text)
</code></pre>
<p>This makes the code much cleaner and easier to maintain.</p>
<h3>Use Cases in Modern JavaScript</h3>
<p>Template literals are widely used in modern JavaScript development.</p>
<p>They are commonly used when generating dynamic messages that include variables or expressions.</p>
<p>Example:</p>
<pre><code class="language-javascript">const user = "Ankit";
const greeting = `Welcome back, ${user}!`;
</code></pre>
<p>Template literals are also frequently used when creating HTML structures dynamically.</p>
<p>Example:</p>
<pre><code class="language-javascript">const title = "JavaScript Basics";

const html = `${title} Learning JavaScript is fun.`; 
</code></pre>
<p>They are also useful when formatting logs or debugging messages.</p>
<p>Example:</p>
<pre><code class="language-javascript">const item = "Book"; 
const price = 300;

console.log(`The \({item} costs \){price} rupees.`);
</code></pre>
<p>Template literals improve readability and reduce errors when building complex strings.</p>
<h3>Conclusion</h3>
<p>Template literals provide a modern and powerful way to work with strings in JavaScript. They solve many problems associated with traditional string concatenation and make code easier to read and maintain. By using backticks, developers can embed variables, write expressions inside strings, and create multi-line text without extra syntax. Understanding template literals is an essential step toward writing cleaner and more expressive JavaScript code.</p>
]]></content:encoded></item><item><title><![CDATA[Array Flatten in JavaScript]]></title><description><![CDATA[In this article we will understand nested arrays and how to flatten them in JavaScript. Many beginners(including me) get confused when arrays start containing other arrays inside them. We will learn w]]></description><link>https://blog.shwetacodes.pro/array-flatten-in-javascript</link><guid isPermaLink="true">https://blog.shwetacodes.pro/array-flatten-in-javascript</guid><category><![CDATA[ChaiCode]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[array]]></category><dc:creator><![CDATA[Shweta Nigam]]></dc:creator><pubDate>Tue, 17 Mar 2026 14:58:31 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/67aa11e6e2231673d3db79d1/2e78f40b-c7a1-4a48-a6f0-a42c26d44f02.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In this article we will understand nested arrays and how to flatten them in JavaScript. Many beginners(including me) get confused when arrays start containing other arrays inside them. We will learn what nested arrays are, why flattening them is useful, different ways to flatten arrays, and how this topic often appears in coding interviews.</p>
<h2>What Nested Arrays Are</h2>
<p>A nested array simply means an array that contains another array inside it.</p>
<p>Example:</p>
<pre><code class="language-javascript">const arr = [1, 2, [3, 4], 5];
</code></pre>
<p>Here the main array contains another array <code>[3, 4]</code>. That makes it a nested array.</p>
<p>Nested arrays can go even deeper.</p>
<pre><code class="language-javascript">const arr = [1, [2, [3, 4]], 5];
</code></pre>
<p>Here we have arrays inside arrays multiple levels deep. This structure is common when working with data from APIs or complex data structures.</p>
<h2>Why Flattening Arrays Is Useful</h2>
<p>Flattening an array means converting a nested array into a single-level array.</p>
<p>For example:</p>
<pre><code class="language-javascript">const arr = [1, 2, [3, 4], 5];
</code></pre>
<p>Flattened version:</p>
<pre><code class="language-javascript">[1, 2, 3, 4, 5]
</code></pre>
<p>Flattening becomes useful in many situations.</p>
<p>Sometimes APIs return nested arrays that are hard to process. Flattening them makes the data easier to loop through or manipulate. Many array methods like map, filter, and reduce work more smoothly when the array is a single level. Flattening simplifies data processing. It is also useful when combining results from multiple arrays or working with grouped data.</p>
<h2>Concept of Flattening Arrays</h2>
<p>The basic idea of flattening is simple.</p>
<p>We look at each item of the array. If the item is a normal value, we add it to the result array. If the item is another array, we go inside it and add its elements instead.</p>
<p>Example input:</p>
<pre><code class="language-javascript">[1, [2, 3], 4]
</code></pre>
<p>Process:</p>
<pre><code class="language-plaintext">1 → add to result
[2,3] → open it and add 2 and 3
4 → add to result
</code></pre>
<p>Result:</p>
<pre><code class="language-javascript">[1, 2, 3, 4]
</code></pre>
<h3>Different Approaches to Flatten Arrays</h3>
<p>There are several ways to flatten arrays in JavaScript.</p>
<p>Using flat()</p>
<p>JavaScript provides a built-in method called flat.</p>
<pre><code class="language-javascript">const arr = [1, 2, [3, 4]];
const result = arr.flat();

console.log(result);
</code></pre>
<p>Output:</p>
<pre><code class="language-javascript">[1, 2, 3, 4]
</code></pre>
<p>If the array has deeper nesting, we can specify the depth.</p>
<pre><code class="language-javascript">arr.flat(2);
</code></pre>
<p>If we want to flatten everything regardless of depth:</p>
<pre><code class="language-javascript">arr.flat(Infinity);
</code></pre>
<p>Using reduce()</p>
<p>Another common approach is using reduce.</p>
<pre><code class="language-javascript">const arr = [1, [2, 3], 4];

const result = arr.reduce((acc, curr) =&gt; {
  return acc.concat(curr);
}, []);

console.log(result);
</code></pre>
<p>This works well for one-level nested arrays.</p>
<p>Using recursion</p>
<p>Recursion is often used to flatten arrays of any depth.</p>
<pre><code class="language-javascript">function flatten(arr) {
  let result = [];

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

  return result;
}

const arr = [1, [2, [3, 4]], 5];
console.log(flatten(arr));
</code></pre>
<p>Output:</p>
<pre><code class="language-javascript">[1, 2, 3, 4, 5]
</code></pre>
<p>This method checks if an element is an array. If it is, it recursively flattens it.</p>
<h3>Common Interview Scenarios</h3>
<p>Flattening arrays is a common topic in JavaScript interviews. One common question is to flatten an array without using the built-in flat method. Interviewers usually expect a recursive solution.</p>
<p>Another scenario is flattening an array only one level deep.</p>
<p>Flattening arrays is a common topic in JavaScript interviews.</p>
<p>One common question is to flatten an array without using the built-in flat method. Interviewers usually expect a recursive solution.</p>
<p>Another scenario is flattening an array only one level deep.</p>
<h3>Summary</h3>
<p>JavaScript provides different ways to flatten arrays, such as using the built-in <code>flat()</code> method, using <code>reduce()</code>, or writing a recursive function to handle arrays of any depth.</p>
<p>Flattening arrays is also a common topic in coding interviews because it tests a developer’s understanding of arrays, recursion, and problem-solving. Learning how to flatten arrays helps developers work more effectively with structured data in JavaScript.</p>
]]></content:encoded></item><item><title><![CDATA[JavaScript Modules: Import and Export ]]></title><description><![CDATA[In this article we'll understand the JavaScript modules with simple explanations. Imagine having your JavaScript projects growing, keeping all code in one file becomes messy. That’s why modules exist.]]></description><link>https://blog.shwetacodes.pro/javascript-modules-import-and-export</link><guid isPermaLink="true">https://blog.shwetacodes.pro/javascript-modules-import-and-export</guid><category><![CDATA[ChaiCode]]></category><dc:creator><![CDATA[Shweta Nigam]]></dc:creator><pubDate>Tue, 17 Mar 2026 11:32:49 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/67aa11e6e2231673d3db79d1/5acf3a9e-c053-4a3a-8a97-16733ece431a.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In this article we'll understand the JavaScript modules with simple explanations. Imagine having your JavaScript projects growing, keeping all code in one file becomes messy. That’s why modules exist. Let’s go step-by-step in a clear beginner-friendly way.</p>
<h3>Why Modules Are Needed</h3>
<p>Imagine writing everything in one file. Small code files seems handleable but what if it becomes 5000+ or 10000+ . That is where the nightmare of developer's begin. Your code becomes hard to find, maintain, naming conflicts arises and reusing code becomes hard to impossible.</p>
<p>That is where Module comes to rescue you from the mess we just discussed.</p>
<h3>What is module?</h3>
<p>Think of module as splitting code into separate files, where each file handles one responsibility.</p>
<p>We can see here:</p>
<pre><code class="language-javascript">project --

        -- math.js 
        -- greeting.js 
        -- app.js
</code></pre>
<p>Each becomes a module as each file has single responsibility. This makes code clean, organized and reusable. Saving us from a lot of headache.</p>
<h3>Exporting functions or values</h3>
<p>Remember that a module only exposes things you export. Anything not exported stays private to the file.</p>
<p>for example:</p>
<pre><code class="language-javascript">export function add(a, b) { 
return a + b; 
}
export function multiply(a, b) {
 return a * b;
 }
</code></pre>
<p>Here we are exporting add and multiply function so we can use them in other files.</p>
<p>We can export not only functions but other things as well, let's see them.</p>
<p><strong>Exporting Variables:</strong></p>
<pre><code class="language-javascript">export const PI = 3.14;
</code></pre>
<p><strong>Exporting Objects:</strong></p>
<pre><code class="language-javascript">export const user = {
  name: "Sam",
  age: 25
};
</code></pre>
<p>What we can understand from this is that whatever you export becomes available for other files as well.</p>
<h3>Importing Modules</h3>
<p>Above we learnt that to make one file available we have to export it but that was only 50% of the module story, there is something call importing the modules which complete the entire story. We import the needed files to use them after making them available by exporting them. And this completes the 100% of module story.</p>
<p>for example:</p>
<pre><code class="language-javascript">import { add } from "./index.js";

console.log(add(2, 3));
</code></pre>
<p><strong>Import Multiple Things</strong></p>
<pre><code class="language-javascript">import { add, multiply } from "./math.js";
</code></pre>
<p><strong>Import Everything</strong></p>
<pre><code class="language-javascript">import * as math from "./math.js";

console.log(math.add(2,3));
console.log(math.multiply(2,3));
</code></pre>
<p>When we write this, we are importing everything that is exported from <code>math.js</code> and grouping it into a single object called <code>math</code> and internally it behaves like this:</p>
<pre><code class="language-javascript">math = { 
add: function,
multiply: function,
}
</code></pre>
<h3>Default vs Named Exports</h3>
<p>This is one of the most confusing topics , so let’s break it clearly.</p>
<p><strong>Named Export</strong></p>
<p>You export multiple things by name.</p>
<h3>math.js</h3>
<pre><code class="language-javascript">export function add(a, b) {
  return a + b;
}

export function subtract(a, b) {
  return a - b;
}
</code></pre>
<p>Import</p>
<pre><code class="language-javascript">import { add, subtract } from "./math.js";
</code></pre>
<p>Notice the curly braces <code>{}</code></p>
<p>Because we are importing by name.</p>
<h3>Default Export</h3>
<p>A module can have only one default export.</p>
<p><strong>greeting.js</strong></p>
<pre><code class="language-javascript">export default function greet(name) {
  return "Hello " + name;
}
</code></pre>
<p>Import</p>
<pre><code class="language-javascript">import greet from "./greeting.js";
</code></pre>
<p>No <code>{}</code> needed.</p>
<p>For default export we can do something like this:</p>
<h3>Example</h3>
<pre><code class="language-javascript">export default function greet() {}
</code></pre>
<p>You can import it like:</p>
<pre><code class="language-javascript">import hello from "./greet.js"
</code></pre>
<p>or</p>
<pre><code class="language-javascript">import anything from "./greet.js"
</code></pre>
<p>In conclusion the name does not matter. (Yup! it does not matter, I find it quite interesting)</p>
<h3>Benefits of modular code</h3>
<p>Modules provide several advantages when building JavaScript applications.</p>
<p><em><strong>Better organization</strong></em><br />Breaking code into modules makes large projects easier to navigate and understand.</p>
<p><em><strong>Code reusability</strong></em><br />Functions and utilities written in one module can be reused across different parts of the project.</p>
<p><em><strong>Easier maintenance</strong></em><br />If something breaks, developers can quickly locate the module responsible for the issue and fix it.</p>
<p><em><strong>Team collaboration</strong></em><br />Different developers can work on different modules at the same time without interfering with each other’s work.</p>
<p><em><strong>Encapsulation</strong></em><br />Modules allow developers to hide internal implementation details and only expose the necessary parts of the code.</p>
<h3>Summary</h3>
<p>As JavaScript applications grow in size, modules become an essential tool for keeping projects organized, scalable, and maintainable. It save us a lot of time and headache!</p>
]]></content:encoded></item><item><title><![CDATA[The Magic of this, call(), apply(), and bind() in JavaScript]]></title><description><![CDATA[In this article we'll learn about one of most important topics of JavaScript. These are the topics that help you crack the interview and write good and efficient code as a developer. We'll be discussi]]></description><link>https://blog.shwetacodes.pro/this-call-apply-and-bind-in-javascript</link><guid isPermaLink="true">https://blog.shwetacodes.pro/this-call-apply-and-bind-in-javascript</guid><category><![CDATA[ChaiCode]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[Chaiaurcode]]></category><dc:creator><![CDATA[Shweta Nigam]]></dc:creator><pubDate>Tue, 10 Mar 2026 08:05:06 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/67aa11e6e2231673d3db79d1/52ba1631-2bea-4883-a7bd-f84dfce605d1.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In this article we'll learn about one of most important topics of JavaScript. These are the topics that help you crack the interview and write good and efficient code as a developer. We'll be discussing <code>this</code> keyword, call(), apply() and bind() with simple explanation and examples.</p>
<h2><code>this</code> keyword in JavaScript</h2>
<p>When learning JavaScript, one thing that confuses many beginners is the <code>this</code> keyword. At first it looks mysterious. But once you understand the idea, it becomes much easier. Let’s break it down step by step.</p>
<p>Always remember that <code>this</code>always refers to the current context. By context I mean who is calling "this".</p>
<p>Let's take simple a non-tech example</p>
<p>If Alice says:</p>
<pre><code class="language-plaintext">I am a developer
</code></pre>
<p>“I” refers to <strong>Alice</strong>.</p>
<p>If Bob says:</p>
<pre><code class="language-plaintext">I am a developer
</code></pre>
<p>“I” refers to <strong>Bob</strong>.</p>
<p>JavaScript works in the same way.</p>
<h2><code>this</code> inside a normal function</h2>
<p>In a normal function, <code>this</code> usually refers to the global object. In browsers, the global object is <code>window</code>. And in nodejs the global object is different.</p>
<p>Example:</p>
<pre><code class="language-javascript">function showThis() {
  console.log(this);
}

showThis();
</code></pre>
<p>Output (in browser):</p>
<pre><code class="language-javascript">Window {...}
</code></pre>
<p>Why?</p>
<p>Because no object called the function, so JavaScript defaults to the global object. Here it is very important to note that where your are running the code. Because the environment decides the current context and as I mentioned earlier that <code>this</code> points to the current context.</p>
<h2><code>this</code> inside an object</h2>
<p>When a function is inside an object, <code>this</code> refers to <strong>that object</strong>.</p>
<p>Example:</p>
<pre><code class="language-javascript">const person = {
  name: "Alex",
  greet: function () {
    console.log("Hi, my name is " + this.name);
  }
};

person.greet();
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">Hi, my name is Alex
</code></pre>
<p>Why?</p>
<p>Because <code>person</code> called the function.</p>
<p>So:</p>
<pre><code class="language-javascript">this = person
</code></pre>
<h2>What does <code>call()</code> do?</h2>
<p><code>call()</code> lets you borrow a function and choose what <code>this</code> should be.</p>
<p>Imagine your friend has a car, and you say:</p>
<p>“Can I use your car for a minute?”</p>
<p>That’s what <code>call()</code> does.</p>
<p>Example:</p>
<pre><code class="language-javascript">function introduce() {
  console.log("Hello, I am " + this.name);
}

const user = {
  name: "Shreya"
};

introduce.call(user);
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">Hello, I am Shreya
</code></pre>
<p>Here we manually set <code>this</code> to <code>user</code>. It is a really cool concept.</p>
<h2>What does <code>apply()</code> do?</h2>
<p><code>apply()</code> is almost the same as <code>call()</code>. The only difference is how arguments are passed. <code>apply()</code> takes array as its arguments .</p>
<p>Example:</p>
<pre><code class="language-javascript">function introduce(city, country) {
  console.log(this.name + " lives in " + city + ", " + country);
}

const user = {
  name: "Ram"
};

introduce.apply(user, ["Delhi", "India"]);
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">Ram lives in Delhi, India
</code></pre>
<h2>What does <code>bind()</code> do?</h2>
<p><code>bind()</code> creates a new function with a fixed <code>this</code> value.</p>
<p>Think of it like permanently assigning ownership.</p>
<p>Example:</p>
<pre><code class="language-javascript">function greet() {
  console.log("Hello " + this.name);
}

const user = {
  name: "Amany"
};

const newFunction = greet.bind(user);

newFunction();
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">Hello Amany
</code></pre>
<p><code>bind()</code> does not run immediately. It returns a new function.</p>
<h2>Easy way to remember</h2>
<p>Think of them like borrowing tools.</p>
<p><code>call()</code> :</p>
<p>Use the tool right now</p>
<p><code>apply()</code> :</p>
<p>Use the tool right now but give items in a box (array)</p>
<p><code>bind()</code> :</p>
<p>Take the tool home and use later</p>
<h2>Final Thoughts</h2>
<p>Understanding <code>this</code>, <code>call()</code>, <code>apply()</code>, and <code>bind()</code> is very important in JavaScript because they control how functions behave with different objects.</p>
<p>At first it may look confusing, but remember this simple rule: <code>this</code> depends on who is calling the function.</p>
]]></content:encoded></item><item><title><![CDATA[Object-Oriented Programming in JavaScript]]></title><description><![CDATA[If you are in programming then once in while you must hear about about OOP that stands for OBJECT-ORIENTED-PROGRAMMING. We'll learn about the OOP in this article in simple explanation. Object-Oriented]]></description><link>https://blog.shwetacodes.pro/understanding-object-oriented-programming-in-javascript</link><guid isPermaLink="true">https://blog.shwetacodes.pro/understanding-object-oriented-programming-in-javascript</guid><category><![CDATA[ChaiCode]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[OOP In JavaScript]]></category><dc:creator><![CDATA[Shweta Nigam]]></dc:creator><pubDate>Tue, 10 Mar 2026 07:10:52 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/67aa11e6e2231673d3db79d1/043aba03-e10d-497a-a990-1f48ec06228d.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>If you are in programming then once in while you must hear about about OOP that stands for OBJECT-ORIENTED-PROGRAMMING. We'll learn about the OOP in this article in simple explanation. Object-Oriented Programming does not exist only in JavaScript.<br />OOP is a programming style used in many programming languages.</p>
<p>If we understand OOP in simple explanation then they are a simply a programming style of storing data in "objects" that represent real world things.</p>
<p>So instead of writing random functions and variables to store data, we group related things together. This give clean structure to code and data.</p>
<p>Real world objects like:</p>
<ul>
<li><p>A Car</p>
</li>
<li><p>A User</p>
</li>
<li><p>A Student</p>
</li>
<li><p>A Bank Account</p>
</li>
</ul>
<p>Each object has:</p>
<ul>
<li><p>properties (data - information)</p>
</li>
<li><p>methods (actions - which does something)</p>
</li>
</ul>
<p>For example a Car can has colour, speed and model as it's properties and it can perform actions such as start(), moveAhead(), moveBack() and break().</p>
<h2>Understanding class with Real-world analogy: Blueprint → Objects</h2>
<p>Think about building a house.</p>
<p>First, you create a blueprint.</p>
<p>Then many houses can be built using that blueprint.</p>
<pre><code class="language-plaintext">Blueprint → House 1
          → House 2
          → House 3
</code></pre>
<p>In programming:</p>
<pre><code class="language-plaintext">Class → Object 1
      → Object 2
      → Object 3
</code></pre>
<p>So <code>Class</code> is the blueprint and <code>object</code> are real instance created from the blueprint.</p>
<h2>Class</h2>
<h3>Understanding Class in JavaScript</h3>
<p>A <code>class</code> is a template used to create objects (think of class as blueprint - which help to build many similar things).</p>
<p>Example:</p>
<pre><code class="language-plaintext">class User {
}
</code></pre>
<p>This class currently does nothing.</p>
<p>But it will define how a user object should look.</p>
<h3>Creating Objects Using Classes</h3>
<p>To create an object from a class we use the <code>new</code> **'**keyword'.</p>
<p>Example:</p>
<pre><code class="language-javascript">class User {}

const user1 = new User()
</code></pre>
<p>Here:</p>
<pre><code class="language-plaintext">User → class
user1 → object
</code></pre>
<p>You can create many objects:</p>
<pre><code class="language-javascript">const user1 = new User()
const user2 = new User()
const user3 = new User()
</code></pre>
<h3>Constructor Method</h3>
<p>A constructor is a special method used to initialize objects when they are created.</p>
<p>Example:</p>
<pre><code class="language-javascript">class User {

  constructor(name, age) {
    this.name = name
    this.age = age
  }

}
</code></pre>
<p>Now to create an object:</p>
<pre><code class="language-javascript">const user1 = new User("Sam", 25)

console.log(user1)
</code></pre>
<p>Output:</p>
<pre><code class="language-javascript">{ name: "Sam", age: 25 }
</code></pre>
<p>Explanation:</p>
<pre><code class="language-javascript">this.name = name
this.age = age
</code></pre>
<p><code>this</code> refers to the <em>current object being created.</em></p>
<h3>Methods Inside a Class</h3>
<p>Methods are functions inside a class.</p>
<p>They describe actions an object can perform.</p>
<p>Example:</p>
<pre><code class="language-javascript">class User {

  constructor(name, age) {
    this.name = name
    this.age = age
  }

  greet() {
    console.log("Hello, my name is " + this.name)
  }

}
</code></pre>
<p>Create an object:</p>
<pre><code class="language-javascript">const user1 = new User("Sam", 25)

user1.greet()
</code></pre>
<p>Output:</p>
<pre><code class="language-javascript">Hello, my name is Sam
</code></pre>
<p>Here:</p>
<pre><code class="language-javascript">greet() → method
</code></pre>
<p>Let's understand it with full example:</p>
<pre><code class="language-javascript">class Car {

  constructor(brand, speed) {
    this.brand = brand
    this.speed = speed
  }

  drive() {
    console.log(this.brand + " is driving at " + this.speed + " km/h")
  }

}

const car1 = new Car("Toyota", 120)
const car2 = new Car("BMW", 150)

car1.drive()
car2.drive()
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">Toyota is driving at 120 km/h
BMW is driving at 150 km/h
</code></pre>
<h3>Basic Idea of Encapsulation</h3>
<p>Encapsulation means hiding internal details and controlling access to data.</p>
<p>Example:</p>
<pre><code class="language-javascript">class BankAccount {

  constructor(balance) {
    this.balance = balance
  }

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

  getBalance() {
    return this.balance
  }

}
</code></pre>
<p>Here the user interacts through <strong>methods</strong> instead of changing data directly.</p>
<pre><code class="language-javascript">deposit()
getBalance()
</code></pre>
<p>This protects the data.</p>
<p>In TypeScript we often use:</p>
<pre><code class="language-javascript">private
public
</code></pre>
<p>for better encapsulation.</p>
<h2>Summary</h2>
<p>So in sort we can say that OOP = data + behaviour grouped together inside objects. OOP is an important concept which help us understand and write good code.</p>
]]></content:encoded></item><item><title><![CDATA[Object-Oriented Programming in JavaScript]]></title><description><![CDATA[If you are in programming then once in while you must hear about about OOP that stands for OBJECT-ORIENTED-PROGRAMMING. We'll learn about the OOP in this article in simple explanation. Object-Oriented]]></description><link>https://blog.shwetacodes.pro/Object Oriented Programming in JavaScript</link><guid isPermaLink="true">https://blog.shwetacodes.pro/Object Oriented Programming in JavaScript</guid><category><![CDATA[ChaiCode]]></category><category><![CDATA[Chaiaurcode]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[OOP In JavaScript]]></category><dc:creator><![CDATA[Shweta Nigam]]></dc:creator><pubDate>Tue, 10 Mar 2026 07:02:59 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/67aa11e6e2231673d3db79d1/e04480f0-bff3-40d3-93aa-383dc6dac7bd.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>If you are in programming then once in while you must hear about about OOP that stands for OBJECT-ORIENTED-PROGRAMMING. We'll learn about the OOP in this article in simple explanation. Object-Oriented Programming does not exist only in JavaScript.<br />OOP is a programming style used in many programming languages.</p>
<p>If we understand OOP in simple explanation then they are a simply a programming style of storing data in "objects" that represent real world things.</p>
<p>So instead of writing random functions and variables to store data, we group related things together. This give clean structure to code and data.</p>
<p>Real world objects like:</p>
<ul>
<li><p>A Car</p>
</li>
<li><p>A User</p>
</li>
<li><p>A Student</p>
</li>
<li><p>A Bank Account</p>
</li>
</ul>
<p>Each object has:</p>
<ul>
<li><p>properties (data - information)</p>
</li>
<li><p>methods (actions - which does something)</p>
</li>
</ul>
<p>For example a Car can has colour, speed and model as it's properties and it can perform actions such as start(), moveAhead(), moveBack() and break().</p>
<h2>Understanding class with Real-world analogy: Blueprint → Objects</h2>
<p>Think about building a house.</p>
<p>First, you create a blueprint.</p>
<p>Then many houses can be built using that blueprint.</p>
<pre><code class="language-plaintext">Blueprint → House 1
          → House 2
          → House 3
</code></pre>
<p>In programming:</p>
<pre><code class="language-plaintext">Class → Object 1
      → Object 2
      → Object 3
</code></pre>
<p>So <code>Class</code> is the blueprint and <code>object</code> are real instance created from the blueprint.</p>
<h2>Class</h2>
<h3>Understanding Class in JavaScript</h3>
<p>A <code>class</code> is a template used to create objects (think of class as blueprint - which help to build many similar things).</p>
<p>Example:</p>
<pre><code class="language-plaintext">class User {
}
</code></pre>
<p>This class currently does nothing.  </p>
<p>But it will define how a user object should look.</p>
<h3>Creating Objects Using Classes</h3>
<p>To create an object from a class we use the <code>new</code> **'**keyword'.</p>
<p>Example:</p>
<pre><code class="language-javascript">class User {}

const user1 = new User()
</code></pre>
<p>Here:</p>
<pre><code class="language-plaintext">User → class
user1 → object
</code></pre>
<p>You can create many objects:</p>
<pre><code class="language-javascript">const user1 = new User()
const user2 = new User()
const user3 = new User()
</code></pre>
<h3>Constructor Method</h3>
<p>A constructor is a special method used to initialize objects when they are created.</p>
<p>Example:</p>
<pre><code class="language-javascript">class User {

  constructor(name, age) {
    this.name = name
    this.age = age
  }

}
</code></pre>
<p>Now to create an object:</p>
<pre><code class="language-javascript">const user1 = new User("Sam", 25)

console.log(user1)
</code></pre>
<p>Output:</p>
<pre><code class="language-javascript">{ name: "Sam", age: 25 }
</code></pre>
<p>Explanation:</p>
<pre><code class="language-javascript">this.name = name
this.age = age
</code></pre>
<p><code>this</code> refers to the <em>current object being created.</em></p>
<h3>Methods Inside a Class</h3>
<p>Methods are functions inside a class.</p>
<p>They describe actions an object can perform.</p>
<p>Example:</p>
<pre><code class="language-javascript">class User {

  constructor(name, age) {
    this.name = name
    this.age = age
  }

  greet() {
    console.log("Hello, my name is " + this.name)
  }

}
</code></pre>
<p>Create an object:</p>
<pre><code class="language-javascript">const user1 = new User("Sam", 25)

user1.greet()
</code></pre>
<p>Output:</p>
<pre><code class="language-javascript">Hello, my name is Sam
</code></pre>
<p>Here:</p>
<pre><code class="language-javascript">greet() → method
</code></pre>
<p>Let's understand it with full example:</p>
<pre><code class="language-javascript">class Car {

  constructor(brand, speed) {
    this.brand = brand
    this.speed = speed
  }

  drive() {
    console.log(this.brand + " is driving at " + this.speed + " km/h")
  }

}

const car1 = new Car("Toyota", 120)
const car2 = new Car("BMW", 150)

car1.drive()
car2.drive()
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">Toyota is driving at 120 km/h
BMW is driving at 150 km/h
</code></pre>
<h3>Basic Idea of Encapsulation</h3>
<p>Encapsulation means hiding internal details and controlling access to data.</p>
<p>Example:</p>
<pre><code class="language-javascript">class BankAccount {

  constructor(balance) {
    this.balance = balance
  }

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

  getBalance() {
    return this.balance
  }

}
</code></pre>
<p>Here the user interacts through <strong>methods</strong> instead of changing data directly.</p>
<pre><code class="language-javascript">deposit()
getBalance()
</code></pre>
<p>This protects the data.</p>
<p>In TypeScript we often use:</p>
<pre><code class="language-javascript">private
public
</code></pre>
<p>for better encapsulation.</p>
<h2>Summary</h2>
<p>So in sort we can say that OOP = data + behaviuor grouped together inside objects. OOP is an important concept which help us understand and write good code.</p>
]]></content:encoded></item><item><title><![CDATA[Function Declaration vs Function Expression: What’s the Difference?]]></title><description><![CDATA[In this article we'll learn about function declaration, function expression and the difference between them. Before jumping on the topic itself let's understand the function meaning and it's use. Func]]></description><link>https://blog.shwetacodes.pro/function-declaration-vs-function-expression-what-s-the-difference</link><guid isPermaLink="true">https://blog.shwetacodes.pro/function-declaration-vs-function-expression-what-s-the-difference</guid><category><![CDATA[ChaiCode]]></category><category><![CDATA[Chaiaurcode]]></category><category><![CDATA[functions in js]]></category><category><![CDATA[JavaScript]]></category><dc:creator><![CDATA[Shweta Nigam]]></dc:creator><pubDate>Tue, 10 Mar 2026 05:41:23 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/67aa11e6e2231673d3db79d1/f09945a2-a5fe-4b8d-9c86-b982aef9e1d3.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In this article we'll learn about function declaration, function expression and the difference between them. Before jumping on the topic itself let's understand the function meaning and it's use. Functions are nothing but reusable block of code. We make them to perform repeated work efficiently. It help us follow the important rule of 'DRY' (DO NOT REAPEAT YOURSELF).</p>
<p>If you want to add two numbers, you will probably write it like this:</p>
<pre><code class="language-javascript">let sum1 = 5 + 3;
console.log(sum1);

let sum2 = 10 + 7;
console.log(sum2);
</code></pre>
<p>But if you have to get multiple sum of 2 numbers then the code become redundant and messy which becomes hard to manage.</p>
<p>That is where we write function:</p>
<pre><code class="language-javascript">function add(a, b) {
  return a + b;
}

console.log(add(5, 3));
console.log(add(10, 7));
</code></pre>
<p>Now we can reuse the same function whenever we need to add two numbers.</p>
<h2>Function Declaration</h2>
<p>One common way to create a function is using a function declaration.</p>
<p>Example:</p>
<pre><code class="language-plaintext">function greet() {
  console.log("Hello, welcome to JavaScript!");
}
</code></pre>
<p>To run the function, we simply call it:</p>
<pre><code class="language-plaintext">greet();
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">Hello, welcome to JavaScript!
</code></pre>
<p>Functions can also accept parameters.</p>
<pre><code class="language-plaintext">function greet(name) {
  console.log("Hello " + name);
}

greet("Sam");
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">Hello Sam
</code></pre>
<h2>Function Expression</h2>
<p>Another way to create a function is using a function expression.</p>
<p>Here, the function is stored inside a variable. If you still have doubt about what is a variable then I would recommend you read this <a href="https://aronamic.hashnode.dev/variables-and-data-types-in-javascript">blog</a> first to get the hang of things here.</p>
<p>Example:</p>
<pre><code class="language-plaintext">const greet = function () {
  console.log("Hello from function expression");
};

greet();
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">Hello from function expression
</code></pre>
<p>We can also pass parameters here:</p>
<pre><code class="language-plaintext">const multiply = function (a, b) {
  return a * b;
};

console.log(multiply(4, 5));
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">20
</code></pre>
<h2>Important difference between function declaration and expression</h2>
<ul>
<li><p><strong>Syntax difference</strong></p>
<ul>
<li><p>Function declaration is defined directly using the <code>function</code> keyword.</p>
</li>
<li><p>Function expression stores the function inside a variable.</p>
</li>
</ul>
</li>
<li><p><strong>Hoisting</strong></p>
<ul>
<li><p>Function declarations are hoisted, so they can be called before they are defined.</p>
</li>
<li><p>Function expressions are not hoisted in the same way, so they must be defined before they are called.</p>
</li>
</ul>
</li>
<li><p><strong>Usage</strong></p>
<ul>
<li><p>Function declarations are commonly used for reusable functions in a program.</p>
</li>
<li><p>Function expressions are often used when functions need to be assigned to variables or used as callbacks.</p>
</li>
</ul>
</li>
<li><p><strong>Readability</strong></p>
<ul>
<li><p>Function declarations are usually easier to read in larger programs.</p>
</li>
<li><p>Function expressions provide more flexibility in certain situations.</p>
</li>
</ul>
</li>
</ul>
<h2>Basic Idea of Hoisting</h2>
<p>Hoisting is the behaviour where all the function declaration are moved to the top of their scope.</p>
<p>This means we can call a function declaration before it appears in the code.</p>
<p>Example:</p>
<pre><code class="language-plaintext">sayHello();

function sayHello() {
  console.log("Hello!");
}
</code></pre>
<p>This works because JavaScript internally treats it like:</p>
<pre><code class="language-plaintext">function sayHello() {
  console.log("Hello!");
}

sayHello();
</code></pre>
<p>However, function expressions are not hoisted in the same way, so they must be defined before being used.</p>
<h2>Summary</h2>
<p>Functions are one of the most important concepts in JavaScript. They allow us to group reusable logic into a single block of code and call it whenever needed.</p>
<p>By understanding function declarations, function expressions, and the basic idea of hoisting, we can write cleaner, more organized, and maintainable JavaScript programs.</p>
]]></content:encoded></item><item><title><![CDATA[JavaScript Operators: The Basics You Need to Know]]></title><description><![CDATA[When writing JavaScript programs, we often need to perform operations on values. For example, we might need to add numbers, compare two values, or check multiple conditions before making a decision.
T]]></description><link>https://blog.shwetacodes.pro/javascript-operators-the-basics-you-need-to-know</link><guid isPermaLink="true">https://blog.shwetacodes.pro/javascript-operators-the-basics-you-need-to-know</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Operators]]></category><dc:creator><![CDATA[Shweta Nigam]]></dc:creator><pubDate>Mon, 09 Mar 2026 18:31:34 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/67aa11e6e2231673d3db79d1/8fc5b3f2-379e-4b61-bd52-04074adcb717.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>When writing JavaScript programs, we often need to perform operations on values. For example, we might need to add numbers, compare two values, or check multiple conditions before making a decision.</p>
<p>To perform these tasks, JavaScript provides <strong>operators</strong>. An <strong>operator</strong> is a symbol that performs an operation on one or more values (called operands).</p>
<p>For example:</p>
<pre><code class="language-plaintext">let sum = 5 + 3;
</code></pre>
<p>Here:</p>
<pre><code class="language-plaintext">+   → operator
5,3 → operands
</code></pre>
<p>The operator performs an action on the values.</p>
<h3>Arithmetic Operators</h3>
<p>Arithmetic operators are used to perform mathematical calculations. These are the most basic operators you will encounter in programming.</p>
<p>Example:</p>
<pre><code class="language-plaintext">let a = 10;
let b = 5;

console.log(a + b); 
console.log(a - b);
console.log(a * b);
console.log(a / b);
console.log(a % b);
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">15
5
50
2
0
</code></pre>
<p>The modulus operator <code>%</code> returns the remainder after division.</p>
<p>Example:</p>
<pre><code class="language-plaintext">console.log(7 % 3);
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">1
</code></pre>
<h3>Comparison Operators</h3>
<p>Comparison operators are used to compare two values. They usually return a boolean value (<code>true</code> or <code>false</code>).</p>
<h3>Difference between <code>==</code> and <code>===</code></h3>
<p>This is an important concept in JavaScript.</p>
<p><code>==</code> compares values only.</p>
<pre><code class="language-plaintext">console.log(10 == "10");
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">true
</code></pre>
<p>Because JavaScript converts <code>"10"</code> to a number before comparison.</p>
<p>But <code>===</code> compares both value and type.</p>
<pre><code class="language-plaintext">console.log(10 === "10");
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">false
</code></pre>
<p>Here:</p>
<pre><code class="language-plaintext">10   → number
"10" → string
</code></pre>
<p>Since the types are different, the result is <code>false</code>.</p>
<p>For this reason, most developers usually prefer <code>===</code> over <code>==</code>.</p>
<h3>Logical Operators</h3>
<p>Logical operators are used to combine multiple conditions.</p>
<p>Example:</p>
<pre><code class="language-plaintext">let age = 20;
let hasID = true;

console.log(age &gt; 18 &amp;&amp; hasID);
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">true
</code></pre>
<p>Here both conditions must be true.</p>
<p>Example of <strong>OR operator</strong>:</p>
<pre><code class="language-plaintext">console.log(age &gt; 18 || age &gt; 60);
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">true
</code></pre>
<p>The OR operator returns true if at least one condition is true.</p>
<p>Example of <strong>NOT operator</strong>:</p>
<pre><code class="language-plaintext">console.log(!true);
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">false
</code></pre>
<p>The NOT operator simply reverses the boolean value.</p>
<h3>Assignment Operators</h3>
<p>Assignment operators are used to <strong>assign values to variables</strong>.</p>
<p>The most common assignment operator is:</p>
<pre><code class="language-plaintext">=
</code></pre>
<p>Example:</p>
<pre><code class="language-plaintext">let x = 10;
</code></pre>
<p>JavaScript also provides shorter assignment operators.</p>
<p>Example:</p>
<pre><code class="language-plaintext">let x = 10;

x += 5;
console.log(x);
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">15
</code></pre>
<p>This is equivalent to writing:</p>
<pre><code class="language-plaintext">x = x + 5;
</code></pre>
<p>Another example:</p>
<pre><code class="language-plaintext">let y = 20;

y -= 5;

console.log(y);
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">15
</code></pre>
<hr />
<h3>Summary</h3>
<p>Operators are an essential part of JavaScript programming. They allow us to perform mathematical calculations, compare values, combine conditions, and assign values to variables.</p>
<p>Understanding different types of operators such as <strong>arithmetic operators, comparison operators, logical operators, and assignment operators</strong> helps us write more powerful and expressive programs. As you continue learning JavaScript, you will use operators frequently in conditions, loops, and many other programming scenarios.</p>
]]></content:encoded></item><item><title><![CDATA[JavaScript Arrays 101]]></title><description><![CDATA[In JavaScript, an array is simply a collection of data stored in a single variable. It is hard to impossible to store large amount of data in different variables. And this where array comes in picture]]></description><link>https://blog.shwetacodes.pro/javascript-arrays-101</link><guid isPermaLink="true">https://blog.shwetacodes.pro/javascript-arrays-101</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Array in JavaScript]]></category><dc:creator><![CDATA[Shweta Nigam]]></dc:creator><pubDate>Mon, 09 Mar 2026 18:15:48 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/67aa11e6e2231673d3db79d1/ea2cbeb0-09f4-49f8-8e9a-2a7516b58f84.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In JavaScript, an array is simply a collection of data stored in a single variable. It is hard to impossible to store large amount of data in different variables. And this where array comes in picture. Arrays help us store and manage multiple pieces of data in an organized way.</p>
<h3>Why Do We Need Arrays?</h3>
<p>It is hard and inefficient to store large amounts of related data in different variables.</p>
<p>For example:</p>
<pre><code class="language-plaintext">let fruit1 = "Apple";
let fruit2 = "Banana";
let fruit3 = "Mango";
</code></pre>
<p>This approach becomes difficult to manage when the number of items increases.</p>
<p>Instead, we can use an array:</p>
<pre><code class="language-plaintext">let fruits = ["Apple", "Banana", "Mango"];
</code></pre>
<p>Now all related data is stored inside one variable, which makes the code cleaner and easier to work with.</p>
<h3>Creating an Array</h3>
<p>Arrays are created using square brackets <code>[]</code>.</p>
<p>Example:</p>
<pre><code class="language-plaintext">let fruits = ["Apple", "Banana", "Mango"];
</code></pre>
<p>In this array:</p>
<ul>
<li><p><code>"Apple"</code> is the first element</p>
</li>
<li><p><code>"Banana"</code> is the second element</p>
</li>
<li><p><code>"Mango"</code> is the third element</p>
</li>
</ul>
<p>Arrays can store different types of values as well.</p>
<p>Example:</p>
<pre><code class="language-plaintext">let data = ["Sam", 25, true];
</code></pre>
<h3>Accessing Elements Using Index</h3>
<p>Each value inside an array has a position called an index.</p>
<p>Important thing to remember:</p>
<p><strong>Array indexing starts from 0 in JavaScript.</strong></p>
<p>Example:</p>
<pre><code class="language-plaintext">let fruits = ["Apple", "Banana", "Mango"];

console.log(fruits[0]);
console.log(fruits[1]);
console.log(fruits[2]);
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">Apple
Banana
Mango
</code></pre>
<h3>Updating Elements in an Array</h3>
<p>We can update an element by assigning a new value to its index.</p>
<p>Example:</p>
<pre><code class="language-plaintext">let fruits = ["Apple", "Banana", "Mango"];

fruits[1] = "Orange";

console.log(fruits);
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">["Apple", "Orange", "Mango"]
</code></pre>
<p>Here we changed <code>"Banana"</code> to <code>"Orange"</code>.</p>
<h3>Array Length Property</h3>
<p>JavaScript arrays have a built-in property called length. It tells us how many elements are inside the array.</p>
<p>Example:</p>
<pre><code class="language-plaintext">let fruits = ["Apple", "Banana", "Mango"];

console.log(fruits.length);
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">3
</code></pre>
<p>This means the array contains 3 elements.</p>
<h3>Looping Through an Array</h3>
<p>Very often we need to access all elements of an array. Instead of writing multiple console statements, we can use a loop.</p>
<p>One common way is using a for loop.</p>
<p>Example:</p>
<pre><code class="language-plaintext">let fruits = ["Apple", "Banana", "Mango"];

for (let i = 0; i &lt; fruits.length; i++) {
  console.log(fruits[i]);
}
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">Apple
Banana
Mango
</code></pre>
<p>The loop starts from index <code>0</code> and continues until it reaches the end of the array.</p>
<h3>Real-World Example</h3>
<p>Imagine storing marks of a student.</p>
<pre><code class="language-plaintext">let marks = [75, 80, 92, 68];

console.log(marks[0]); 
console.log(marks[2]);
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">75
92
</code></pre>
<h2>Summary</h2>
<p>Arrays are one of the most commonly used data structures in JavaScript. They allow us to store multiple values in a single variable and access them using indexes. By understanding how to create arrays, access elements, update values, check their length, and loop through them, we can handle collections of data much more efficiently in our programs.</p>
]]></content:encoded></item><item><title><![CDATA[
Understanding Objects in JavaScript]]></title><description><![CDATA[When learning JavaScript, variables help us store individual pieces of data such as numbers, strings, or boolean values. However, real-world data is often more complex and usually consists of multiple]]></description><link>https://blog.shwetacodes.pro/understanding-objects-in-javascript</link><guid isPermaLink="true">https://blog.shwetacodes.pro/understanding-objects-in-javascript</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[objects-in-js]]></category><dc:creator><![CDATA[Shweta Nigam]]></dc:creator><pubDate>Mon, 09 Mar 2026 17:53:22 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/67aa11e6e2231673d3db79d1/3ea3683c-fa25-416c-892a-14c516ecaf30.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>When learning JavaScript, variables help us store individual pieces of data such as numbers, strings, or boolean values. However, real-world data is often more complex and usually consists of multiple related pieces of information. This is where objects become useful.</p>
<h2>What Are Objects and Why Are They Needed?</h2>
<p>An object in JavaScript is a data structure used to store multiple related values in a single variable. These values are stored as key–value pairs.</p>
<p>Think of an object like a real-world entity that has different properties.</p>
<p>For example, if we want to represent a person in our program, we might want to store information like their name, age, and city. Instead of creating multiple variables, we can group them together using an object.</p>
<pre><code class="language-plaintext">const person = {
  name: "Sam",
  age: 29,
  city: "Haryana"
};
</code></pre>
<p>In this example:</p>
<ul>
<li><p><code>name</code>, <code>age</code>, and <code>city</code> are keys (properties)</p>
</li>
<li><p><code>"Sam"</code>, <code>29</code>, and <code>"Haryana"</code> are their values</p>
</li>
</ul>
<p>Objects help us organize related data together, making our code easier to manage and understand.</p>
<hr />
<h2>Creating Objects</h2>
<p>Objects are created using <strong>curly braces</strong> <code>{}</code>.</p>
<pre><code class="language-plaintext">const person = {
  name: "Sam",
  age: 29,
  city: "Haryana"
};
</code></pre>
<p>Each property inside the object is written as:</p>
<pre><code class="language-plaintext">key: value
</code></pre>
<p>Multiple properties are separated using commas.</p>
<hr />
<h2>Accessing Object Properties</h2>
<p>We can access object properties in two ways.</p>
<h3>1. Dot Notation</h3>
<p>The most common way to access object properties is using <strong>dot notation</strong>.</p>
<pre><code class="language-plaintext">console.log(person.name); 
console.log(person.age);
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">sam
29
</code></pre>
<hr />
<h3>2. Bracket Notation</h3>
<p>Another way to access properties is <strong>bracket notation</strong>.</p>
<pre><code class="language-plaintext">console.log(person["city"]);
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">Haryana
</code></pre>
<p>Bracket notation is useful when the property name is dynamic or stored in a variable.</p>
<hr />
<h2>Updating Object Properties</h2>
<p>We can update an object's property by assigning a new value.</p>
<pre><code class="language-plaintext">person.age = 23;

console.log(person.age);
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">23
</code></pre>
<p>Objects allow their properties to be updated easily.</p>
<hr />
<h2>Adding New Properties</h2>
<p>We can also add new properties to an object.</p>
<pre><code class="language-plaintext">person.country = "India";

console.log(person);
</code></pre>
<p>Now the object becomes:</p>
<pre><code class="language-plaintext">{
  name: "Sam",
  age: 23,
  city: "Haryana",
  country: "India"
}
</code></pre>
<hr />
<h2>Deleting Object Properties</h2>
<p>If we want to remove a property from an object, we can use the <code>delete</code> keyword.</p>
<pre><code class="language-plaintext">delete person.city;

console.log(person);
</code></pre>
<p>Now the <code>city</code> property will be removed.</p>
<hr />
<h2>Looping Through Object Keys</h2>
<p>Sometimes we want to access all properties of an object. We can use a <strong>for...in loop</strong> to iterate through the keys.</p>
<pre><code class="language-plaintext">for (let key in person) {
  console.log(key, person[key]);
}
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">name Sam
age 29
country India
</code></pre>
<p>Here:</p>
<ul>
<li><p><code>key</code> represents the property name</p>
</li>
<li><p><code>person[key]</code> gives the value of that property</p>
</li>
</ul>
<hr />
<h2>Difference Between Arrays and Objects</h2>
<p>Example of an array:</p>
<pre><code class="language-plaintext">const fruits = ["apple", "banana", "mango"];
</code></pre>
<p>Example of an object:</p>
<pre><code class="language-plaintext">const person = {
  name: "Sam",
  age: 29
};
</code></pre>
<p>Arrays are used for lists of data, while objects are used for structured data with properties.</p>
<hr />
<p>As a beginner you should start by making object on your own like this:</p>
<p>Create an object representing a student.</p>
<ol>
<li><p>Create an object called <code>student</code>.</p>
</li>
<li><p>Add properties:</p>
<ul>
<li><p><code>name</code></p>
</li>
<li><p><code>age</code></p>
</li>
<li><p><code>course</code></p>
</li>
</ul>
</li>
<li><p>Update one property.</p>
</li>
<li><p>Print all keys and values using a loop.</p>
</li>
</ol>
<p>Example starter code:</p>
<pre><code class="language-plaintext">const student = {
  name: "Rahul",
  age: 20,
  course: "Computer Science"
};

student.age = 21;

for (let key in student) {
  console.log(key, student[key]);
}
</code></pre>
<hr />
<h2>Summary</h2>
<p>Objects are one of the most important data structures in JavaScript. They allow us to store and organize related data using <strong>key–value pairs</strong>. By learning how to create objects, access properties, update them, and loop through them, we can represent real-world data more effectively in our programs.</p>
<p>Understanding objects is an essential step toward writing more structured and maintainable JavaScript code.</p>
]]></content:encoded></item><item><title><![CDATA[Understanding Variables and Data Types in JavaScript]]></title><description><![CDATA[var, let, and const are three keywords you’ll encounter from the very beginning of your JavaScript journey and continue to use throughout. It’s important to understand their differences in order to wr]]></description><link>https://blog.shwetacodes.pro/variables-and-data-types-in-javascript</link><guid isPermaLink="true">https://blog.shwetacodes.pro/variables-and-data-types-in-javascript</guid><category><![CDATA[ChaiCode]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[Data types in javascript]]></category><dc:creator><![CDATA[Shweta Nigam]]></dc:creator><pubDate>Mon, 09 Mar 2026 06:05:49 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/67aa11e6e2231673d3db79d1/38a56b58-ed08-42b6-8256-07512ea72ace.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><code>var</code>, <code>let</code>, and <code>const</code> are three keywords you’ll encounter from the very beginning of your JavaScript journey and continue to use throughout. It’s important to understand their differences in order to write clean, reliable code. All 3 keywords are used to declare variables.</p>
<p>Before jumping into variables themselves, let's understand what does variable mean and why it is needed. Variables are used for storing data. And when you mature as a developer, you will realize that variables are nothing but getting a space in the memory. Primitives data are stored by value whereas non-primitive data are stored as reference (we'll learn more on data types in this article).</p>
<p>Var: It has functional scope. The important thing to note about var is that the values assigned can be re-assigned and same variable can be redeclared which results in lack of control over our code , resulting in bugs and other problems. Therefore in modern projects/products we rarely see the use of var. It is advisable to never use var unless dealing with legacy code.</p>
<pre><code class="language-coffeescript">// declaration
var a;       
// redeclaration allowed
var a = 50;
console.log(a)  // 50
// reassignment is also allowed 
a = 60;
console.log(a)  // 60
</code></pre>
<p>let: It is of block-scope. Variable declared with let keyword can be reassign but can not be redeclared. let be like “ let this variable change its value but don’t let it redeclared).</p>
<pre><code class="language-coffeescript">// declaration
let b;
// redeclaration not allowed
let b = 10;          // SyntaxError: Identifier 'b' has already been declared
// assignment allowed
b = 20;       // ✔️
// reassignment allowed
b = 30 ;        // ✔️
</code></pre>
<p>const: Now if we talk about const it is just like its name (const = constant) . It can neither be re-assigned AND redeclared once it is declared. When we declare a variable with const keyword it is mandatory to initialize it at the time of declaration.</p>
<pre><code class="language-coffeescript">// Initialization at the time of declaration.
const c = 10
// Only declaration of const variable  is not allowed
const d;                         // ❌
// Reassignement is not allowed
c = 20                           // ❌
</code></pre>
<h2><strong>Important Notes About var, const and let</strong></h2>
<ol>
<li><p>Aways use <code>let</code> and <code>const</code> not just over ‘var’ but never use it in the first place.</p>
<ul>
<li><p>Prefer to use <code>const</code> over <code>let</code> unless it is must that value will change.</p>
</li>
<li><p>Using <code>const</code> and <code>let</code> gives you more control over your code.</p>
</li>
</ul>
</li>
<li><p>It is important to understand the concept of hoisting.</p>
<p>Hoisting is the default behaviour of javascript where variable declaration are hoisted on the top.</p>
<p>To understand it more clearly we can use an example to our cause :-</p>
</li>
</ol>
<pre><code class="language-coffeescript">// In case of var 
console.log(x)                  // undefined
var x = 10
</code></pre>
<p>This code is seen by javaScript in this format :</p>
<pre><code class="language-coffeescript">var x; 
console.log(x)
x = 10;
</code></pre>
<p>So here we are accessing variable x before it is initialized resulting in undefined which is the default value for var.</p>
<p>Now before we jump to the <code>let</code> and <code>const</code> examples which gives us our 3rd important point, let’s discuss TDZ in 3 point.</p>
<ol>
<li>TDZ stands for Temporal Dead Zone , in this concept although <code>let</code> and <code>const</code> do get hoisted they stays in TDZ resulting in reference error.</li>
</ol>
<pre><code class="language-coffeescript">console.log(y)       // ReferenceError: Cannot access 'y' before initialization
let y = 10;    

console.log(z)       // ReferenceError: Cannot access 'z' before initialization 
const z = 20;
</code></pre>
<ol>
<li>Scope matters a lot when we deal with these 3 keyword( though not <code>var</code> , it won’t hurt to know more.)</li>
</ol>
<pre><code class="language-coffeescript">{
var a = 10;
let b = 20;
let c = 30;
}
console.log(a);       // 10
console.log(b);       // ReferenceError: b is not defined
console.log(c);       // ReferenceError: c is not defined
</code></pre>
<ol>
<li><code>const</code> does not mean frozen value its just constant binding. In other words if we declare objects and arrays using <code>const</code> variable it does not mean that we can not change the values inside of objects and arrays. It simply means that we cannot redeclare the same variable.</li>
</ol>
<pre><code class="language-coffeescript">// array
const arr = [1,2,3,4,5]
arr.push(6)
console.log(arr) // 1,2,3,4,5,6

// object
const obj = { a:1, b:2, c:3 }
obj.c = 300
console.log(obj)  // { a:1, b:2, c:300 }
</code></pre>
<p><code>const</code> stop us to reassigning the variable not from mutating the object or array.</p>
<img src="https://cdn.hashnode.com/uploads/covers/67aa11e6e2231673d3db79d1/4839d8de-ffe3-497f-8c2a-9c9745e6f18b.png" alt="" style="display:block;margin:0 auto" />

<h2>Primitive Data Types in JavaScript</h2>
<p>In JavaScript, data stored in variables can belong to different data types. The simplest types of data are called primitive data types. These values are stored directly in memory and represent a single value.</p>
<p>JavaScript has several primitive data types, but the most common ones beginners should know are <strong>string, number, boolean, null, and undefined</strong>.</p>
<h3>1. String</h3>
<p>A <strong>string</strong> represents text. Strings are written inside quotes.</p>
<pre><code class="language-plaintext">let name = "Alex";
let language = 'JavaScript';

console.log(name);       // Alex
console.log(language);   // JavaScript
</code></pre>
<p>Strings are commonly used to store things like names, messages, or any textual data.</p>
<hr />
<h3>2. Number</h3>
<p>A <strong>number</strong> represents numeric values. In JavaScript, both integers and decimal numbers are considered numbers.</p>
<pre><code class="language-plaintext">let age = 25;
let price = 99.99;

console.log(age);     // 25
console.log(price);   // 99.99
</code></pre>
<p>Numbers are used for calculations, counts, prices, and other numerical values.</p>
<hr />
<h3>3. Boolean</h3>
<p>A <strong>boolean</strong> represents a logical value that can be either <strong>true</strong> or <strong>false</strong>.</p>
<pre><code class="language-plaintext">let isLoggedIn = true;
let hasPermission = false;

console.log(isLoggedIn);      // true
console.log(hasPermission);   // false
</code></pre>
<p>Booleans are commonly used in conditions and decision-making in programs.</p>
<hr />
<h3>4. Undefined</h3>
<p>When a variable is declared but not assigned a value, JavaScript automatically assigns it the value undefined.</p>
<pre><code class="language-plaintext">let score;

console.log(score);   // undefined
</code></pre>
<p>This simply means that the variable exists, but no value has been given to it yet.</p>
<hr />
<h3>5. Null</h3>
<p>The <strong>null</strong> value represents an <strong>intentional absence of value</strong>. It is used when we want to explicitly indicate that a variable should contain no value.</p>
<pre><code class="language-plaintext">let user = null;

console.log(user);   // null
</code></pre>
<p>Developers often use <code>null</code> when they want to clear a variable or indicate that data is not available yet.</p>
<h2><strong>Summary</strong></h2>
<p>Writing code requires a lots of effort and knowledge therefore resulting in the need of polished knowledge. To know where and which keyword to use to store values inside variables and what will that result in gives us hold on our code. It improves code readability and maintenance.</p>
]]></content:encoded></item><item><title><![CDATA[Control Flow in JavaScript: If, Else, and Switch Explained]]></title><description><![CDATA[We will discuss control flow in JavaScript. Control flow is one of the important behaviour of the language. JavaScript executes code synchronously so controlling the flow of the code is a must.
What c]]></description><link>https://blog.shwetacodes.pro/Control Flow in JavaScript-If, Else, and Switch Explained</link><guid isPermaLink="true">https://blog.shwetacodes.pro/Control Flow in JavaScript-If, Else, and Switch Explained</guid><category><![CDATA[ChaiCode]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[if-else]]></category><category><![CDATA[Switch case]]></category><dc:creator><![CDATA[Shweta Nigam]]></dc:creator><pubDate>Sat, 07 Mar 2026 11:33:12 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/67aa11e6e2231673d3db79d1/48a5d42b-8c6d-4ea7-8ac0-c68e93b01267.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>We will discuss control flow in JavaScript. Control flow is one of the important behaviour of the language. JavaScript executes code synchronously so controlling the flow of the code is a must.</p>
<h2>What control flow means in programming?</h2>
<p>Control flow means the order in which a program executes instructions. By default, JavaScript runs code <em>line by line from top to bottom.</em></p>
<pre><code class="language-javascript">console.log("Start");
console.log("Learning JavaScript");
console.log("End");
</code></pre>
<p>order:</p>
<pre><code class="language-plaintext">Start
Learning JavaScript
End
</code></pre>
<p>But in real programs we need decision making. For example if you are making a weather app and you want to give instructions to take umbrella when it rains or wear sunscreen if temperature is too hot, that's where control flow comes handy.</p>
<p>Simply put in real life:</p>
<ul>
<li><p>If it rains → take umbrella</p>
</li>
<li><p>Else → go outside normally</p>
</li>
</ul>
<p>Programming works the same way.</p>
<p>Control flow lets us decide:</p>
<ul>
<li><p>run some code</p>
</li>
<li><p>skip some code</p>
</li>
<li><p>choose between multiple paths</p>
</li>
</ul>
<p>So <strong>control flow = decision making in code</strong>.</p>
<h2>The <code>if</code> Statement</h2>
<p><code>if</code> runs a block of code only when a condition is true.</p>
<p>Syntax:</p>
<pre><code class="language-plaintext">if (condition) {
  // code runs if condition is true
}
</code></pre>
<p>Example:</p>
<pre><code class="language-plaintext">let age = 18;

if (age &gt;= 18) {
  console.log("You can vote");
}
</code></pre>
<p>How it runs step by step:</p>
<ol>
<li><p>Check condition → <code>age &gt;= 18</code></p>
</li>
<li><p>Is it <code>true</code>?</p>
</li>
<li><p>Yes → run the code</p>
</li>
</ol>
<p>Output:</p>
<pre><code class="language-plaintext">You can vote
</code></pre>
<p>If condition is <strong>false</strong>, the code is skipped.</p>
<h2>The <code>if-else</code> Statement</h2>
<img src="https://cdn.hashnode.com/uploads/covers/67aa11e6e2231673d3db79d1/62694817-1e30-46e3-8b7b-b410e7269550.png" alt="" style="display:block;margin:0 auto" />

<p>Sometimes we want <strong>two possibilities</strong>.</p>
<p>Example:</p>
<ul>
<li><p>If age ≥ 18 → allow voting</p>
</li>
<li><p>Else → not allowed</p>
</li>
</ul>
<p>Syntax:</p>
<pre><code class="language-plaintext">if (condition) {
  // if true
} else {
  // if false
}
</code></pre>
<p>Example:</p>
<pre><code class="language-plaintext">let age = 16;

if (age &gt;= 18) {
  console.log("You can vote");
} else {
  console.log("You cannot vote");
}
</code></pre>
<p>Step by step:</p>
<ol>
<li><p>Check condition</p>
</li>
<li><p>If true → run <code>if</code></p>
</li>
<li><p>If false → run <code>else</code></p>
</li>
</ol>
<p>Output:</p>
<pre><code class="language-plaintext">You cannot vote
</code></pre>
<h2>The <code>else if</code> Ladder</h2>
<p>Sometimes there are <strong>many conditions</strong>, not just two.</p>
<p>Example:</p>
<p>Marks grading system.</p>
<pre><code class="language-plaintext">90+ → Grade A
75+ → Grade B
50+ → Grade C
below → Fail
</code></pre>
<p>Syntax:</p>
<pre><code class="language-plaintext">if (condition1) {
}
else if (condition2) {
}
else if (condition3) {
}
else {
}
</code></pre>
<p>Example:</p>
<pre><code class="language-plaintext">let marks = 82;

if (marks &gt;= 90) {
  console.log("Grade A");
}
else if (marks &gt;= 75) {
  console.log("Grade B");
}
else if (marks &gt;= 50) {
  console.log("Grade C");
}
else {
  console.log("Fail");
}
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">Grade B
</code></pre>
<p>Important rule:</p>
<p>Only <strong>one block runs</strong> — the first true condition.</p>
<h2>The <code>switch</code> Statement</h2>
<p><code>switch</code> is another way to handle <strong>multiple conditions</strong>.</p>
<p>It works well when checking <strong>one value against many options</strong>.</p>
<p>Syntax:</p>
<pre><code class="language-plaintext">switch(value) {
  case option1:
    code
    break;

  case option2:
    code
    break;

  default:
    code
}
</code></pre>
<p>Example: Day of week</p>
<pre><code class="language-plaintext">let day = 2;

switch(day) {
  case 1:
    console.log("Monday");
    break;

  case 2:
    console.log("Tuesday");
    break;

  case 3:
    console.log("Wednesday");
    break;

  default:
    console.log("Invalid day");
}
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">Tuesday
</code></pre>
<h2>Why <code>break</code> is Important</h2>
<p>Without <code>break</code>, JavaScript keeps running the next cases.</p>
<p>Example:</p>
<pre><code class="language-plaintext">let day = 1;

switch(day) {
  case 1:
    console.log("Monday");

  case 2:
    console.log("Tuesday");
}
</code></pre>
<p>Output:</p>
<pre><code class="language-plaintext">Monday
Tuesday
</code></pre>
<p>This is called <strong>fall-through behavior</strong>.</p>
<p>So normally we use:</p>
<pre><code class="language-plaintext">break;
</code></pre>
<p>to stop execution.</p>
<h2>When to Use <code>switch</code> vs <code>if-else</code></h2>
<h3>Use <code>if-else</code> when:</h3>
<p>conditions involve ranges<br />complex logic</p>
<p>Example:</p>
<pre><code class="language-plaintext">if (marks &gt; 90)
</code></pre>
<hr />
<h3>Use <code>switch</code> when:</h3>
<p>comparing <strong>one variable</strong>  </p>
<p>checking <strong>fixed values</strong></p>
<p>Example:</p>
<pre><code class="language-plaintext">day = 1,2,3,4
menu options
user roles
</code></pre>
<p>Example:</p>
<pre><code class="language-plaintext">switch(role)
</code></pre>
<h2>Summary</h2>
<p>Control flow in JavaScript determines how a program decides which code to execute. By default, JavaScript runs code from top to bottom, but real programs require decision-making. Control structures like <code>if</code>, <code>if-else</code>, <code>else if</code>, and <code>switch</code> allow developers to control the flow of execution based on conditions.</p>
<p>The <code>if</code> statement runs code when a condition is true, while <code>if-else</code> handles two possible outcomes. The <code>else if</code> ladder is useful when checking multiple conditions in sequence. The <code>switch</code> statement provides a cleaner way to compare one value against multiple fixed options. When using <code>switch</code>, the <code>break</code> statement is important to prevent unintended execution of other cases.</p>
<p>Understanding when to use <code>if-else</code> or <code>switch</code> helps write clearer and more efficient decision-making logic in JavaScript programs.</p>
]]></content:encoded></item><item><title><![CDATA[Arrow Functions in JavaScript: A Simpler Way to Write Functions]]></title><description><![CDATA[In this article we'll cover arrow functions in simple understanding and examples. Many beginner faces problem with arrow functions and if you are one of those then you do not have to anymore!
Let's fi]]></description><link>https://blog.shwetacodes.pro/arrow-function-in-javascript</link><guid isPermaLink="true">https://blog.shwetacodes.pro/arrow-function-in-javascript</guid><category><![CDATA[ChaiCode]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[learning]]></category><category><![CDATA[ Arrow Functions In JavaScript]]></category><dc:creator><![CDATA[Shweta Nigam]]></dc:creator><pubDate>Sat, 07 Mar 2026 09:47:10 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/67aa11e6e2231673d3db79d1/d5367a8d-05b2-4518-852f-32b72bb49fcf.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In this article we'll cover arrow functions in simple understanding and examples. Many beginner faces problem with arrow functions and if you are one of those then you do not have to anymore!</p>
<p>Let's first understand what is arrow functions and why were they introduced at all.</p>
<h2>What is an arrow function and why use it?</h2>
<p>Arrow function was introduced in ES6 as alternative to normal traditional function with some variations. Simply put together arrow functions are mostly like your normal function, with just simplification in syntax. But it does not mean that they behave exactly same. In other words they are similar but not same, we will discuss more about it in this article later. We use arrow functions for the sake of simplicity in syntax.</p>
<h2>Writing arrow function</h2>
<img src="https://cdn.hashnode.com/uploads/covers/67aa11e6e2231673d3db79d1/727985b7-9172-49cb-a512-da22e9060f47.png" alt="" style="display:block;margin:0 auto" />

<p>We make a normal function like this:</p>
<pre><code class="language-javascript">function sum(a,b){
return a + b
}
</code></pre>
<p>Arrow function of the above traditional functions:</p>
<pre><code class="language-javascript">const sum = (a,b) =&gt; a + b 
</code></pre>
<h2>Understanding simplicity of arrow function syntax</h2>
<p>Below given all syntax are valid</p>
<pre><code class="language-javascript">// traditional anonymous function
(function (a) {
return a * 2
});

// making arrow function from above function
// remove function keyword, add arrow after param
(a) =&gt; { 
return a * 2
}

// making it more simpler 
// remove return keyword (implicit return here)
(a) =&gt; a * 2

// if there is only one param, we can remove the parentheses
a =&gt; a * 2
</code></pre>
<p>As you can see how simpler the syntax of arrow function is compare to traditional function.</p>
<h2>Understanding implicit and explicit return</h2>
<p>In arrow function there is this implicit and explicit return concept understanding this will make you write good arrow functions. Implicit return is where the function automatically return output. Whereas explicit return where you specifically write return keyword.</p>
<pre><code class="language-javascript">// explicit return 
// {} curly braces require return keyword
a =&gt; { return a * 2 }

// implicit return 
// absence of {} curly braces automatically return output 
a =&gt; a * 2  
</code></pre>
<h2>Required parentheses</h2>
<p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters">Rest parameters</a>, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters">default parameters</a>, and <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring">destructuring</a> within params are supported, and always require parentheses:</p>
<pre><code class="language-javascript">(a, b, ...r) =&gt; expression
(a = 400, b = 20, c) =&gt; expression
([a, b] = [10, 20]) =&gt; expression
({ a, b } = { a: 10, b: 20 }) =&gt; expression
</code></pre>
<h2>Syntax</h2>
<p>Now look at these syntax, they are most common arrow function syntax you will come across with:</p>
<pre><code class="language-javascript">() =&gt; expression

param =&gt; expression

(param) =&gt; expression

(param1, paramN) =&gt; expression

() =&gt; {
  statements
}

param =&gt; {
  statements
}

(param1, paramN) =&gt; {
  statements
} 
</code></pre>
<h3>Also understanding statements and expression in arrow function context</h3>
<p>An expression evaluate to a single value whereas statement perform an action and does not as a whole, return a value.</p>
<p>Arrow functions have <strong>two forms</strong>:</p>
<p>1. <strong>Expression body</strong></p>
<p>2. <strong>Statement body</strong></p>
<p>Function with Expression:</p>
<pre><code class="language-javascript">const add = (a, b) =&gt; a + b;
</code></pre>
<p>Here:</p>
<pre><code class="language-plaintext">a + b → expression
</code></pre>
<p>Arrow functions automatically return it.</p>
<p>Equivalent to:</p>
<pre><code class="language-plaintext">const add = (a, b) =&gt; {
  return a + b;
}
</code></pre>
<p>Arrow Function with Statements:</p>
<pre><code class="language-plaintext">const add = (a, b) =&gt; {
  const sum = a + b;
  return sum;
};
</code></pre>
<p>Inside <code>{}</code> you can write <strong>multiple statements</strong>.</p>
<h3>Special Case (Very Important)</h3>
<p>Returning objects.</p>
<p>Wrong:</p>
<pre><code class="language-plaintext">const user = () =&gt; {name: "Alex"}
</code></pre>
<p>JS thinks <code>{}</code> is <strong>statement block</strong>.</p>
<p>Correct:</p>
<pre><code class="language-plaintext">const user = () =&gt; ({name: "Alex"})
</code></pre>
<p>Parentheses force <strong>expression</strong>.</p>
<h2>Difference between arrow function and normal function</h2>
<p>Now we'll understand the difference between arrow function and normal function. These differences exist because arrow function were introduced with deliberate limitations in usage. These are:</p>
<ul>
<li><p>Arrow functions don't have their own <a href="https://developer.mozilla.org/en-US/docs/Glossary/Binding">bindings</a> to <code>this</code>, <code>arguments</code>, or <code>super</code>, and should not be used as <a href="https://developer.mozilla.org/en-US/docs/Glossary/Method">methods</a>.</p>
</li>
<li><p>Arrow functions cannot be used as <a href="https://developer.mozilla.org/en-US/docs/Glossary/Constructor">constructors</a>. Calling them with <code>new</code> throws a <code>TypeError</code>. They also don't have access to the <code>new.target</code> keyword.</p>
</li>
<li><p>Arrow functions cannot use <code>yield</code> within their body and cannot be created as generator functions.</p>
</li>
</ul>
<p>Before getting confused over their limitations let's slowing learn each one with simple understanding.</p>
<p>Between normal function and arrow function the most important difference is of 'this' keyword.</p>
<ol>
<li>Arrow functions <strong>DO NOT HAVE THEIR OWN</strong> <code>this</code>. They <strong>inherit</strong> <code>this</code> <strong>from surrounding scope</strong>.</li>
</ol>
<p>This is called:</p>
<blockquote>
<p><strong>Lexical this</strong></p>
</blockquote>
<p>Normal function and 'this' keyword:</p>
<pre><code class="language-javascript">const obj = {
  name: "Alexa",
  show: function() {
    console.log(this.name);
  }
};

obj.show();
// output: "Alexa"
</code></pre>
<p>Arrow function and 'this' keyword:</p>
<pre><code class="language-javascript">const obj = {
  name: "Alexa",
  show: () =&gt; {
    console.log(this.name);
  }
};

obj.show();
// output: undefined
</code></pre>
<p>Because arrow function does not bind <code>this</code>. It takes <code>this</code> from outer scope.</p>
<p>2. Arrow Functions do not have their <code>arguments</code> they inherit it from their parent.</p>
<p>Normal function and argument:</p>
<pre><code class="language-javascript">function test(){
  console.log(arguments)
}
// works
</code></pre>
<p>Arrow function and argument:</p>
<pre><code class="language-javascript">const test = () =&gt; {
  console.log(arguments);
}
// does not work
//only works if a parent function has arguments.
</code></pre>
<p>3. Arrow Functions Cannot Be Constructors</p>
<p>Normal function:</p>
<pre><code class="language-plaintext">function Person(name){
  this.name = name;
}

const p = new Person("Alex");
</code></pre>
<p>Works.</p>
<hr />
<p>Arrow function:</p>
<pre><code class="language-plaintext">const Person = (name) =&gt; {
  this.name = name;
}

new Person("Alex");
</code></pre>
<p>Error</p>
<pre><code class="language-plaintext">Person is not a constructor
</code></pre>
<p>4. Arrow Functions Do NOT Have <code>prototype</code></p>
<p>Normal function:</p>
<pre><code class="language-plaintext">function test(){}

console.log(test.prototype);
</code></pre>
<p>Exists.</p>
<hr />
<p>Arrow function:</p>
<pre><code class="language-plaintext">const test = () =&gt; {};

console.log(test.prototype);
</code></pre>
<pre><code class="language-plaintext">undefined
</code></pre>
<p>5. Arrow Functions Cannot Use <code>super</code> or <code>new.target</code></p>
<p>Arrow functions still create an execution context but they do not create their own <code>this</code>, <code>arguments</code>, <code>super</code>, or <code>new.target</code>. Remember that : <strong>4 No's of Arrow Functions</strong></p>
<pre><code class="language-plaintext">Arrow functions do not have their own:
this
arguments
prototype
super
new.target
</code></pre>
<p>They borrow from <strong>parent scope</strong>.</p>
<p>6. Arrow functions also cannot be <strong>generators:</strong></p>
<pre><code class="language-plaintext">const test = *() =&gt; {} // invalid
</code></pre>
<p>Generators require normal functions.</p>
<h2>Conclusion</h2>
<p>Arrow functions were introduced in ES6 as a shorter way to write functions in JavaScript. They allow cleaner syntax and support both implicit and explicit return. Unlike normal functions, arrow functions do not create their own <code>this</code> or <code>arguments</code>; instead they inherit them from the surrounding scope (lexical binding). They also cannot be used as constructors and do not have a <code>prototype</code>. Arrow functions are best used for short functions and callbacks, but normal functions are usually better for object methods and constructors.</p>
]]></content:encoded></item></channel></rss>