<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Anshul tripathi on Medium]]></title>
        <description><![CDATA[Stories by Anshul tripathi on Medium]]></description>
        <link>https://medium.com/@anshultrip1234?source=rss-ebcb3975b6e4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*FNNlrDNwcIU8QYTRCEBo4A.jpeg</url>
            <title>Stories by Anshul tripathi on Medium</title>
            <link>https://medium.com/@anshultrip1234?source=rss-ebcb3975b6e4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 10:11:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@anshultrip1234/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Understanding the this Keyword in JavaScript]]></title>
            <link>https://medium.com/@anshultrip1234/understanding-the-this-keyword-in-javascript-65c78d3aa7a7?source=rss-ebcb3975b6e4------2</link>
            <guid isPermaLink="false">https://medium.com/p/65c78d3aa7a7</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Anshul tripathi]]></dc:creator>
            <pubDate>Wed, 18 Nov 2026 18:57:07 GMT</pubDate>
            <atom:updated>2026-11-18T18:57:07.983Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6xEKK0D_N3aaD2FsZdZvOQ.png" /></figure><h3>1. Introduction</h3><p>In JS , the this keyword in one of the most interesting yet confusing concepts , especially when you’re starting to explore how JS works behind the scenes . Unlike variables , whose values are determined by where they are declared , the value of this depends on how a function is called . It can refer to different objects in different situations , which makes understanding its behaviour quite tricky .</p><p>In this blog , we’ll break down the this keyword from the basics , understand how its value changes in different execution contexts and explore how it. behaves inside regular functions , arrow functions , arrow functions objects and constructors . We’ll also look at practical examples to understand what’s happening behind the scenes rather than simply memorising rules .</p><h3>2 . What this represents</h3><p>In Js the this keyword refers to the context in which the current code is executing . Unlike many other programming languages where this always points to the instance of a class , the value of this in JS is dynamic . It is determined entirely at runtime by how a function is called ( the call-site) not where the function is defined !!!</p><p>The 4 main rule of this :</p><p>To figure out what this points to look , at how the function is invoked , JS follows these rules , ordered from lowest to highest priority .</p><ol><li>Default Binding ( global Context / Standalone functions ) <br>If you use this outside of any function , or inside a regular function that is called standalone ( e.g foo() ) , it defaults to the global context .</li></ol><ul><li>In a browser : this refers to the window object .</li><li>In Strict Mode ( use strict ) : this inside a function will be undefined .</li></ul><pre>function showContext() {<br>  console.log(this); <br>}<br><br>showContext(); // Logs the Window object (or undefined in strict mode)<br></pre><p>2 . Implicit Binding ( Object Methods ) : When a function is called as a method of an object ( e.g obj.method() , this points to the object immediately to the left of the dot .</p><pre>const user = {<br>  name: &quot;Alice&quot;,<br>  greet() {<br>    console.log(`Hello, my name is ${this.name}`);<br>  }<br>};<br><br>user.greet(); // Logs: &quot;Hello, my name is Alice&quot; (this = user)</pre><h3>3 . This in global Context</h3><p>In the global context (outside of any function or class ) , this refers to the global object ( globalThis ) , regardless of whether strict mode is enabled , However the exact object or value it points to depends on your JS runtime environment and how the file is loaded .</p><p>Key Behaviour to know :</p><ul><li>Standard Browser Scripts : Outside of any function , this points to the window object , even when use strict is declared at the top of the file .</li></ul><pre>&quot;use strict&quot;;<br>console.log(this === window); // true<br><br>this.appName = &quot;MyApp&quot;;<br>console.log(window.appName); // &quot;MyApp&quot;</pre><ul><li>ES Modules : Modern JS modules enforce strict scoping and do not expose a global this at the top level .</li></ul><pre>&lt;script type=&quot;module&quot;&gt;<br>  console.log(this); // undefined<br>&lt;/script&gt;</pre><ul><li>Arrow functions in Global Scope : Arrow functions do not create their own this binding and instead inherit this from their surroundings lexical scope. When defined in the global scope , an arrow function always binds to globalThis .</li></ul><pre>const checkGlobal = () =&gt; this;<br>console.log(checkGlobal() === globalThis); // true</pre><ul><li>Best Practices (globalThis) : Because this varies between window , global , self and undefined depending on where your code runs , use the standardised globalThis property whenever you reliably need the global object across all environments .</li></ul><h3>4. this inside objects</h3><p>In JS , the value of this inside an object depends on how a function is called , rather than where it is written . Object literals ( {} ) themselves do not create their own this scope .</p><ul><li>Inside a Regular Object methods : When you call a regular function as a method of an object , this refers to the object before the dot . This allows methods to read and modify other properties on the same object.</li></ul><pre>const user = {<br>  name: &quot;Aarav&quot;,<br>  greet() {<br>    console.log(`Hello, ${this.name}`);<br>  }<br>};<br><br>user.greet(); // Output: &quot;Hello, Aarav&quot; (`this` is `user`)</pre><ul><li>Directly Inside Object Properties : Because object literals do not create a new execution scope , using this directly as a property value pulls this from the outer scope . One point of agreement among developers is that this inside an object literal refers to the calling context-such as the global window object-rather than the object being defined .</li></ul><pre>const obj = {<br>  currentContext: this // Refers to window / globalThis, NOT `obj`<br>};</pre><ul><li>Inside Nested Objects : When an object contains another objects , this inside a nested method refers only to the immediate parent object before the dot .</li></ul><pre>const company = {<br>  name: &quot;TechCorp&quot;,<br>  department: {<br>    name: &quot;Engineering&quot;,<br>    getDeptName() {<br>      return this.name; // Refers to `department`, not `company`<br>    }<br>  }<br>};<br><br>console.log(company.department.getDeptName()); // Output: &quot;Engineering&quot;</pre><h3>5 . this inside functions</h3><p>In JS , the value of this inside a function depends on how the function is called (invoked ) , rather than where or how it is defined .</p><p>The only exception is an arrow function , which does not bind its own this and instead inherits it from its surrounding scope .</p><p>1 . Regular ( Standalone ) Function Call : When you call a standard function directly without attaching it to an object , this defaults to the global execution context .</p><ul><li>Non-strict mode : this refers to the global object ( window in browsers, global in Node.js or globalThis ) .</li><li>Strict mode : ( use strict ) . this is undefined .</li></ul><pre>function showThis() {<br>  console.log(this);<br>}<br><br>showThis(); // Window (in browser) or undefined (in strict mode)</pre><p>2 . Object Method Call : When a function is stored as a property of an object and called using dot notation ( obj.method() ) , this points to the object before the dot .</p><pre>const user = {<br>  name: &quot;Alex&quot;,<br>  greet() {<br>    console.log(this.name);<br>  }<br>};<br><br>user.greet(); // &quot;Alex&quot; (this === user)</pre><p>3 . Arrow Functions : Arrow functions ( () =&gt; {} ) do not create their own this binding. Instead , they capture the this value from the enclosing lexical scope ( the surrounding code where the arrow function was created)</p><pre>const team = {<br>  name: &quot;Developers&quot;,<br>  members: [&quot;Sam&quot;, &quot;Taylor&quot;],<br>  listMembers() {<br>    // &#39;this&#39; here is the &#39;team&#39; object<br>    this.members.forEach((member) =&gt; {<br>      // Arrow function inherits &#39;this&#39; from listMembers()<br>      console.log(`${member} is on ${this.name}`);<br>    });<br>  }<br>};<br><br>team.listMembers(); // &quot;Sam is on Developers&quot;, &quot;Taylor is on Developers&quot;</pre><p>4 . Constructor Function ( new Keyword ) : When you invoke a function using the new keyword , JS creates a brand-new empty object and sets this to point to that newly created instance .</p><pre>function Car(make) {<br>  this.make = make;<br>}<br><br>const myCar = new Car(&quot;Toyota&quot;);<br>console.log(myCar.make); // &quot;Toyota&quot;</pre><p>6 . DOM Event Handlers : When a regular function is used as an event listener on a DOM element , this refers to the HTML element that received the event .</p><pre>button.addEventListener(&quot;click&quot;, function() {<br>  console.log(this); // The &lt;button&gt; element<br>});</pre><h3>6 . How calling context changes this</h3><p>In JS , the value of this inside a function depends on how the function is called (invoked) rather than where or how it is defined . The only exception is an arrow function , which does not bind its own this and instead inherits it from its surroundings scope .</p><p>1 . Regular ( Standalone ) Function Call</p><p>When you call a standard function directly without attaching it to an object, this defaults to the global execution context .</p><ul><li>Non-strict mode : this refers to the global object ( window in browsers , global in Node.js or globalThis )</li><li>Strict mode ( “use strict”) . this is undefined .</li></ul><pre>function showThis() {<br>  console.log(this);<br>}<br><br>showThis(); // Window (in browser) or undefined (in strict mode)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uuHbcNiD5RsdwpzAnnMZ_A.png" /><figcaption>comparison table</figcaption></figure><h3>7. Conclusion</h3><p>The this keyword in JavaScript becomes much easier to understand when we focus on how a function is called rather than where it is defined. Understanding its behaviour across different contexts helps us write better code and understand JavaScript more deeply.</p><p>Don’t just memorise the rules; experiment with them, break things, and see what happens.</p><p><strong>Keep building and keep exploring !!!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=65c78d3aa7a7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The new Keyword in JavaScript]]></title>
            <link>https://medium.com/@anshultrip1234/the-new-keyword-in-javascript-3b23d96005bc?source=rss-ebcb3975b6e4------2</link>
            <guid isPermaLink="false">https://medium.com/p/3b23d96005bc</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[agentic-ai]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Anshul tripathi]]></dc:creator>
            <pubDate>Wed, 21 Oct 2026 08:36:15 GMT</pubDate>
            <atom:updated>2026-10-21T08:36:15.312Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C2NyVVgUKQRey1emdJtOnA.png" /></figure><h3>1. Introduction</h3><p>Have you ever wondered what actually happens behind the scenes when you use the new keyword in JS ? How does it create an object , connect it to a constructor function , and make this work the way it does ?</p><p>The new keyword is the fundamental concept for the JS oops , It allows us to create new objects from constructor functions or classes while automatically handling several important steps behind the scenes .</p><p>In this blog we’ll break down how the new keyword works , explore what happens behind the scenes and understand it with simple code eg .</p><h3>2 . What the new keyword does</h3><p>In Js the new keyword is used to create an instance of a user-defined object type or a class , When you put new before a function call or class constructor , it triggers four sequential operations behind the scenes .</p><p>What happens under the hood :</p><ul><li>creates a brand-new , empty object .</li><li>Links the prototype : it sets the internal of this new object to point to the constructor function’s prototype object , establishing the inheritance chain .</li><li>Binds this : it executes the constructor function , binding the this keyword to the newly created object so you can assign properties and methods to it .</li><li>Return the object : It automatically returns the new object , unless the function explicitly returns a different non-primitive object .</li></ul><pre>function User(name) {<br>  this.name = name; // &#39;this&#39; points to the newly created object<br>}<br><br>// Adding a method to the prototype so all instances can access it<br>User.prototype.sayHi = function() {<br>  console.log(`Hi, I&#39;m ${this.name}`);<br>};<br><br>// Calling the function with the &#39;new&#39; keyword<br>const user1 = new User(&quot;Alice&quot;);<br><br>console.log(user1.name); // Output: &quot;Alice&quot;<br>user1.sayHi();           // Output: &quot;Hi, I&#39;m Alice&quot;</pre><h3>3 . Constructor functions</h3><p>A constructor function in JS is a special function used as a blueprint to create and initialise multiple objects with a similar structure , properties and behaviours . It acts similarly to classes in other object-oriented languages , while modern Js often uses the class syntax , constructor functions are the foundational mechanism underneath them .</p><p>Key Characteristics :</p><ul><li>Naming conventions : By convention , the function name starts with a capital letter (e.g Person instead of person ) to distinguish it from regular functions .</li><li>The new keyword : It must be called using the new operator .</li><li>The this keyword : Inside the function , this refers to the newly created, empty object instance .</li><li>No Explicit return : You do not need to use return . Js automatically returns the newly created object at the end of the execution .</li></ul><pre>// 1. Define the constructor function<br>function User(name, age) {<br>  // &quot;this&quot; points to the new empty object being created<br>  this.name = name;<br>  this.age = age;<br>  <br>  this.sayHello = function() {<br>    console.log(`Hello, my name is ${this.name}!`);<br>  };<br>}<br><br>// 2. Create unique object instances using the &#39;new&#39; keyword<br>const user1 = new User(&quot;Alice&quot;, 25);<br>const user2 = new User(&quot;Bob&quot;, 30);<br><br>user1.sayHello(); // Output: Hello, my name is Alice!<br>console.log(user2.age); // Output: 30</pre><h3>4 . Object creation Process</h3><p>The new keyword governs the object creation process when invoking a constructor function or ES6 class constructor .</p><p>When you call new Constructor() , JS executes four steps behind the scene to create and initialise the new object .</p><pre>// 1. A new plain JavaScript object is created.<br>// 2. The object&#39;s internal [[Prototype]] is linked to the constructor&#39;s prototype.<br>// 3. The `this` context is bound to this new object, and the constructor code runs.<br>// 4. The new object is automatically returned (unless a different object is explicitly returned).</pre><p><strong>Step-by-step breakdown</strong></p><p><strong>1 . A brand new object is created</strong>: Js allocates memory for a fresh , empty object .</p><ul><li>Conceptually : const newObj = {}</li></ul><p><strong>2 . The prototype is linked</strong> : The new object’s internal prototype (_proto_) is set to point to the constructor function’s .prototype object . This establishes the inheritance chain , giving the new object access to any shared methods defined on the constructor’s prototype .</p><ul><li>Conceptually : Object.setPrototypeOf(newObj , Constructor.prototype);</li></ul><p><strong>3 .</strong> <strong>this is bound and the function executes</strong> : The execution context binds the this keyword to the newly created object newObj . The code inside the constructor function then runs dynamically adding properties and method onto this based on the passed arguments .</p><ul><li>Conceptually : Constructor.call(newObj , ...args);</li></ul><p><strong>4 </strong>. <strong>The object is returned</strong> : If the constructor function does not explicitly return a non-primitive value ( like another object ) , JS automatically returns the newly created object .</p><ul><li>Note : If you explicitly return someOtherObject; that specific object will be returned instead , discarding the one just created .</li></ul><h3>5 . How the new links the prototype</h3><p>When you call a function with new, JavaScript does four things behind the scenes, and the prototype linking happens in the first one.</p><ol><li><strong>A new empty object is created</strong>, and its internal [[Prototype]] slot is set to the constructor’s prototype property. So if you call new Dog(), the new object’s hidden prototype link points to Dog.prototype.</li><li><strong>The constructor runs with </strong><strong>this bound to that new object</strong>, so this.name = ... writes properties onto it.</li><li><strong>The object is returned automatically</strong>, unless the constructor explicitly returns a different object (returning a primitive is ignored).</li></ol><pre>function Dog(name) {<br>  this.name = name;<br>}<br>Dog.prototype.bark = function () {<br>  return `${this.name} says woof`;<br>};<br><br>const d = new Dog(&quot;Rex&quot;);<br><br>Object.getPrototypeOf(d) === Dog.prototype; // true<br>d.bark(); // &quot;Rex says woof&quot; (found via the prototype, not on d itself)<br>d.hasOwnProperty(&quot;bark&quot;); // false</pre><p>When you access d.bark, the engine doesn’t find it on d, so it follows the [[Prototype]] link to Dog.prototype, finds it there, and calls it with this set to d. If it weren’t there either, lookup would continue to Object.prototype, and then to null, where it stops and returns undefined.</p><p>A handy way to understand it is to write new yourself:</p><pre>function myNew(Constructor, ...args) {<br>  const obj = Object.create(Constructor.prototype); // the prototype link<br>  const result = Constructor.apply(obj, args);      // run constructor with this = obj<br>  return (result !== null &amp;&amp; typeof result === &quot;object&quot;) || typeof result === &quot;function&quot;<br>    ? result<br>    : obj;<br>}<br><br>const d2 = myNew(Dog, &quot;Fido&quot;);<br>d2.bark(); // &quot;Fido says woof&quot;</pre><p>Object.create(proto) is the key line. It makes an object whose [[Prototype]] is proto, which is exactly what newdoes in its first step.</p><p>A couple of related points that often cause confusion. Dog.prototype is not Dog’s own prototype. It’s the object that will <em>become</em> the prototype of instances. Dog’s own prototype is Function.prototype. The non-standard __proto__ accessor exposes the same hidden link, so d.__proto__ === Dog.prototype, but Object.getPrototypeOf is the preferred way to read it. Also, ES6 class syntax uses this same mechanism. Methods defined in a class body go on ClassName.prototype, and new links instances to it in the same way.</p><h3>7. Conclusion</h3><p>The new keyword in JavaScript is more than just a way to create objects. It plays an important role in object-oriented programming (OOP) by creating new instances, connecting them to their constructor&#39;s prototype, binding this to the newly created object, and returning the appropriate result.</p><p>Understanding what happens behind the scenes makes concepts like constructor functions, prototypes, inheritance, and classes much easier to understand. Instead of simply using new, you now know the mechanism that makes it work.</p><p>Remember, the best way to master JavaScript is not just to learn the syntax but to understand the logic behind it. Keep experimenting with constructor functions, explore prototypes, and try implementing your own version of the new operator to strengthen your understanding.</p><p>Till then, keep exploring, keep building, and keep practicing!!!!!</p><p>Please share your Feedback !!!!</p><p>Thank you 😀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3b23d96005bc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Object Oriented Programming in Js]]></title>
            <link>https://medium.com/@anshultrip1234/understanding-object-oriented-programming-in-js-46e33c1d0184?source=rss-ebcb3975b6e4------2</link>
            <guid isPermaLink="false">https://medium.com/p/46e33c1d0184</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[object-oriented]]></category>
            <dc:creator><![CDATA[Anshul tripathi]]></dc:creator>
            <pubDate>Tue, 20 Oct 2026 06:41:40 GMT</pubDate>
            <atom:updated>2026-10-20T06:41:40.594Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lAjbeF4bY8NOXIk-Jbb98w.png" /></figure><h3>Introduction</h3><p>Js is more than just a language used to make website interactive , As applications grow in size and complexity , writing clean , reusable and maintainable code become increasingly important . This is where Object-Oriented Programming ( OOP ) comes into the picture .</p><p>OOPs is a programming paradigm that organises code around object rather than just functions and logic , It allows us to combine data and the behaviour associated with that data into a single unit , making our code easier to structure , understand and reuse .</p><p>In this blog , we will be exploring how OOP works in JS , starting with objects and prototypes and gradually moving towards concepts such as classes , constructors , inheritance , encapsulation and polymorphism , Rather than simply memorizing definitions , we will focus on understanding what happens behind the scenes and how these concepts help us write better code .</p><h3>2 . What Object-Oriented Programming (OOPs) means</h3><p>OOPs in Js is a programming paradigm that organises software design around objects- which contain data (properties) and code ( methods ) -rather than just functions and logic .</p><p>While JS is a Multi-paradigm language (meaning you can also write it using functional or procedural styles ) , it heavily supports OOP .</p><p>There are two ways JS handles OOP</p><ul><li><strong>Prototypes ( The core Engine ) </strong>: Js is natively a prototype-based language . This means objects directly inherit properties and behaviour from other objects hidden ‘prototype’ link , rather than using rigid classes .</li><li><strong>Classes ( The modern Wrapper )</strong> : In 2015 ( ES6 ) , JS introduced the class keyword . This is ‘syntactic sugar’-it doesn&#39;t change how JS works under the hood , but it provides a clean , familiar syntax for developers coming from other languages .</li></ul><h3>3 . Real-World analogy. ( blueprint → objects )</h3><p>OOPs in Js can be understood using the real-world analogy of a Car Factory and its Cars .</p><ul><li><strong>Class ( The Blueprint </strong>) : Think of the architectural design or blueprint of a car . It is not wheels , an engine and a steering wheel ) and capabilities in js a class defines this structure .</li><li><strong>Object / Instance ( The physical Car )</strong> : think of the actual , physicals cars rolled off the assembly line . You can make hundreds of unique cars from the same blueprint and each is an “object” .</li><li><strong>Properties ( State / Data )</strong> : think of what specific characteristics of a single car , such as its Color (red) , speed ( 120km/hr) , or fuel level , In Js these are object variables .</li><li><strong>Methods ( Behaviour / Action )</strong> : Think of what the car can actually do , such as accelerate() , brake() , or honk() . In Js these are functions attached to the object ,</li><li><strong>Encapsulation ( The Dashboard / Hood )</strong> : Think of the car’s engine compartment. You do not need to manually pull spark plugs or inject fuel to make it move; you just press the gas pedal. The complex inner workings are hidden safely inside the car’s “capsule,” and you only interact with a simple interface. In JavaScript, this means hiding private data (like #fuelLevel) and exposing only safe .</li></ul><h3>4 . What is a class In Js</h3><p>In Js , a class is blueprint or template for creating objects , Introduction in ES6 , classes allow you to bundle data ( properties ) and behaviour (methods) together in a clean , organised structure .</p><p>However ,under the hood a JS class is actually syntactic sugar over the language’s existing prototype-based inheritance . In fact , if you check the type of a class using typeof MyClass , it returns &quot;function” , This is syntax simply provides a cleaner , more familiar way to write constructor functions and manages prototypes , mimicking the behaviour of languages like C++ .</p><p>A basic class consists of the class keyword an optional constructor method to initialise properties and any custom methods .</p><pre>class User {<br>  // 1. The constructor initializes properties when an object is created<br>  constructor(name, role) {<br>    this.name = name; // Instance property<br>    this.role = role; // Instance property<br>  }<br><br>  // 2. Class method<br>  sayHello() {<br>    return `Hello, my name is ${this.name} and I am a ${this.role}.`;<br>  }<br>}<br><br>// Instantiating (creating) an object from the class<br>const user1 = new User(&quot;Alice&quot;, &quot;Developer&quot;);<br>console.log(user1.sayHello()); // Output: Hello, my name is Alice and I am a Developer.</pre><h3>5 . Creating Objects using classes</h3><p>To create an object using a class in JS , you define the blueprint using the class keyword and instantiate it using the new operator , This approach provides a structured template for generating multiple objects with similar properties and behaviour .</p><pre>// 1. Define the class template<br>class User {<br>  // The constructor initializes the object&#39;s properties<br>  constructor(name, role) {<br>    this.name = name; // &#39;this&#39; refers to the new object being created<br>    this.role = role;<br>  }<br><br>  // Define a method (behavior) shared by all instances<br>  sayHello() {<br>    console.log(`Hello, my name is ${this.name} and I am a ${this.role}.`);<br>  }<br>}<br><br>// 2. Create objects (instances) using the &#39;new&#39; keyword<br>const user1 = new User(&quot;Alice&quot;, &quot;Admin&quot;);<br>const user2 = new User(&quot;Bob&quot;, &quot;Developer&quot;);<br><br>// 3. Access properties and call methods<br>console.log(user1.name); // Output: Alice<br>user2.sayHello();        // Output: Hello, my name is Bob and I am a Developer.</pre><p>Key components to know-</p><ul><li><strong>Class keyword</strong> : Used to declare a class , by convention class names start with a capital letter ( PascalCase ) .</li><li><strong>constructor ()</strong> : A special , mandatory function that runs automatically whenever new is called , It sets up the starting values for the object’s properties , you can only have one constructor per class .</li><li><strong>this keyword</strong> : Inside the class definition this points directly to the specific object instance that is currently being created or used .</li><li><strong>new Operator</strong> : You must use the new operator to instantiate a class , Attempting to call a class like a normal function ( e.g User() will throw a TypeError .</li></ul><h3>6 . Constructor Method</h3><p>The constructor method in Js is a special method used to create and initialise objects , It runs automatically when you instantiate a class using a new keyword .</p><p>Depending on your implementation context , Js handles constructor through either modern classes or legacy constructor functions .</p><ul><li><strong>Modern Syntax : ES6 classes</strong> : In modern Js , the constructor is explicitly defined inside a class block . A class can only have one constructor method .</li></ul><pre>class User {<br>  // The constructor initializes properties<br>  constructor(name, role) {<br>    this.name = name;       // &quot;this&quot; points to the new object being created<br>    this.role = role;<br>  }<br><br>  // A standard method on the class<br>  sayHello() {<br>    console.log(`Hello, my name is ${this.name}.`);<br>  }<br>}<br><br>// Instantiating objects using the &#39;new&#39; keyword<br>const user1 = new User(&quot;Alice&quot;, &quot;Admin&quot;);<br>const user2 = new User(&quot;Bob&quot;, &quot;Editor&quot;);<br><br>user1.sayHello(); // Output: Hello, my name is Alice.</pre><p>Key rules for class constructors :</p><ul><li>Default Constructor : If you do not explicitly write a constructor() , JS automatically inserts an empty default one for you ( constructor() {} ).</li><li>Inheritance ( super ) : If a class extends a parent class , you must call super() inside the constructor before accessing this .</li></ul><pre>class Admin extends User {<br>  constructor(name, permissions) {<br>    super(name, &quot;Admin&quot;); // Calls the parent class constructor<br>    this.permissions = permissions;<br>  }<br>}</pre><p>2 . <strong>Traditional Syntax : Constructor Functions</strong></p><p>Before ES6 classes were introduced , Js used regular functions acting as constructors . By convention , these functions start with a capital letter to differentiate them from standard functions .</p><pre>function Car(make, model) {<br>  // JavaScript implicitly creates an empty object: this = {};<br>  <br>  this.make = make;<br>  this.model = model;<br>  <br>  // JavaScript implicitly returns &#39;this&#39; at the end<br>}<br><br>const myCar = new Car(&quot;Toyota&quot;, &quot;Corolla&quot;);</pre><p><strong>What happens behind the scenes -:</strong></p><p>when you call a constructor with the new keyword , Js executes four steps implicitly .</p><ol><li>It creates a brand-new , empty object ( {} ) .</li><li>It binds this inside the constructor code to point to that new object .</li><li>It executes the constructor code (setting up properties like this.name = name ).</li><li>It automatically returns the newly created object ( unless you explicitly return a different object ).</li></ol><h3>7 . Methods inside a class</h3><p>In Js classes , methods are functions defined inside a class that dictate the behaviour of its objects . By default , standard methods are attached to the class’s prototype and shared across all instances to save memory ,</p><p>You can categorise methods inside a JS class into five main types :</p><ol><li><strong>The constructor Method</strong> : The constructor() is a special initialisation method , It runs automatically when you create a new object using the new keyword , and it is typically used to set up instance properties using this .</li></ol><pre>class User {<br>  constructor(name) {<br>    this.name = name; // Sets an instance property<br>  }<br>}</pre><p><strong>2 . Instance Methods ( Prototype Methods )</strong> : These are standard actions available to any object instantiated from the class . They can access object data using the this keyword . You declare them using a shorthand syntax without the function keyword .</p><pre>class User {<br>  constructor(name) {<br>    this.name = name;<br>  }<br><br>  // Instance method<br>  sayHello() {<br>    return `Hello, my name is ${this.name}!`;<br>  }<br>}<br><br>const bob = new User(&quot;Bob&quot;);<br>console.log(bob.sayHello()); // &quot;Hello, my name is Bob!&quot;</pre><p><strong>3 . Static method</strong> : It belong directly to the class itself , rather than to instances of the class . You define them using the static keyword , They are often used as utility functions or factory mehtods .</p><pre>class User {<br>  // Static method<br>  static clearSession() {<br>    return &quot;All user sessions cleared.&quot;;<br>  }<br>}<br><br>// Called directly on the class, not the instance<br>console.log(User.clearSession());</pre><p><strong>4 . Getters and Setters </strong>: It look like methods but behave like properties . They are prefixed with the get and set keywords and allow you to execute logic behind the scenes when a property is read or updated .</p><pre>class User {<br>  constructor(name) {<br>    this._name = name;<br>  }<br><br>  // Getter<br>  get name() {<br>    return this._name.toUpperCase();<br>  }<br><br>  // Setter<br>  set name(newName) {<br>    if (newName.length &gt; 0) this._name = newName;<br>  }<br>}<br><br>const bob = new User(&quot;Bob&quot;);<br>console.log(bob.name); // BOOB (calls the getter)<br>bob.name = &quot;Robert&quot;;   // Calls the setter</pre><p><strong>5 . Private Methods</strong> : To prevents external code from calling a method , you can make it private by prefixing its name with a hashtag ( # ). Private methods can only be invoked from within other methods of the same class.</p><pre>class User {<br>  #validateToken() {<br>    return true; // Secret internal logic<br>  }<br><br>  logIn() {<br>    if (this.#validateToken()) {<br>      console.log(&quot;Logged in successfully!&quot;);<br>    }<br>  }<br>}</pre><p><strong>Comparison -:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Llv9AI4SpZR-MNNI0TvUHQ.png" /><figcaption>comparison between different methods</figcaption></figure><h3>8 . Basic idea of encapsulation :</h3><p>It is the practice of building data ( properties ) and methods (functions ) into a single unit while restricting direct access to some of the object’s internal details .</p><p>Think of it like a capsule or a black box , the outside world interacts only with a clean, public interface ,while the messy internal logic and sensitive data stay hidden safely inside .</p><p><strong>Why do we need it -:</strong></p><p>Without encapsulation , any part of your codebase can accidentally modify you data , leading to unexpected bugs .</p><ul><li><strong>Data Protection</strong> : It prevents external code from setting invalid values ( e.g setting a user’s age to -5 ) .</li><li><strong>Maintainability</strong> : You can completely change the interval mechanics of your object later without breaking the rest of your app .</li></ul><p>Js didn’t have traditional access modifiers like private or public . Today , there are two primary way to enforce strict encapsulation .</p><ol><li><strong>The modern way</strong> : Private Class fields ( # ) : Introduced in modern JS prefixing a property or method with a # symbol makes it truly private . It cannot be accessed outside the class bounds .</li></ol><pre>class BankAccount {<br>  // Private field (cannot be read/written directly from outside)<br>  #balance = 0; <br><br>  constructor(owner) {<br>    this.owner = owner; // Public property<br>  }<br><br>  // Public method acting as a controller interface<br>  deposit(amount) {<br>    if (amount &gt; 0) {<br>      this.#balance += amount;<br>    }<br>  }<br><br>  // Getter method to safely read the private data<br>  getBalance() {<br>    return this.#balance;<br>  }<br>}<br><br>const myAccount = new BankAccount(&quot;Alice&quot;);<br>myAccount.deposit(100);<br><br>console.log(myAccount.getBalance()); // Output: 100<br>console.log(myAccount.#balance);     // Error: Private field &#39;#balance&#39; must be declared in an enclosing class</pre><p><strong>2. The functional Way</strong> : Closures : Before classes had private fields , developers relied on closure . Variable declared inside a function are inaccessible from the outside , but methods returned by that function can still interact with them .</p><pre>function createCounter() {<br>  let count = 0; // Private variable hidden inside the scope<br><br>  return {<br>    increment: function() {<br>      count++;<br>      return count;<br>    },<br>    getCount: function() {<br>      return count;<br>    }<br>  };<br>}<br><br>const counter = createCounter();<br>console.log(counter.increment()); // Output: 1<br>console.log(counter.increment()); // Output: 2<br>console.log(counter.count);       // Output: undefined (Secure!)</pre><h3>9 . Conclusion</h3><p>Object-Oriented Programming in JavaScript helps us write code that is more organised, reusable, and maintainable. By understanding objects, prototypes, classes, constructors, methods, and encapsulation, we can build a strong foundation for developing complex applications. Although JavaScript uses a prototype-based inheritance system internally, the introduction of classes provides a cleaner and more structured way to work with objects.</p><p>Ultimately, understanding these concepts beyond just memorising definitions allows us to write better code, solve problems more effectively, and build scalable applications with confidence.</p><p>Till then, keep exploring, keep building, and keep practicing!!!!!</p><p>Please share your feedback !!!</p><p>Thank You !! 😀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=46e33c1d0184" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Object In JavaScript]]></title>
            <link>https://medium.com/@anshultrip1234/understanding-object-in-javascript-162d3d8f3cdc?source=rss-ebcb3975b6e4------2</link>
            <guid isPermaLink="false">https://medium.com/p/162d3d8f3cdc</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[object-oriented]]></category>
            <dc:creator><![CDATA[Anshul tripathi]]></dc:creator>
            <pubDate>Tue, 15 Sep 2026 05:29:14 GMT</pubDate>
            <atom:updated>2026-09-15T05:36:16.674Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xjsAWAzGpZHv00j44rmDwg.png" /></figure><h3>1 . Introduction</h3><p>When you start learning JavaScript, you’ll quickly come across <strong>objects</strong>. Objects are one of the most important concepts in JavaScript because they allow us to store and organize related data and functionality together.</p><p>Think of a real-world object, like a <strong>car</strong>. A car has properties such as its brand, color, and model, and it can perform actions such as starting, stopping, or accelerating. Similarly, in JavaScript, an object can contain <strong>properties</strong> (data) and <strong>methods</strong> (functions) that describe and control something.</p><p>For example, instead of storing a person’s information in separate variables:</p><pre>let name = &quot;Anshul&quot;;<br>let age = 20;<br>let city = &quot;Delhi&quot;;</pre><p>we can group everything into a single object:</p><pre>let person = {<br>    name: &quot;Anshul&quot;,<br>    age: 20,<br>    city: &quot;Delhi&quot;<br>};</pre><p>Now, all the related information is organized under one person object.</p><p>In this blog, we’ll understand what objects are, how to create them, how to access and modify their properties, how methods work, and why objects are so important when building real-world JavaScript applications<strong>.</strong></p><h3>2 . What Objects are and why they are needed</h3><p>In Js objects are standalone entities that store data as collection of key-value pairs , acting as digital containers or filing cabinets for related information . Unlike primitive data types (like numbers or strings ) which hold only a single value , an object allows you to group complex , mismatched data types and functions together into a single variable .</p><p>Without objects , managing anything beyond simple math or raw text in Js becomes chaotic . Objects solve several structural problems .</p><pre>let userName = &quot;Alice&quot;; <br>let userAge = 20; <br>let userEmail = &quot;alice@gmail.com&quot; ; </pre><p>If you have 100 users , managing hundreds of individual variables is impossible , Objects allow you to bundle this data cleanly into one entity (const user1 = { .... }) .</p><h3>3 . Creating an Object</h3><p>In Js you can create an object in serval different ways . The best method depends on whether you need a single , quick object or a blueprint to make multiple similar objects .</p><ul><li><strong>Object Literals</strong> : The easiest and most popular way to create an object is by using curl braces {} , You simply define a list of key:value pair inside the braces .</li></ul><pre>// Creating an object with properties and a method<br>const user = {<br>  name: &quot;Alice&quot;,<br>  age: 28,<br>  isAdmin: true,<br>  <br>  // A method (a function inside an object)<br>  greet: function() {<br>    console.log(`Hello, my name is ${this.name}`);<br>  }<br>};<br><br>// Accessing properties<br>console.log(user.name); // Output: Alice<br>user.greet();          // Output: Hello, my name is Alice</pre><ul><li><strong>ES6 Classes ( Best for Object-Oriented Programming )</strong> : If you need to create multiple objects with the same structure using modern class syntax is the standard approach .</li></ul><pre>class Car {<br>  constructor(brand, model) {<br>    this.brand = brand;<br>    this.model = model;<br>  }<br><br>  drive() {<br>    console.log(`${this.brand} ${this.model} is moving!`);<br>  }<br>}<br><br>// Create instances using the &#39;new&#39; keyword<br>const car1 = new Car(&quot;Tesla&quot;, &quot;Model 3&quot;);<br>const car2 = new Car(&quot;Toyota&quot;, &quot;Corolla&quot;);<br><br>car1.drive(); // Output: Tesla Model 3 is moving!</pre><ul><li><strong>Object.create()</strong> : This method allows you to create a new object using an existing object as its prototype , The new object inherits all properties and methods of the original object .</li></ul><pre>const animal = {<br>  makeSound: function() {<br>    console.log(&quot;Some generic animal sound&quot;);<br>  }<br>};<br><br>// Create a new object that inherits from &#39;animal&#39;<br>const dog = Object.create(animal);<br>dog.breed = &quot;Labrador&quot;;<br><br>dog.makeSound(); // Output: Some generic animal sound (inherited)<br>console.log(dog.breed); // Output: Labrador</pre><ul><li><strong>Constructor Functions ( Older alternative to classes )</strong> : Before classes were introduced , developers used regular functions alongside the new keyword to create object blueprints . You will still see this often in legacy codebases environment .</li></ul><pre>function Product(name, price) {<br>  this.name = name;<br>  this.price = price;<br>}<br><br>const item = new Product(&quot;Laptop&quot;, 999);<br>console.log(item.name); // Output: Laptop</pre><h3>4 . Accessing properties ( dot notation and bracket notation )</h3><p>In Js , dot notation and bracket notation are the two primary ways to access, modify or add properties to an object , while both serve a similar purpose , they differ significantly in flexibility and syntax .</p><ol><li><strong>Dot Notation</strong> ( object . property ) : Dot notation is the most common and preferred way because it is succinct and easy to read .</li></ol><ul><li>R<strong>ule-:</strong> The property name after the dot must be a valid JS identifier , it cannot contain spaces , start with a number or include special characters (except $ and _ ) .</li></ul><pre>const user = {<br>  name: &quot;Alex&quot;,<br>  age: 28<br>};<br><br>// Accessing properties<br>console.log(user.name); // Output: Alex<br>console.log(user.age);  // Output: 28<br><br>// Modifying and Adding properties<br>user.age = 29;<br>user.isAdmin = true;</pre><p>2 . Bracket Notation : Bracket notation evaluates the expression inside the square brackets as a string to find the property , It is far more powerful and is mandatory in several scenarios .</p><ul><li>S<strong>cenario A</strong> : The property name has a spaces or special char .</li></ul><pre>const order = {<br>  &quot;item id&quot;: 4502,<br>  &quot;user-email&quot;: &quot;alex@email.com&quot;<br>};<br><br>// console.log(order.item id); // Syntax Error<br>console.log(order[&quot;item id&quot;]);  // Output: 4502<br>console.log(order[&quot;user-email&quot;]); // Output: alex@email.com</pre><ul><li>Scenario B : The property name starts with or is a number</li></ul><pre>const schedule = {<br>  1: &quot;Monday&quot;,<br>  2: &quot;Tuesday&quot;<br>};<br><br>// console.log(schedule.1); // Syntax Error<br>console.log(schedule[1]);    // Output: Monday (JS automatically converts the number to a string)</pre><ul><li>Scenario C : Accessing the properties dynamically using a variable</li></ul><pre>const bike = {<br>  brand: &quot;Ducati&quot;,<br>  color: &quot;Red&quot;<br>};<br><br>const query = &quot;brand&quot;;<br><br>console.log(bike.query);   // Output: undefined (looks for a key literally named &quot;query&quot;)<br>console.log(bike[query]);  // Output: Ducati (evaluates `query` to &quot;brand&quot;)</pre><blockquote>Use dot notation by default for its clean readability and switch to bracket notation when dealing with variable , dynamic keys or irregular property name ( spaces , numbers , special characters ) .</blockquote><h3>5 . Updating object properties</h3><p>In Js , you can update object properties using either mutable methods ( changing the original object ) or immutable methods ( creating a new object with updated values ) .</p><p>1 . <strong>Mutable Approach</strong> (Modifying the original object ) : If you want to change the property values directly on the existing object , you can use dot notation or bracket notation .</p><ul><li><strong>Dot Notation</strong> : Best used when you already know the exact name of the property you want to update .</li></ul><pre>const user = { name: &quot;Alex&quot;, age: 25 };<br><br>// Update the age property<br>user.age = 26; <br><br>console.log(user); // { name: &quot;Alex&quot;, age: 26 }</pre><ul><li><strong>Bracket Notation</strong> : Best used when the property name is stored in a variable , contains spaces / special characters or is determined dynamically at runtime .</li></ul><pre>const user = { name: &quot;Alex&quot;, age: 25 };<br>const propertyToUpdate = &quot;age&quot;;<br><br>// Update using a dynamic variable<br>user[propertyToUpdate] = 30; <br><br>// Update using a string literal<br>user[&quot;name&quot;] = &quot;Jordan&quot;; <br><br>console.log(user); // { name: &quot;Jordan&quot;, age: 30 }</pre><p>2 . Immutable Approach ( creating a new object ) : In modern JS ( and modern frameworks like React ) , it is highly recommended to treat objects as immutable , instead of changing the original object , you create a copy of it with the updated values .</p><ul><li><strong>Spread Operato</strong>r ( ... ) : The spread operator copies all existing properties into a new object literal while letting you overwrite specific fields .</li></ul><pre>const originalUser = { name: &quot;Alex&quot;, age: 25, role: &quot;Developer&quot; };<br><br>// Create a new object with updated age<br>const updatedUser = {<br>  ...originalUser,<br>  age: 26<br>};<br><br>console.log(originalUser.age); // 25 (unchanged)<br>console.log(updatedUser.age);  // 26 (updated)</pre><ul><li><strong>Object.assign</strong> : This method copies the properties from one or more source object into a target object . Passing an empty object {} as the first argument ensures you to generate a brand new object .</li></ul><pre>const user = { name: &quot;Alex&quot;, age: 25 };<br><br>const updatedUser = Object.assign({}, user, { age: 28 });<br><br>console.log(updatedUser); // { name: &quot;Alex&quot;, age: 28 }</pre><h3>6 . Adding and Deleting properties in JS</h3><p>To add and delete properties from object in Js we can use the dot notation and bracket notation .</p><p>1 .<strong> Adding properties</strong> : You can add a property simply by assigning a value to a new key .</p><ul><li>Dot Notation : Best when you know the property name beforehand .</li><li>Bracket Notation : Essential when the property name is stored in variable , has spaces , or is a number.</li></ul><pre>const user = { name: &quot;Alex&quot; };<br><br>// Using Dot Notation<br>user.age = 30; <br><br>// Using Bracket Notation<br>const keyName = &quot;email&quot;;<br>user[keyName] = &quot;alex@example.com&quot;; <br><br>console.log(user); <br>// Output: { name: &quot;Alex&quot;, age: 30, email: &quot;alex@example.com&quot; }</pre><p>2 <strong>. Deleting Properties</strong> : You can completely remove a property from an object using the delete operator , this removes both the key and its value .</p><pre>const user = { name: &quot;Alex&quot;, age: 30, email: &quot;alex@example.com&quot; };<br><br>// Using Dot Notation<br>delete user.age; <br><br>// Using Bracket Notation<br>delete user[&quot;email&quot;]; <br><br>console.log(user); <br>// Output: { name: &quot;Alex&quot; }</pre><h3>7 . Looping through object keys</h3><p>The most efficient and modern way to loop through object keys in JS is by using Object.key() . This method extracts the objects keys into an array , allowing you to use standard array iterations method like for...of or forEach() .</p><p><strong>1 . Loop Through keys only ( </strong><strong>object.keys() )</strong></p><pre>const user = { name: &#39;Alex&#39;, role: &#39;Admin&#39;, age: 28 };<br><br>// Using for...of (Recommended for readability)<br>for (const key of Object.keys(user)) {<br>  console.log(key); <br>}<br>// Output: name, role, age</pre><p>2 . <strong>Loop through keys and values together</strong> : This is the cleanest approach if you need both the key and its corresponding values , It returns an array of [key , value] pair which you can easily destructure .</p><pre>const user = { name: &#39;Alex&#39;, role: &#39;Admin&#39;, age: 28 };<br><br>for (const [key, value] of Object.entries(user)) {<br>  console.log(`${key}: ${value}`);<br>}<br>// Output: <br>// name: Alex<br>// role: Admin<br>// age: 28</pre><p>3 . <strong>The traditional approach </strong>( for...in ) : The for...in loop is built-in way to iterate over object keys . However , it has a major caveat , it also iterates over keys inherited through the prototype chain , If you use it , always include a hasOwnProperty() check to keep it safe .</p><pre>const user = { name: &#39;Alex&#39;, role: &#39;Admin&#39;, age: 28 };<br><br>for (const key in user) {<br>  if (user.hasOwnProperty(key)) { // Ensures it only loops over the object&#39;s own properties<br>    console.log(key, user[key]);<br>  }<br>}</pre><h3>8 . Conclusion</h3><p>Objects are one of the fundamental building blocks of JavaScript. They make it easier to organize related data and functionality into a single, meaningful structure. In this blog, we explored how to create objects, access their properties using dot and bracket notation, update existing properties, add or delete properties, and loop through object keys and values.</p><p>Understanding these concepts gives you a strong foundation for working with JavaScript. As you move toward more advanced topics like arrays of objects, nested objects, destructuring, prototypes, and classes, you’ll find that objects are used almost everywhere in real-world JavaScript applications.</p><p>So, if you’re learning JavaScript, getting comfortable with objects is not optional , it’s an essential step toward becoming a better JavaScript developer.</p><p>Till then keep practicing , Keep exploring and Keep Building !!!!!!!!!!!!</p><p>Please share your feedback with us !!!!!</p><p>Thank You 😄</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=162d3d8f3cdc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Arrow Functions in JavaScript: A Simpler Way to Write Functions]]></title>
            <link>https://medium.com/@anshultrip1234/arrow-functions-in-javascript-a-simpler-way-to-write-functions-f055586dc76c?source=rss-ebcb3975b6e4------2</link>
            <guid isPermaLink="false">https://medium.com/p/f055586dc76c</guid>
            <category><![CDATA[arrow-functions]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[tech]]></category>
            <dc:creator><![CDATA[Anshul tripathi]]></dc:creator>
            <pubDate>Wed, 02 Sep 2026 08:36:07 GMT</pubDate>
            <atom:updated>2026-09-02T08:36:07.746Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yw-CFMNoNztX8LwF2H-B7w.png" /></figure><h3>1. Introduction</h3><p>JS provides different ways to write functions , and one of the modern and popular approaches is using <strong>arrow functions</strong>. Introduced with <strong>ES6 (ECMAScript 2015)</strong>, arrow functions offer a shorter and cleaner syntax for writing functions compared to traditional function expressions.</p><p>They are especially useful when you want to write simple functions in a more concise way. However, arrow functions are not just about reducing the amount of code you write they also behave differently from regular functions in certain situations, particularly when it comes to the this keyword.</p><p>In this blog, we’ll understand what arrow functions are, how to write them, and how they differ from traditional JavaScript functions.</p><h3>2 . What arrow functions are</h3><p>Arrow functions are a more concise syntax for writing function expressions in JS , introduced in ECMAScript 6 (ES6) . They utilise the =&gt; (“fat arrow”) token to define functions quickly , making code cleaner and more readable .</p><ul><li>Arrow functions don’t have their own binding to this , arguments or super and should not be used as method .</li><li>Arrow functions cannot be used as constructors , calling them with new throws a typeError . They also don’t have access to the new.target keyword .</li><li>Arrow functions cannot use yield within their body and cannot be created as generator functions .</li></ul><h3>3 . Basic arrow function syntax</h3><p>Arrow functions are a concise way to write function expressions in JS using the =&gt; syntax .</p><p>The Core breakdown :</p><p>Here is a direct comparison between the traditional function expression and the basic arrow function syntax .</p><pre>const sayHello = () =&gt; {<br>return &quot;hello!&quot;;<br>};</pre><p>Here is a direct comparison between the traditional function expression and the basic arrow function syntax:</p><p><strong>Traditional Function</strong> : const add = function(a, b) { return a + b; };</p><p><strong>SyntaxArrow Function Syntax</strong>: const add = (a, b) =&gt; { return a + b; };</p><p>To convert a traditional function into an arrow function, you <strong>remove the </strong><strong>function keyword</strong> and <strong>add a fat arrow (</strong><strong>=&gt;)</strong> between the parameters and the opening curly brace.</p><h3>4 . Arrow function with one parameter</h3><p>An arrow function with exactly one parameter allows for a highly concise syntax in JS , When a function only has a single parameter , you can omit the parentheses around it .</p><p>Furthermore , if the function only returns a single expression , you can omit the curly braces {} and the return keyword for an implicit return .</p><p>eg-</p><pre>const double = num =&gt; num *2 ; <br><br>console.log(double(5));<br></pre><h3>5 . Arrow functions with multiple parameters</h3><p>When writing an arrow function with multiple parameters in JS you must enclose the parameters in parentheses () .</p><p>While you can omit parentheses for a single parameter , they are strictly requires when dealing with two or more inputs .</p><p>If you need to perform multiple steps or lines of logic , you must use curly braces {} and explicitly use the return keyword .</p><pre>// Multiple parameters: num1 and num2<br>const add = (num1, num2) =&gt; num1 + num2;<br><br>console.log(add(5, 3)); // Output: 8</pre><ul><li>Multi-line body ( explicit Return ) : If you need to perform multiple steps or lines of logic , you must use curly braces {} and explicitly use the return keyword .</li></ul><pre>// Multiple parameters: firstName and lastName<br>const formatGreeting = (firstName, lastName) =&gt; {<br>  const upperFirst = firstName.toUpperCase();<br>  const upperLast = lastName.toUpperCase();<br>  return `Hello, ${upperFirst} ${upperLast}!`;<br>};<br><br>console.log(formatGreeting(&quot;John&quot;, &quot;Doe&quot;)); // Output: Hello, JOHN DOE!</pre><h3>6 . Implicit return vs explicit return</h3><p>The main difference between an implicit return and an explicit return in JS arrow function comes down to whether you use curly braces {} and the return keyword .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hoFm3p2c_QvXIKvWWhxMZA.png" /><figcaption>difference between implicit return and explicit return</figcaption></figure><p>In simple word in JS arrow functions can automatically return values without needing the return keyword , This is called implicit return . It works when the function contains a single expression , and the result of that expression is automatically returned .</p><pre>const add = (a,b) =&gt; a+b ; <br>console.log (add(2,4)); //output : 5 <br><br>const setData = (prevData) =&gt; ({<br>         ...prevData, <br>        content: &#39;lorem ipsum&#39;<br>}); </pre><p>Notice that there is no return keyword in the body of the function , The result of a+b is implicitly returned .</p><ul><li>Sometimes , you might need to execute multiple operations within a function or the function has a block body ( using {} ) . In these cases , you must use the return keyword to explicitly return a value .</li></ul><pre>const setData = (prevData) =&gt; {<br>return { <br>  ...preData, <br>  content: &quot;lorem ipsum&quot;<br>};<br>};</pre><p>Here , the return keyword is necessary because the function body is enclosed in {} and we need to explicitly return the updated object .</p><h3>7 . Basic difference between arrow functions and normal functions</h3><p>The main difference is that arrow functions provide a shorter syntax and do not have their own this binding or argument objects.</p><p>Key differences</p><ul><li><strong>Syntax</strong> : Normal functions use the function keyword , while arrow functions use a short fat arrow =&gt; syntax .</li><li>The this Keyword : Normal functions define their own this value based on how they are called . Arrow functions inherit this from the surrounding code block (lexical scoping).</li><li><strong>Arguments Object</strong> : Normal functions have access to an argument array-like object . Arrow functions do not have an arguments object ; you must use rest parameters (…args) instead .</li><li><strong>Constructor use</strong> : Normal functions can be used as constructors with the new keyword . Arrow functions cannot be used as constructors .</li><li><strong>Hoisting</strong> : Normal function declarations are hoisted to the top of their scope . Arrow functions are not hoisted and behave like variables .</li></ul><h3>8 . Conclusion</h3><p>Arrow functions provide a cleaner and more concise way to write functions in JavaScript. They are especially useful for writing short functions, callbacks, and functional programming patterns. Their lexical handling of this also makes them particularly helpful in certain situations where traditional functions can behave differently.</p><p>However, arrow functions are not meant to completely replace regular functions. Understanding when to use arrow functions and when to use traditional function declarations is an important part of becoming a better JavaScript developer.</p><p>By choosing the right type of function for the right situation, you can write code that is cleaner, more readable, and easier to maintain.</p><p><strong>Till then, keep building, keep trying, and keep exploring!!!!!!</strong></p><p>Please share you feedback !!!</p><p>Thank you 😀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f055586dc76c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Function Declaration vs Function Expression in JavaScript]]></title>
            <link>https://medium.com/@anshultrip1234/function-declaration-vs-function-expression-in-javascript-4ab1de1457b5?source=rss-ebcb3975b6e4------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ab1de1457b5</guid>
            <category><![CDATA[function]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[node]]></category>
            <dc:creator><![CDATA[Anshul tripathi]]></dc:creator>
            <pubDate>Sat, 15 Aug 2026 08:14:54 GMT</pubDate>
            <atom:updated>2026-08-15T08:14:54.033Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5K8bMzeMplLFe6MlgJd3KA.png" /></figure><h3>1 . Introduction</h3><p>Functions are one of the most important building blocks of JS . They allow us to organise code into reusable pieces , making programs easier to write , understand and maintain , but when working with functions , we may come across two common ways of creating them , Function Declaration and Function Expressions .</p><p>At first ,they might look almost identical , but there are some important differences in how they are defined , hoisted and used understanding these differences can help us write cleaner JS and avoid unexpected behaviour in our code .</p><p>In this blog , we’ll explore Function Declarations vs Function Expressions , understanding how each one works and see when we should use one over the other .</p><h3>2 . What functions are and why we need them</h3><p>A function is a self-contained block of reusable code designed to perform a specific task . Think of it like a cooking recipe : we write down the ingredients (inputs ) and the instructions once and we can reuse that recipe to make the dish whenever we want without rewriting the instructions .</p><p>A standard function consists of a declaration , parameters (inputs) and a return value (output) .</p><pre>// 1. Defining the function (The Recipe)<br>function greetUser(username) { <br>  return &quot;Hello, &quot; + username + &quot;!&quot;; <br>}<br><br>// 2. Calling the function (Cooking the Dish)<br>let message = greetUser(&quot;Alice&quot;); <br>console.log(message); // Outputs: Hello, Alice!</pre><p><strong>Why we need Function in JS</strong></p><p>Without functions , programming would involve copying and pasting the same blocks of code repeatedly , Function solve several critical software development challenges .</p><ul><li><strong>Code Reusabilit</strong>y : Instead of writing the same code over and over , we write it once inside a function and call it whenever needed , This follows the DRY ( Don’t Repeat Yourself) .</li><li><strong>Organisation and Readabilit</strong>y : Function let us break large complex codebases into smaller ,manageable chunks . Eg- Instead of reading a massive 500-line script , a developer can look at a clean sequence of functions .</li></ul><h3>3 . Function Declaration syntax</h3><p>In Js a function declaration is defined using the function keyword , followed by a mandatory function name , a list of parameters in parentheses and the code body inside curly braces .</p><pre>function functionName(parameter1, parameter2, parameterN) {<br>  // Code to execute (function body)<br>  return value; // Optional<br>}</pre><pre>// Declaring the function<br>function greetUser(username) {<br>  return `Hello, ${username}!`;<br>}<br><br>// Executing (calling) the function<br>const message = greetUser(&quot;Alice&quot;);<br>console.log(message); // Output: Hello, Alice!</pre><p>From the above example we can understand the basic of function</p><ul><li>function <strong>keyword</strong> : The mandatory keyword that tells JS you are declaring a function .</li><li><strong>Function Name</strong> : A unique identifier (e.g- greetUser ) used to call the function later .</li><li><strong>Parameters</strong> : Inputs listed inside parentheses () and separated by commas . IF our function does not need inputs leave the parentheses empty () .</li><li><strong>Function Body</strong> : The block of code inside the curly braces {} that runs whenever the function is invoked .</li><li>return <strong>Statement</strong> : An optional keyword used to send a value back whenever the function was called , If omitted the function returns undefined by default .</li></ul><h3>4 . Function expression Syntax</h3><p>A JS function expression defines inside an expression , typically by assigning it to a variable , Unlike function declarations , function expressions are not hoisted , meaning they cannot be used before they are defined in the code.</p><p>1 . Anonymous Function expressions</p><p>The most common syntax omits the function name after the function keyword . The function is invoked using the variable name .</p><pre>const variableName = function(param1, param2) {<br>  // Code to execute<br>  return value;<br>}; // Notice the semicolon at the end<br><br>// Example usage:<br>const add = function(a, b) {<br>  return a + b;<br>};<br><br>console.log(add(5, 3)); // Outputs: 8</pre><p>2 . Named function Expression</p><p>We can include a function name after the function keyword , This name is only accessible inside the function’s own scope , making it useful for debugging stack traces or creating recursive calls</p><pre>const variableName = function functionName(param) {<br>  // &#39;functionName&#39; is available here for recursion<br>  return param;<br>};<br><br>// Example usage:<br>const factorial = function computeFactorial(n) {<br>  if (n &lt;= 1) return 1;<br>  return n * computeFactorial(n - 1); // Uses internal name<br>};<br><br>console.log(factorial(5)); // Outputs: 120<br>// console.log(computeFactorial(5)); // Throws ReferenceError</pre><p>3 . Arrow Function Expression ( Modern ES6+ )</p><p>Introduced in modern JS , arrows functions offer a highly concise shorthand for writing function expressions by dropping the function keyword .</p><pre>const variableName = (param1, param2) =&gt; {<br>  return param1 + param2;<br>};<br><br>// If the function has only one parameter, parentheses can be omitted:<br>const square = x =&gt; x * x;</pre><h3>5 . Key differences between declarations and expression</h3><p>The core difference between a declaration and an expression in Js is that declarations create a variable or function structure without producing a value .</p><p>This distinction applies broadly across the language , but it is most critical when comparing Function Declaration and Function Expressions .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pHPaJUExXb_y1wGtM_5niw.png" /><figcaption>Main differences</figcaption></figure><h3>6 . Basic idea of hoisting</h3><p>Hoisting is JS default behaviour of moving declarations to the top of their current scope before the code executes .</p><p>Essentially , the JS engine reads your code twice : first to find and allocate memory for all variables and functions ( the compilation phase ) and second to execute the code line by line , because of this you can often reference variables and functions before they are formally written in our file .</p><p>Crucially , JS only hoists declarations ,not initialisations ( assignements ) .</p><p>1 . Function Hoisting</p><p>Function declarations are fully hoisted , the JS engine moves the entire function structure to the top of the scope , allowing you to safely call a function before defining it .</p><pre>greet(); // Output: &quot;Hello!&quot;<br><br>function greet() {<br>    console.log(&quot;Hello!&quot;);<br>}</pre><p>2 . Variable Hoisting ( var vs let &amp; const )</p><p>The keyword you use to declare a variable completely changes how it handles hoisting .</p><p>Using var</p><p>When you use var , the variable declaration is hoisted and automatically given a placeholder value of undefined</p><pre>console.log(user); // Output: undefined (No crash)<br>var user = &quot;Alice&quot;; <br>console.log(user); // Output: &quot;Alice&quot;</pre><p>Behind the scenes the engine sees the code like this :</p><pre> var user;          // Declaration is hoisted to the top!<br>console.log(user); // Value is undefined<br>user = &quot;Alice&quot;;    // Assignment stays right where it was<br>console.log(user); // Value is now &quot;Alice&quot;</pre><p>Using let and const</p><p>Variable declared with let and const are also hoisted , but they are not initialised with any default value . They sit in a locked state called the <strong>Temporal Dead Zone</strong> ( TDZ) from the start of the block until the engine reaches the line where they are declared .</p><p>Trying to access them early causes the application to crash with a ReferenceError .</p><pre>console.log(age); // Throws ReferenceError: Cannot access &#39;age&#39; before initialization<br>let age = 25;</pre><p>3 . Function Expression and Arrow Functions</p><p>If you assign a function to a variable , it follows the hoisting rules of that specific variable keyword hoisting not function hoisting rules .</p><pre>sayHi(); // Throws TypeError: sayHi is not a function<br><br>var sayHi = function() {<br>    console.log(&quot;Hi!&quot;);<br>};</pre><p>Because sayHi was declared with var , only the variable declarations was hoisted (as undefined ) . You cannot invoke undefined as a function , if you used let or const here , it would throw a ReferenceError instead .</p><h3>7 . When to use each type</h3><p>You should use <strong>let for variables that will change</strong> and <strong>const for variables that must remain constant.</strong></p><p>In modern JavaScript, you should almost never use var. Choosing between let and const depends entirely on whether you need to reassign the variable later.</p><p>Use const by Default</p><p>You should use const for <strong>around 80-90% of your variables</strong>. It prevents accidental bugs by ensuring a variable cannot be reassigned to a completely new value.</p><ul><li><strong>Fixed values:</strong> const pi = 3.14;</li><li><strong>DOM elements:</strong> const submitBtn = document.getElementById(&#39;submit&#39;);</li><li><strong>Functions:</strong> const fetchData = () =&gt; {};</li><li><strong>Objects and Arrays:</strong> (Even if you change the properties <em>inside</em> an object or array, the variable itself isn’t being reassigned).</li></ul><pre>const user = { name: &quot;Alice&quot; };<br>user.name = &quot;Bob&quot;; // This is perfectly fine!<br><br>user = { name: &quot;Charlie&quot; }; // Throws TypeError (Cannot reassign)</pre><h3>8 . Conclusion</h3><p>Understanding the difference between Function Declaration and Function Expression is an important part of writing clean and predictable JS , While both are used to create function , they differ in syntax , hoisting behaviour and how they are commonly used .</p><p>Function declaration are great when we want to define reusable functions that can be called before their definition . Function expressions , on the other hand provide more flexibility and are especially useful when working with callbacks , conditional logic , or assigning functions to variables .</p><p>Once you understand these differences , choosing between the two becomes much easier and your JS code becomes more intentional and readable .</p><p>Keep learning , Keep exploring and Keep building !!!!!</p><p>Please share your feedback with us !!!!</p><p>Thank you 😀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ab1de1457b5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript Arrays: Flattening Nested Structures]]></title>
            <link>https://medium.com/@anshultrip1234/javascript-arrays-flattening-nested-structures-7dfe660b4576?source=rss-ebcb3975b6e4------2</link>
            <guid isPermaLink="false">https://medium.com/p/7dfe660b4576</guid>
            <category><![CDATA[polyfill-in-javascript]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[browsers]]></category>
            <category><![CDATA[array-methods]]></category>
            <dc:creator><![CDATA[Anshul tripathi]]></dc:creator>
            <pubDate>Thu, 13 Aug 2026 07:25:58 GMT</pubDate>
            <atom:updated>2026-08-13T07:25:58.798Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AwupoHRlxmkl9eAPaLAx-w.png" /></figure><h3><strong>1 . Introduction</strong></h3><p>Arrays are one of the most commonly used data structures in JS , but things can get a little messy when arrays contain other arrays. eg instead of having a simple array like [1,2,3,4] , we might end up with something like [1, [2,3] , [4, 5]] .</p><p>This is where array flattening comes in , Flattening means converting a nested array into a single-level array , making the data easier to work with and process .</p><p>In this blog , we’ll explore how to flatten arrays in JS using like flat() and flatMap() , understanding how they work and look at different ways handle deeply nested arrays.</p><h3>2 . What nested arrays are</h3><p>Nested arrays are arrays that contain other arrays as their elements , instead of holding simple values like numbers or strings , an outer ‘parent’ array holds one or more ‘child’ sub-arrays . This structure is often referred to as a multi-dimensional array .</p><p>Think of a nested array like a tree , a grid or a box containing smaller boxes</p><pre>// A simple 2-dimensional nested array<br>const matrix = [<br>  [1, 2, 3], // Row 0<br>  [4, 5, 6], // Row 1<br>  [7, 8, 9]  // Row 2<br>];</pre><ul><li><strong>Outer Array</strong> : The main wrapper array containing the data .</li><li><strong>Inner Array</strong> : The sub-arrays residing in the outer array .</li><li><strong>Element Count</strong> : When calculating the length of the outer array , each inner array is counted as a single element , regardless of how many items are inside it .</li></ul><h3>3 . Why flattening arrays is useful</h3><p>Flattening an array transforms a multi-dimensional , nested structure into a single-level array , making data manipulation significantly more efficient and straightforward , It solves the core problem of dealing with complex structural hierarchies when our operations require a uniform , linear list .</p><ul><li>Simplifies UI Rendering : Modern frontend libraries expect flat lists, so we can easily map data into components or render them linearly into the DOM .</li><li>Normalises API Responses : JSON data from databases or external APIs often arrives deeply nested to represent relationship hierarchies , Flattening cleans this up so our business logic can consume the raw data directly .</li><li>Streamlines Data Processing : Standard array methods (filter() , .map() , and .sort() become trivial to use because you no longer need complex , recursive loop nesting to access inner values .</li><li>Library Integration : Visualisation and charting tools requires simple , linear 1D datasets to map onto axes or charts .</li><li>Simplifies Search &amp; Deduplication : Algorithm searching for specific values or filtering out duplicates ( like using a Set ) requires a unified array to perform optimally .</li></ul><h3>4 . Concept of flattening arrays</h3><p>Flattening an array means converting a multi-dimensional or nested array structure into single-layer , one-dimensional array . It unwraps internal subarrays , moving all nested items directly into the parent array .</p><p>The flat() method is a copying method , it does not alter this but instead returns a shallow copy that contains the same elements as the ones from the original array . The flat() methods removes empty slots if the array being flattened is sparse . for eg- if depth is 1 both empty slots in the root arrays and in the first level of nested arrays are ignored , but empty slots in further nested arrays are preserved with the arrays themselves .</p><pre>// Visualizing the concept<br>[1, [2, 3], [4, [5, 6]]] ─── Flattened ───&gt; [1, 2, 3, 4, 5, 6]</pre><p>In technical interviews we are often asked to implement our own version of .flat() without using the native method .</p><p>We can use array.reduce() method to iterate through items . If an element is an array it recursively calls itself , otherwise it appends the item to the running accumulator .</p><pre>function deepFlatten(arr) {<br>  return arr.reduce((acc, val) =&gt; {<br>    return acc.concat(Array.isArray(val) ? deepFlatten(val) : val);<br>  }, []);<br>}<br><br>const arr = [1, [2, [3, 4], 5], 6];<br>console.log(deepFlatten(arr)); // [1, 2, 3, 4, 5, 6]</pre><h3>5 . Different approaches to flatten arrays</h3><p>There are several ways to flatten a nested array in JS , ranging from modern native method to custom algorithms techniques commonly requested in technical interviews .</p><p>1 . Modern &amp; Built-In Methods</p><ul><li>Array.prototype.flat() : The standard modern method , pass specific number for different level or completely when passed Infinity .</li></ul><pre>const arr = [1, [2, [3, 4]]];<br>arr.flat(Infinity); // [1, 2, 3, 4] </pre><ul><li>Array.prototype.flatMap() : Maps each element using a callback function and flattens the result by exactly one level .</li></ul><pre>const arr = [1, 2, 3];<br>arr.flatMap(x =&gt; [x, x * 2]); // [1, 2, 2, 4, 3, 6]</pre><p>2 . Iterative and Custom Performance Approaches :</p><ul><li>Stack-Based Iteration : Avoids the call stack limitations of recursion to prevent Maximum call stack size exceeded errors on heavily nested arrays .</li></ul><pre>function flattenIterative(arr) {<br>  const stack = [...arr];<br>  const res = [];<br>  while (stack.length) {<br>    const next = stack.pop();<br>    if (Array.isArray(next)) {<br>      stack.push(...next);<br>    } else {<br>      res.unshift(next);<br>    }<br>  }<br>  return res;<br>}<br></pre><h3>6 . Common Interview scenarios</h3><p>Flattening a nested array is one the most common coding challenges in JS technical interviews . Interviews use it to evaluate our understanding of recursion , stack control , memory optimisation and modern ES6 + array</p><p>1 . The Standard Polyfill :</p><p>Interviewers will explicitly ask you not to use the native Array.prototype.flat() . They wan to see a manual recursive implementation to handle infinite nesting</p><pre>function deepFlatten(arr) {<br>  return arr.reduce((acc, current) =&gt; {<br>    if (Array.isArray(current)) {<br>      acc.push(...deepFlatten(current)); // Recursive call if element is an array<br>    } else {<br>      acc.push(current);<br>    }<br>    return acc;<br>  }, []);<br>}</pre><ul><li>alternative we can also use for ... of loop or .concat() , but .reduce() showcases a strong functional programming foundation .</li></ul><p>2 . Flattening to a Specific Depth : A major step up is handling a custom depth argument exactly mimicking how the built-in Array.prototype.flat(depth) works .</p><pre>function flattenByDepth(arr, depth = 1) {<br>  if (depth &lt; 1) return arr.slice(); // Base case: return copy if depth limit reached<br><br>  return arr.reduce((acc, current) =&gt; {<br>    if (Array.isArray(current)) {<br>      acc.push(...flattenByDepth(current, depth - 1));<br>    } else {<br>      acc.push(current);<br>    }<br>    return acc;<br>  }, []);<br>}</pre><p>Always talk through edge cases before writing code . Interviewers look for this quality to identify engineering maturity . Be prepared to handle .</p><ul><li>Sparse Array ( Empty Slots ) : An array like [1, ,3] contains a hole . A standard for loop handles this differently than reduce or flat . The native flat() method deletes empty slots . Ask your interviewer if holes should be preserved or discarded .</li><li>Null and Undefined : Ensure your check uses Array.isArray(val) and not a generic truthy object check . A value of null returns an object type in Js ( typeof null === &#39;object&#39; ) , which can break poorly written custom flat algorithms .</li></ul><h3>7 . Conclusion</h3><p>Flattening nested arrays in JavaScript is a simple yet powerful technique for working with complex data structures. Whether you use Array.prototype.flat(), flatMap(), or a recursive approach for deeper customization, understanding how flattening works can make your code cleaner and easier to manage.</p><p>The key is to choose the right approach based on your use case. For most situations, flat() is the simplest and most readable solution. Once you understand these methods, handling nested array data becomes much more straightforward and efficient.</p><p>Keep exploring, keep building, and keep learning.</p><p>Please share your feedback with us !!</p><p>Thank you 😀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7dfe660b4576" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From push() to reduce(): Mastering JavaScript Array Methods]]></title>
            <link>https://medium.com/@anshultrip1234/from-push-to-reduce-mastering-javascript-array-methods-41ecf1e2ddd6?source=rss-ebcb3975b6e4------2</link>
            <guid isPermaLink="false">https://medium.com/p/41ecf1e2ddd6</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[javascript-array-methods]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Anshul tripathi]]></dc:creator>
            <pubDate>Mon, 10 Aug 2026 04:38:41 GMT</pubDate>
            <atom:updated>2026-08-10T04:38:41.448Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fxvNxlNIRoxNdn0KXbXICA.png" /></figure><h3>1. Introduction</h3><p>If you’ve worked with JS arrays , you’ve probably used method like push() or pop() to add and remove elements . But JS arrays come with a whole toolbox of built-in methods that can help you search , transform , filter , sort and manipulate data without writing everything form scratch .</p><p>In this blog we’ll explore some of the most useful JS array methods , understanding how they work and see practical eg of when to use them . Whether you’re just getting started with JS or want to strengthen your fundamentals , mastering these method will make working with arrays much easier.</p><h3>2 . Push() and Pop() method</h3><p>In JS push() adds one or more elements to the end of an array , while pop() removes the very last element from that same array . Both methods directly mutate (modify) the original array .</p><p>Together , they allow us to easily implement a LIFO ( last-in , First-Out) stack data structure in JS .</p><p><strong>1 . The push() Method</strong> : It allows us to append the values to the end of an array instance and returns the new length of the array .</p><pre>const tools = [&#39;hammer&#39;, &#39;screwdriver&#39;];<br><br>// Add a single item<br>const newLength = tools.push(&#39;wrench&#39;); <br><br>console.log(tools);     // Output: [&#39;hammer&#39;, &#39;screwdriver&#39;, &#39;wrench&#39;]<br>console.log(newLength); // Output: 3<br><br>// Add multiple items at once<br>tools.push(&#39;saw&#39;, &#39;drill&#39;);<br>console.log(tools);     // Output: [&#39;hammer&#39;, &#39;screwdriver&#39;, &#39;wrench&#39;, &#39;saw&#39;, &#39;drill&#39;]</pre><p>As we can see from the above eg that the push() method allow us to add elements to the end and it can accept one or more items .</p><p><strong>2 . The pop() Method</strong> : It allows us to remove the last element from an array and returns that removed element , If the array is empty , it returns undefined without throwing an error .</p><pre>const tools = [&#39;hammer&#39;, &#39;screwdriver&#39;, &#39;wrench&#39;];<br><br>// Remove the last item<br>const removedItem = tools.pop();<br><br>console.log(tools);       // Output: [&#39;hammer&#39;, &#39;screwdriver&#39;]<br>console.log(removedItem); // Output: &#39;wrench&#39;<br><br>// Calling pop on an empty array<br>const emptyArray = [];<br>console.log(emptyArray.pop()); // Output: undefined</pre><p>As we can see from the above eg that the pop() method allow us to remove the last element and it does not accept any arguments .</p><h3>3 . shift() and unshift() method</h3><p>shift() and unshift() are built-in JS array methods used to modify the beginning of an array , both methods are destructive , meaning they alter the original array directly rather than creating a new one .</p><p>1 . The shift() Method : It helps to removes the first element from an array and returns that removed element. This action shifts all subsequent elements down by one index .</p><ul><li>Syntax : array.shift()</li></ul><pre>const colors = [&quot;red&quot;, &quot;blue&quot;, &quot;green&quot;];<br><br>const firstColor = colors.shift(); <br><br>console.log(firstColor); // Output: &quot;red&quot;<br>console.log(colors);     // Output: [&quot;blue&quot;, &quot;green&quot;]</pre><p>From the above eg we can understand that shift() method helps to remove the first item and it returns the removed element .</p><p>2 . The unshift() Method : It helps to add one or more elements to the beginning of an array .</p><ul><li>Syntax : array.unshift(element1 , element2 ,... elementx</li></ul><pre>const numbers = [3, 4];<br><br>const newLength = numbers.unshift(1, 2); <br><br>console.log(newLength); // Output: 4<br>console.log(numbers);   // Output: [1, 2, 3, 4]</pre><p>From the above eg we can understand that unshift() method helps to add elements to the beginning of the array and it return the new array length.</p><h3>4 . The Map() Method</h3><p>The JS map() method creates a new array by applying a specific callback function to every element of the original array . It loops through each item sequentially , transforms it based on our logic and returns the newly constructed array without changing the original one .</p><ul><li>Basic syntax : const newArr = originalArray.map((element , index ,array) =&gt; { return the new value for this element });</li><li>element : The current item being processed in the array .</li><li>index : The index position of the current item .</li><li>array : The original array map() was called upon .</li></ul><p>Common use cases :</p><p><strong>1 . Transforming Array Elements</strong> : We can apply a mathematical or string operation to every item .</p><pre>const numbers = [1, 2, 3, 4];<br>const doubled = numbers.map(num =&gt; num * 2);<br><br>console.log(doubled); // [2, 4, 6, 8]<br>console.log(numbers); // [1, 2, 3, 4] (Original remains unchanged)</pre><p><strong>2 . Extracting specific Data from object</strong> : This is highly useful when handling APIs responses where we only need one propety .</p><pre>const users = [<br>  { id: 1, name: &quot;Alice&quot; },<br>  { id: 2, name: &quot;Bob&quot; }<br>];<br><br>const names = users.map(user =&gt; user.name);<br>console.log(names); // [&quot;Alice&quot;, &quot;Bob&quot;]</pre><p>The map() method returns a new array and it does not change the original array , it help us to transform data into a new format and it provide chainability i.e we can attach more method to it .</p><h3>5 . The filter() Method</h3><p>JS Array.prototype.filter() method creates a new array containing all elements form the original array that pass a specific test implemented by a provided callback function , It does not mutate the original array .</p><ul><li>Syntax : filter(callbackFn)</li></ul><p>The Callback Parameters :The callback function executes for every element and accepts three arguments.</p><ul><li>element : The current item being processed .</li><li>index : The index of the current item and it is optional .</li><li>array : The original array being iterated and this is optional as well .</li></ul><pre>const numbers = [5, 12, 8, 130, 44];<br><br>const bigNumbers = numbers.filter(num =&gt; num &gt; 10);<br><br>console.log(bigNumbers); <br>// Output: [12, 130, 44]</pre><p>As we can see the above example is of basic number filtering and it filter an array to keep only numbers greater than 10 .</p><p>Now we can say that the filter() method returns a new array of all matching elements and returns an empty array [] if no matches are found .</p><h3>6 . The Reduce Method</h3><p>The Array.prototype.reduce() method in JS executes a user-supplied “reducer” callback function on each element of an array to calculate and return a single accumulated value . It passes the return value from the calculations on the preceding element to the next iteration , effectively “reducing” the array down to one result .</p><ul><li>Syntax :</li></ul><pre>array.reduce(( accumulator , currentValue , currentIndex , array ) =&gt; {<br><br>// some code here <br><br>return accumulator ;<br>}, initialValue);</pre><ul><li>accumulator : It is the callback’s return value . It is the accumulated result from the previous iteration .</li><li>currentValue : The current element being processed in the array .</li><li>currentIndex : The index of the current element being processed and it is optional .</li><li>array : The original array upon which reduce() was called .</li><li>initialValue : The value to use as the first argument to the first call of the callback .</li><li>The return value of that results from running the “reducer” callback function to completion over the entire array .</li></ul><pre>const numbers = [10, 20, 30, 40];<br><br>const totalSum = numbers.reduce((accumulator, currentValue) =&gt; {<br>  return accumulator + currentValue;<br>}, 0); // initialValue is 0<br><br>console.log(totalSum); // Output: 100</pre><p>The above eg is the most common use case i.e summing an array of numbers .</p><pre>const fruits = [&#39;apple&#39;, &#39;banana&#39;, &#39;apple&#39;, &#39;orange&#39;, &#39;banana&#39;, &#39;apple&#39;];<br><br>const fruitCount = fruits.reduce((accumulator, fruit) =&gt; {<br>  // If the fruit exists in the object, increment it; otherwise, set it to 1<br>  accumulator[fruit] = (accumulator[fruit] || 0) + 1;<br>  return accumulator;<br>}, {}); // initialValue is an empty object<br><br>console.log(fruitCount); <br>// Output: { apple: 3, banana: 2, orange: 1 }</pre><p>We can use an empty object {} as the initialValue to map and count items inside an array .</p><h3>7 . The forEach() Method</h3><p>The forEach() method in JS executes a provided callback function once for every element in an array . It is primarily used to trigger side effects such as logging data , modifying external variables or updating DOM elements rather than creating new arrays .</p><p>Syntax :</p><pre>array.forEach(( element , index , array ) =&gt; {<br>// some code here <br>});</pre><p>The callback function can accept up to three arguments in this strict order .</p><p>element : The current item being processed .</p><p>index : The index number of the current item .</p><p>array : The entire array that forEach() was called on .</p><pre>const fruits = [&#39;apple&#39;, &#39;banana&#39;, &#39;cherry&#39;];<br><br>fruits.forEach(fruit =&gt; console.log(fruit));<br>// Output:<br>// apple<br>// banana<br>// cherry</pre><p>Note : A loop is a general tool to repeat any code . A map transforms every item in a list to make a new list of the same size . A filter checks items and keeps only the one that pass a test , making a new list that can be smaller .</p><h3>8 . Conclusion</h3><p>JavaScript array methods are one of the most powerful tools for working with collections of data. From adding and removing elements with push(), pop(), shift(), and unshift() to transforming and filtering data with map(), filter(), and reduce(), these methods can make your code cleaner, shorter, and easier to understand.</p><p>You don’t need to memorize every method at once. Start with the commonly used ones, understand <strong>when and why</strong> to use them, and gradually explore the rest as you build projects.</p><p>The more you work with arrays, the more naturally these methods will become part of your JavaScript toolkit.</p><p>Keep practicing , keep building and keep exploring !!!!!!</p><p>Please share your feedback with us !!!!</p><p>Thank You 😀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=41ecf1e2ddd6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Arrays in JavaScript: Store More, Do More]]></title>
            <link>https://medium.com/@anshultrip1234/arrays-in-javascript-store-more-do-more-85c83ae67f08?source=rss-ebcb3975b6e4------2</link>
            <guid isPermaLink="false">https://medium.com/p/85c83ae67f08</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[javascript-array-methods]]></category>
            <category><![CDATA[arrays]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Anshul tripathi]]></dc:creator>
            <pubDate>Sat, 08 Aug 2026 06:05:10 GMT</pubDate>
            <atom:updated>2026-08-08T06:05:10.097Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*drD1n4_kKcDsNVVKjQzE-g.png" /></figure><h3>1 . Introduction</h3><p>Imagine we need to store the names of 10 students , a list of products , or the scores of multiple players . Creating a separate variable for every value would quickly become messy and difficult to manage . This is where arrays come in picture. IN JS , an array allow us to store multiple values in a single variable and work with them efficiently . Whether we’re handling a list of users , managing items in a shopping cart, storing API data or solving DSA problems , arrays are one of the most commonly used data structures .</p><p>In this blog we’ll explore JS arrays , how to create and access them , modify their contents , use common array methods and understand some of the concepts that make arrays so powerful.</p><h3>2. What are arrays and why do we need them ?</h3><p>In Js , an array is an <strong>ordered collection </strong>of values stored inside a single variable . Instead of holding just one piece of information an array acts like a list container that can hold multiple numbers , strings , objects or even other arrays .</p><p>Without arrays , managing data sets becomes incredibly chaotic . We need them for several critical reasons :-</p><ul><li><strong>Preventing Variable Pollution</strong> : If we need to store a list of 50 students , names creating 50 separate variables ( student 1 , student2 , etc). is incredibly messy and inefficient . An array keeps our global environment clean by grouping related data into one place.</li><li><strong>Efficient Data looping and Iteration</strong> : Because arrays are ordered by numerical indexes , we can write a single loop to process thousands of items in just a few lines of code .</li></ul><pre>let prices = [10,23,12,40];<br><br>for(let i = 0 ; i &lt; prices.length ;i++){<br>prices[i] = prices[i] * 2 ;<br> }<br></pre><ul><li><strong>Access to Powerful Built-in Methods</strong> : JS arrays come packed with native prototypes methods that make data manipulation fast and readable , We don’t have to write complex logic from scratch , we can use built-in tools instead .</li></ul><h3>3. How to create an Array in JS</h3><p>There are many ways to create an array in JS , the most common way to create an array in JS is by using array literal syntax with square brackets [] .</p><ol><li><strong>Using Array Literals </strong>: This is the simplest , most readable and most efficient method . We could simply enclose a comma-separated list of values inside square brackets [] .</li></ol><pre>//Creating an empty array <br><br>const emptyArr = [];<br><br>//Creating an Array with elements <br><br>const fruits = [&quot;Mango&quot; , &quot;Banana&quot; , &quot;Orange&quot;];<br><br>//Creating an array with mix data types <br>const mixedArray = [ 42 , &#39;Hello&#39; , true , {name:&quot;John&quot;}]:<br><br></pre><p>2.<strong> Using the </strong><strong>Array() Constructor</strong> : We can call the built-in Array global object constructor . We can use it with or without the new keyword .</p><ul><li>With elements : Passing multiple arguments initialises the array with those elements.</li><li>With a single number : Passing a single number creates an empty array with that specific length called a sparse array.</li></ul><pre>// Creating an array with elements<br>const colors = new Array(&#39;Red&#39;, &#39;Green&#39;, &#39;Blue&#39;);<br><br>// Creating an empty array with a length of 5 <br>const emptySlots = new Array(5);</pre><p>3. Using Static Factory Methods : Modern JS offers dedicated static methods on the Array object for specific creation use cases .</p><ul><li>Array.of() : Creates an array from its argument . Unlike the constructor , Array.of(5) will creates an array with one element [5] instead of 5 empty slots .</li><li>Array.from() : Creates an array from an array-like or iterable object (like a NodeList , set or string ) .</li></ul><pre>// Using Array.of()<br>const numbers = Array.of(1, 2, 3); // [1, 2, 3]<br><br>// Using Array.from() to turn a string into an array of characters<br>const chars = Array.from(&#39;Hello&#39;); // [&#39;H&#39;, &#39;e&#39;, &#39;l&#39;, &#39;l&#39;, &#39;o&#39;]</pre><h3>4 . Accessing elements using index</h3><p>To access an element in an array , we can use square brackets ( [] ) with the index of the elements we want to access , the index starts at 0 for the first element in the array and increments by 1 for each subsequent element</p><p>example of how to access elements in an array in Js :</p><pre>const fruits = [&#39;apple&#39;, &#39;banana&#39;, &#39;orange&#39;, &#39;grape&#39;];<br><br>// Access the first element<br>const firstFruit = fruits[0];<br>console.log(firstFruit); // Output: &quot;apple&quot;<br><br>// Access the third element<br>const thirdFruit = fruits[2];<br>console.log(thirdFruit); // Output: &quot;orange&quot;</pre><p>In this eg , we have an array of fruits and we use square brackets with the index of the element we want to access to assign the value of the first and third elements to varialbes .</p><h3>5. Updating the Elements</h3><p>To update an element in JS array , we can either mutate the original array directly or return a new modified array without changing the original ( non-mutating/ immutable approach) .</p><p>The most common , direct way to update an array element is by assigning a new value using its index brackets (array[index] = newValue) .</p><ol><li><strong>Mutating Approaches ( Modifies the original Array </strong>)</li></ol><ul><li>By direct Index Assignment : Access the specific position using brackets notation and reassign it .</li></ul><pre>let fruits = [&#39;apple&#39;, &#39;banana&#39;, &#39;cherry&#39;];<br>fruits[1] = &#39;blueberry&#39;; <br><br>console.log(fruits); // [&#39;apple&#39;, &#39;blueberry&#39;, &#39;cherry&#39;]</pre><ul><li>Using splice() : The splice() method targets an index , removes a set number of items , and replaces them.</li></ul><pre>let numbers = [10, 20, 30];<br>// syntax: splice(startIndex, deleteCount, newItem)<br>numbers.splice(1, 1, 99); <br><br>console.log(numbers); // [10, 99, 30]</pre><ul><li>Using loops ( forEach or for ) : Useful when we need to update all elements or find elements that match a dynamic condition .</li></ul><pre>let scores = [5, 12, 8, 15];<br>scores.forEach((value, index) =&gt; {<br>  if (value &lt; 10) {<br>    scores[index] = value * 2; // Double numbers less than 10<br>  }<br>});<br><br>console.log(scores); // [10, 12, 16, 15]</pre><p>2 . Non-Mutating Approaches ( Returns a New Array)</p><ul><li>Using Map() : Transforms elements safely by returning an updated copy of the array based on a condition</li></ul><pre>const initialList = [&#39;red&#39;, &#39;green&#39;, &#39;blue&#39;];<br>const updatedList = initialList.map(item =&gt; item === &#39;green&#39; ? &#39;emerald&#39; : item);<br><br>console.log(updatedList); // [&#39;red&#39;, &#39;emerald&#39;, &#39;blue&#39;]<br>console.log(initialList); // [&#39;red&#39;, &#39;green&#39;, &#39;blue&#39;] (Unchanged)</pre><ul><li>Using with() : A modern JS alternative to bracket assignment that produces a new copy . It accepts positive indices or negative indices to count backwards from the end .</li></ul><pre>const items = [&#39;A&#39;, &#39;B&#39;, &#39;C&#39;, &#39;D&#39;];<br>const newItems = items.with(2, &#39;Z&#39;); // Replaces index 2<br><br>console.log(newItems); // [&#39;A&#39;, &#39;B&#39;, &#39;Z&#39;, &#39;D&#39;]</pre><p>3. Updating an Array of Objects : When elements are structured objects combine findIndex() or Map() to locate and modify targeted keys .</p><pre>let users = [<br>  { id: 1, name: &#39;Alice&#39;, active: false },<br>  { id: 2, name: &#39;Bob&#39;, active: false }<br>];<br><br>// Option A: Mutating with findIndex<br>const index = users.findIndex(u =&gt; u.id === 2);<br>if (index !== -1) users[index].active = true;<br><br>// Option B: Non-mutating with map<br>const updatedUsers = users.map(user =&gt; <br>  user.id === 2 ? { ...user, active: true } : user<br>);</pre><p>These are the few common ways to update the array in JS .</p><h3>6 . Array length Property</h3><p>In Js length property returns or sets the total number of elements slots inside an array instance . It is a live property that automatically stays synchronised with the array’s content , and its value is always strictly greater than the highest numerical index used in the array .</p><p>Reading the Length</p><p>Because Js arrays use zero-based indexing , the length of an array is always one number higher than the index of the final element . We can access it directly without using parentheses .</p><pre>const fruits = [&#39;apple&#39;, &#39;banana&#39;, &#39;cherry&#39;];<br>console.log(fruits.length); // Outputs: 3<br><br>// Accessing the last item<br>const lastItem = fruits[fruits.length - 1]; <br>console.log(lastItem); // Outputs: &#39;cherry&#39;</pre><p>Modifying the length</p><p>Unlike many programming languages where array sizes are fixed , Js allows us to rewrite the length property directly to modify our array structure .</p><ul><li>Truncating an array : Assigning a lower value than the current length permanently deletes elements beyond that threshold .</li><li>Clearing an array : Setting the property to 0 completely empties the array instantly .</li><li>Extending an array : Assigning a higher value expands the array layout by creating empty slots , rather than filling them with actual undefined values .</li></ul><pre>const numbers = [10, 20, 30, 40, 50];<br><br>// Truncate<br>numbers.length = 3;<br>console.log(numbers); // [10, 20, 30]<br><br>// Extend<br>numbers.length = 5;<br>console.log(numbers); // [10, 20, 30, &lt;2 empty items&gt;]<br><br>// Clear completely<br>numbers.length = 0;<br>console.log(numbers); // []</pre><h3>7. Conclusion</h3><p>Arrays are one of the most fundamental and useful data structures in JavaScript. They allow you to store multiple values in a single variable and provide a wide range of methods to add, remove, search, transform, and manipulate data efficiently.</p><p>In this blog we have explored the arrays and their some common methods , we have also seen that how we can modify , update and access different values from the array using different methods provided by the JS .</p><p>If you’re just getting started, don’t try to memorize every array method. Instead, practise using them and understand <strong>when and why</strong> you would use each one.</p><p>Till then keep building and keep exploring !!!!!!!</p><p>Please share your feedback with us</p><p>Thank you !!!!!😀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=85c83ae67f08" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Control Flow in JavaScript: Make Better Decisions with if and switch]]></title>
            <link>https://medium.com/@anshultrip1234/control-flow-in-javascript-make-better-decisions-with-if-and-switch-6d45fcaafb26?source=rss-ebcb3975b6e4------2</link>
            <guid isPermaLink="false">https://medium.com/p/6d45fcaafb26</guid>
            <category><![CDATA[switch-statement]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[control-flow-statement]]></category>
            <dc:creator><![CDATA[Anshul tripathi]]></dc:creator>
            <pubDate>Tue, 28 Jul 2026 20:29:52 GMT</pubDate>
            <atom:updated>2026-07-28T20:29:52.727Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K0mP0bZcjiaZiXKuObsFtQ.png" /></figure><h3>1. Introduction</h3><p>Imagine we want to go outside and need to decide what to wear , you check the weather and make the choices step by step .</p><ul><li>The check : We look out the window to see is it raining .</li><li>First Choice : If it is raining , we’ll grab an umbrella and a raincoat.</li><li>Alternative : If it is not raining , we’ll skip the umbrella and wear a light cloth .</li><li>The End : We walk out the door .</li></ul><p>Every Program needs to make decisions , whether it’s checking if a user is logged in , validating a password , decision-making is a fundamental part of programming . In this blog we’ll learn how to JS if , else-if , else and switch statement to write smarter , more efficient code .</p><h3>2. What control flow means in programming</h3><p>Control flow is the order in which individual statements , instructions or function calls are executed or evaluated in a computer program . By default a computer executes code sequentially from top to bottom ,one line at a time. Control flow structures break this default linear path , allowing the program to make decisions , repeat tasks or skip specific blocks of code based on changing conditions .</p><p>Core Types of Control Flow :</p><p>Programming languages achieve dynamic behaviour through three foundational control flow structures .</p><ol><li>Sequential Flow : Code runs exactly in the order it is written , from the first line down to the last line . Eg- Setting a variable name, adding to it, and then printing the result .</li><li>Conditional Flow ( Decision making ) : The program evaluates a boolean expression ( true or false ) and chooses a path based on the outcome .</li></ol><ul><li>if / else if / else : Executes a block of code only if a specific condition is met , for eg- checking if a user’s age is greater than 18 to grant access .</li><li>switch / case : Evaluates a single variable against multiple potential values , acting like a cleaner alternative to complex if-else chains .</li></ul><p>3. Iterative flow (loops ) : Loops instruct the program to repeat a specific block of code multiple times until a predefined condition changes . eg- for while and do-while .</p><p>4. Advanced Control Flow Mechanisms : Beyond basic conditionals and loops , advanced tools let us aggressively redirect or manage execution .</p><p>Jump Statements:</p><ul><li>break: Immediately exits out of the current loop or switch block.</li><li>continue: Skips the remainder of the current loop iteration and jumps straight to the next one.</li><li>return: Halts execution inside a function and hands a value back to the code that called it.</li><li><strong>Exception Handling (</strong><strong>try / </strong><strong>catch):</strong> Diverts the standard flow of execution when an unexpected error occurs, preventing the program from crashing by routing control to a dedicated error-handling block.</li><li><strong>Function Calls:</strong> Pauses the execution of the current code block to jump over to a specific sub-program, executes that code, and then returns right back to where it left off.</li></ul><p>Without control flow , computer programs would be entirely rigid and incapable of handling real-world complexity . Control flow gives software the power to interact dynamically with user .</p><h3>3. The if statement</h3><p>An if statement in JS executes a block of code only if a specified condition evaluates to true or a “ truthy ” value. It is the most fundamental control structure used to make decisions and direct the flow of our program .</p><p><strong>Basic syntax :</strong></p><p>The keyword if is followed by a condition in parentheses and the code to execute is placed inside curly braces {} .</p><pre>let score = 21; <br>if(score &gt;= 20) {<br>console.log(&quot;You passed!&quot;):<br>}</pre><p><strong>Truthiness</strong>: JavaScript automatically converts the values inside the parentheses to a boolean. Values like 0, &quot;&quot; (empty string), null, undefined, and NaN are treated as falsy, while most other values are truthy.</p><h3>4. The if-else statement</h3><p>An if-else statement is a fundamental programming control structure that allows a computer to make decisions by executing one block of code if a condition is true and a different block if it is false . It forms the backbone of logic in software development, controlling how programs react to different inputs .</p><p>How it works :</p><ol><li>The program evaluates a conditional expression ( which results in a boolean true or false ).</li><li>If the condition is true , the code inside the if block executes and the else block is completely skipped .</li><li>If the condition is false , the code inside the if block is skipped and the code inside the else block executes .</li></ol><pre>let score = 75;<br><br>if (score &gt;= 90) {<br>    console.log(&quot;Grade: A&quot;);<br>} else {<br>    console.log(&quot;Grade: B&quot;);<br>}</pre><h3>5. The else if ladder</h3><p>An else if ladder in JS is a control structure used to test multiple conditions in sequence . It executes exactly one block of code corresponding to the first condition that evaluates to true , skipping all subsequent checks.</p><p>How it works :</p><ul><li>Top-to-bottom execution : JS evaluates conditions sequentially starting from the top .</li><li>Short-Circuit Behaviour : The moment a condition is met , its code block runs and the engine immediately exits the entire ladder .</li><li>Optional Catch-all : The final else block acts as a fallback and only runs if every single ifand else if condition evaluates to false .</li></ul><pre>let number = -5;<br><br>if(number &gt; 0 ) {<br>console.log(&quot;Positive&quot;);<br>}<br>else if(number &lt; 0 ){<br>console.log(&quot;Negative&quot;); // Output : &quot;Negative&quot;<br>}<br>else{<br>conosle.log(&quot;zero&quot;);<br>}</pre><h3>6. The switch statement</h3><p>The JS switch statement evaluates an expression and executes a code block associated with a matching case value. It is used as a cleaner , more readable alternative to multi-line if...else if chains when comparing a single value against multiple options .</p><p>Basic Syntax :</p><pre>switch (expression) {<br>  case value1:<br>    // Code runs if expression === value1<br>    break;<br>  case value2:<br>    // Code runs if expression === value2<br>    break;<br>  default:<br>    // Code runs if no cases match<br>}</pre><p>Core components</p><ul><li>Expression : The main value or variable evaluated once at the start .</li><li>Case : A targeted value checked against the expression .</li><li>Strict Equality ( === ) : Comparisons always use strict evaluation. This means matching requires both the same data type and values ( eg 5 will not &quot;5&quot; ).</li><li>Break : Exits the statement immediately after a match .</li><li>default : A fallback block that triggers if no case matches , acting like a final else statement .</li></ul><pre>const day = prompt(&quot;enter the number&quot;);<br><br>switch (day) {<br>case &quot;1&quot; : <br>console.log(&quot;Monday&quot;); <br>break;<br><br>case &quot;2&quot;:<br>console.log(&quot;Tuesday&quot;);<br>break;<br><br>case &quot;3&quot;:<br>console.log(&quot;Wednesday&quot;);<br>break;<br><br>case &quot;4&quot;: <br>console.log(&quot;Thursday&quot;);<br>break; <br><br>case &quot;5&quot;: <br>console.log(&quot;Friday&quot;);<br>break;<br><br>case &quot;6&quot;: <br>console.log(&quot;Saturday&quot;);<br>break;<br><br>case &quot;7&quot;: <br>console.log(&quot;Sunday&quot;);<br>break;<br><br>default: <br>conosle.log(&quot;haha, Pls enter a valid number&quot;);<br>}</pre><h3>7. When to use switch vs if-else</h3><p>Use switch statement when we need to compare a single variable against multiple discrete , constant values . Use an if-else statement when evaluating complex boolean logic , ranges of values , or multiple unrelated variables .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hDqW-2niROZIIz7iDH43dg.png" /></figure><p>Lastly , implement whichever design is clearer and more maintainable as per the demand of your code . If you are landing in a huge switch-case or if-else block , switch to other techniques like polymorphism , Just find out the behaviour of the object and try to encapsulate it if possible .</p><h3>8. Conclusion</h3><p>Control flow is one of the core concepts of JS because it determines how our code makes decisions and execute different path based on specific conditions. By understanding if, else-if , else and switch statements , we can write cleaner, more efficient and more readable programs .</p><p>This blog covered the fundamentals of JS control flow but there’s still much more to explore . In the upcoming blogs , we’ll dive into nested conditional statements , the ternary operator and other advanced control flow techniques that will help you write even more concise and powerful code .</p><p>Until then , keep experimenting and keep building !!!</p><p>Please share your feedback !!!!!</p><p>Thank You 😀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6d45fcaafb26" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>