<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Jyoti chaudhary</title>
    <description>The latest articles on DEV Community by Jyoti chaudhary (@jyotich15).</description>
    <link>https://dev.to/jyotich15</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1405011%2F8fbe4659-cb68-4aac-9ccf-de684af03b5f.jpg</url>
      <title>DEV Community: Jyoti chaudhary</title>
      <link>https://dev.to/jyotich15</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/jyotich15"/>
    <language>en</language>
    <item>
      <title>How Hoisting works internally?</title>
      <dc:creator>Jyoti chaudhary</dc:creator>
      <pubDate>Wed, 04 Feb 2026 12:39:22 +0000</pubDate>
      <link>https://dev.to/jyotich15/how-hoisting-works-internally-pml</link>
      <guid>https://dev.to/jyotich15/how-hoisting-works-internally-pml</guid>
      <description>&lt;h1&gt;
  
  
  🔹What is Hoisting?
&lt;/h1&gt;

&lt;p&gt;Hoisting is JavaScript's default behavior of moving declarations to the top of their scope during the memory creation phase, before code execution.&lt;/p&gt;

&lt;h1&gt;
  
  
  🔹How Hoisting Works Internally
&lt;/h1&gt;

&lt;p&gt;JS code runs in two phases:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. Memory Creation Phase (Hoisting happens here)&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;During the memory creation phase, JavaScript parses the code and allocates memory for variable and function declarations, storing them inside the execution context before code execution begins.&lt;/p&gt;

&lt;p&gt;Or &lt;/p&gt;

&lt;p&gt;In simple terms, JavaScript scans the code and then allocates memory for variables, functions etc and then stores them in memory.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;JS scans the code&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Allocates memory for:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt; Variables&lt;/li&gt;
&lt;li&gt; Functions&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;li&gt;&lt;p&gt;Stores them in memory&lt;/p&gt;&lt;/li&gt;

&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;2. Execution Phase&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;Code runs line by line&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Assignments happen&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Functions are executed&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;




&lt;h1&gt;
  
  
  🔹Types of Hoisting in JavaScript
&lt;/h1&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;var hoisting&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;let hoisting&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;const hoisting&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Function declaration hoisting&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Function expression hoisting&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Class hoisting&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;1&lt;/strong&gt;. var Hoisting (Fully Hoisted)&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;console.log(a);
var a = 10;

Internal:
var a; // undefined
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;✔ Declaration is hoisted&lt;br&gt;
✔ Initialized with undefined&lt;/p&gt;



&lt;p&gt;&lt;strong&gt;2&lt;/strong&gt;. let and const Hoisting (Hoisted but NOT initialized)&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;console.log(b);
let b = 20;

Error:
ReferenceError: Cannot access 'b' before initialization

---

console.log(c);
const c = 30;
❌ Error:

ReferenceError: Cannot access 'c' before initialization
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;let and const is hoisted, But placed in Temporal Dead Zone (TDZ)&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;🔥 Temporal Dead Zone (TDZ)&lt;br&gt;
TDZ = time between: entering scope and variable initialization&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// TDZ starts
console.log(b); // ❌ error
let b = 20;
// TDZ ends
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;blockquote&gt;
&lt;p&gt;let is hoisted but not initialized, and accessing it before declaration causes a ReferenceError due to TDZ.&lt;/p&gt;
&lt;/blockquote&gt;




&lt;p&gt;&lt;strong&gt;3&lt;/strong&gt;. Function Declaration Hoisting (Fully Hoisted)&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;sayHello();

function sayHello() {
  console.log("Hello!");
}

Internally:
sayHello → function reference
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;p&gt;&lt;strong&gt;4&lt;/strong&gt;. Function Expression Hoisting&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;sayHi();

var sayHi = function () {
  console.log("Hi");
};

TypeError: sayHi is not a function
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;Why?&lt;br&gt;
-&amp;gt; sayHi is hoisted as undefined&lt;br&gt;
-&amp;gt; Calling undefined() ❌&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;sayHi();
const sayHi = function () {
  console.log("Hi");
};

ReferenceError (TDZ)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;blockquote&gt;
&lt;p&gt;Only function declarations are fully hoisted, not function expressions.&lt;/p&gt;
&lt;/blockquote&gt;




&lt;h1&gt;
  
  
  🔹Execution Context
&lt;/h1&gt;

&lt;p&gt;When JavaScript runs your code, it does &lt;strong&gt;not&lt;/strong&gt; execute it line by line immediately.&lt;/p&gt;

&lt;p&gt;It does &lt;strong&gt;two phases&lt;/strong&gt; for every execution context:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Memory Creation Phase (also called &lt;em&gt;Creation / Hoisting phase&lt;/em&gt;)&lt;/li&gt;
&lt;li&gt;Execution Phase&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;What is an Execution Context?&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Execution Context = an environment where JavaScript code is evaluated and executed&lt;/em&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Think of it like a &lt;strong&gt;box&lt;/strong&gt; created by JS to run code.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Each execution context contains &lt;strong&gt;two main things&lt;/strong&gt;:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Memory (Variable Environment) ⇒ Variables + Functions stored here&lt;/li&gt;
&lt;li&gt;Code (Thread of Execution) ⇒ Code executes line by line&lt;/li&gt;
&lt;/ol&gt;




&lt;h4&gt;
  
  
  👉 Types of Execution Context
&lt;/h4&gt;

&lt;ol&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Global Execution Context (GEC)&lt;/strong&gt;&lt;br&gt;
– Created when the program starts&lt;br&gt;
– Only one&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;strong&gt;Function Execution Context (FEC)&lt;/strong&gt;&lt;br&gt;
– Created each time a function is called&lt;/p&gt;&lt;/li&gt;
&lt;/ol&gt;




&lt;h4&gt;
  
  
  👉 Memory Component Stores
&lt;/h4&gt;

&lt;p&gt;During &lt;strong&gt;memory creation phase&lt;/strong&gt;:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Variables&lt;/li&gt;
&lt;li&gt;Function declarations&lt;/li&gt;
&lt;li&gt;Function parameters&lt;/li&gt;
&lt;li&gt;Scope references&lt;/li&gt;
&lt;/ul&gt;




&lt;h4&gt;
  
  
  👉 Where This Memory Lives Physically?
&lt;/h4&gt;

&lt;p&gt;Stack = &lt;em&gt;where execution happens&lt;/em&gt;&lt;br&gt;
Heap = &lt;em&gt;where data lives&lt;/em&gt;&lt;/p&gt;
&lt;h5&gt;
  
  
  Heap Memory
&lt;/h5&gt;

&lt;ul&gt;
&lt;li&gt;Large and unstructured&lt;/li&gt;
&lt;li&gt;Stores:

&lt;ul&gt;
&lt;li&gt;Objects&lt;/li&gt;
&lt;li&gt;Functions&lt;/li&gt;
&lt;li&gt;Closures&lt;/li&gt;
&lt;li&gt;Complex data&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;h5&gt;
  
  
  Stack Memory
&lt;/h5&gt;

&lt;ul&gt;
&lt;li&gt;Fast and LIFO ordered&lt;/li&gt;
&lt;li&gt;Stores:

&lt;ul&gt;
&lt;li&gt;Execution contexts&lt;/li&gt;
&lt;li&gt;Primitive values (often)&lt;/li&gt;
&lt;li&gt;References (addresses) to heap&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ul&gt;


&lt;h4&gt;
  
  
  👉 Who Gives This Memory?
&lt;/h4&gt;
&lt;h6&gt;
  
  
  JavaScript Engine
&lt;/h6&gt;

&lt;p&gt;Examples:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;V8 (Chrome, Node.js)&lt;/li&gt;
&lt;li&gt;SpiderMonkey (Firefox)&lt;/li&gt;
&lt;li&gt;JavaScriptCore (Safari)&lt;/li&gt;
&lt;/ul&gt;
&lt;h6&gt;
  
  
  The JS Engine:
&lt;/h6&gt;

&lt;ul&gt;
&lt;li&gt;Allocates memory&lt;/li&gt;
&lt;li&gt;Manages memory&lt;/li&gt;
&lt;li&gt;Frees memory (Garbage Collection)&lt;/li&gt;
&lt;/ul&gt;


&lt;h4&gt;
  
  
  🔹 Internally What Happens?
&lt;/h4&gt;

&lt;p&gt;When JS runs:&lt;/p&gt;
&lt;h5&gt;
  
  
  Step 1 → Engine creates Execution Context
&lt;/h5&gt;
&lt;h5&gt;
  
  
  Step 2 → Allocates memory for variables/functions
&lt;/h5&gt;
&lt;h5&gt;
  
  
  Step 3 → Runs code
&lt;/h5&gt;


&lt;h5&gt;
  
  
  🔥 Real Flow
&lt;/h5&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Browser / Node
   ↓
JavaScriptEngine(V8 etc.)
   ↓
Creates Execution Context
   ↓
AllocatesMemory(Hoisting Phase)
   ↓
Executes Code
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;h5&gt;
  
  
  Example:
&lt;/h5&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var a = 10;
let b = 20;
const c = 30;

function add(x, y) {
  var sum = x + y;
  return sum;
}

let result = add(2, 3);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;STEP 1. Global Execution Context (GEC) is created&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;GEC is pushed into the CALL STACK&lt;/li&gt;
&lt;li&gt;Memory Creation Phase (inside GEC)&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;🔹What goes to STACK memory?&lt;/p&gt;
&lt;h6&gt;
  
  
  Primitive variables
&lt;/h6&gt;


&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var a;
let b;
const c;
let result;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;Stored in &lt;strong&gt;stack memory&lt;/strong&gt; (inside GEC):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;a      → undefined
b      →&amp;lt;uninitialized&amp;gt;
c      →&amp;lt;uninitialized&amp;gt;
result →&amp;lt;uninitialized&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;🔹 What goes to HEAP memory?&lt;/p&gt;

&lt;h6&gt;
  
  
  Function declaration
&lt;/h6&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;functionadd(x, y) { ... }

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Function &lt;strong&gt;object&lt;/strong&gt; is stored in &lt;strong&gt;heap&lt;/strong&gt;
&lt;/li&gt;
&lt;li&gt;Stack stores &lt;strong&gt;reference (address)&lt;/strong&gt; to it
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;STACK (GEC)           HEAP
─────────────        ─────────────
add  →0x123  ───▶function add(){...}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;STEP 2: Execution Phase starts&lt;/p&gt;

&lt;p&gt;All primitives → &lt;strong&gt;stored directly in STACK&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;STACK
a →10
b →20
c →30
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;STEP 3: Function call happens&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let result =add(2,3);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;🔹What happens internally?&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;New &lt;strong&gt;Function Execution Context (FEC)&lt;/strong&gt; created&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;Pushed into &lt;strong&gt;CALL STACK&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;CALL STACK
────────────
|  FEC(add)|
|    GEC|
────────────
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;h5&gt;
  
  
  🔹 Function Execution Context Memory
&lt;/h5&gt;

&lt;h6&gt;
  
  
  Parameters &amp;amp; local variables
&lt;/h6&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;x =2
y =3
sum =undefined
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;All are &lt;strong&gt;primitives → STACK&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;STACK (FEC)
x   →2
y   →3
sum → undefined
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h6&gt;
  
  
  Execution inside function
&lt;/h6&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;sum = x + y;// 5
return sum;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;sum&lt;/code&gt; becomes &lt;code&gt;5&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;Value returned to global context&lt;/li&gt;
&lt;/ul&gt;

&lt;h6&gt;
  
  
  Function ends
&lt;/h6&gt;

&lt;p&gt;❌ Function Execution Context is &lt;strong&gt;popped from stack&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;CALL STACK
──────────
|  GEC   |
──────────

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h6&gt;
  
  
  Returned value assigned:
&lt;/h6&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;result → 5   (STACK)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






</description>
      <category>webdev</category>
      <category>javascript</category>
      <category>tutorial</category>
      <category>react</category>
    </item>
    <item>
      <title>Basic Coding Interview Questions ( 2025 )</title>
      <dc:creator>Jyoti chaudhary</dc:creator>
      <pubDate>Tue, 29 Apr 2025 09:52:28 +0000</pubDate>
      <link>https://dev.to/jyotich15/basic-coding-interview-questions-2025--2pld</link>
      <guid>https://dev.to/jyotich15/basic-coding-interview-questions-2025--2pld</guid>
      <description>&lt;ol&gt;
&lt;li&gt;Reverse a String &lt;/li&gt;
&lt;li&gt;Check if a String is a Palindrome &lt;/li&gt;
&lt;li&gt;Remove Duplicates from a String &lt;/li&gt;
&lt;li&gt;Find the First Non-Repeating Character &lt;/li&gt;
&lt;li&gt;Count the Occurrences of Each Character &lt;/li&gt;
&lt;li&gt;Reverse Words in a Sentence &lt;/li&gt;
&lt;li&gt;Check if Two Strings are Anagrams &lt;/li&gt;
&lt;li&gt;Find the Longest Substring Without Repeating Characters &lt;/li&gt;
&lt;li&gt;Convert a String to an Integer &lt;/li&gt;
&lt;li&gt;Compress a String &lt;/li&gt;
&lt;li&gt;Find the Most Frequent Character &lt;/li&gt;
&lt;li&gt;Find All Substrings of a Given String &lt;/li&gt;
&lt;li&gt;Check if a String is a Rotation of Another String &lt;/li&gt;
&lt;li&gt;Remove All White Spaces from a String &lt;/li&gt;
&lt;li&gt;Check if a String is a Valid Shuffle of Two Strings &lt;/li&gt;
&lt;li&gt;Convert a String to Title Case &lt;/li&gt;
&lt;li&gt;Find the Longest Common Prefix &lt;/li&gt;
&lt;li&gt;Convert a String to a Character Array &lt;/li&gt;
&lt;li&gt;Replace Spaces with %20 (URL Encoding) &lt;/li&gt;
&lt;li&gt;Convert a Sentence into an Acronym &lt;/li&gt;
&lt;li&gt;Check if a String Contains Only Digits &lt;/li&gt;
&lt;li&gt;Find the Number of Words in a String &lt;/li&gt;
&lt;li&gt;Remove a Given Character from a String &lt;/li&gt;
&lt;li&gt;Find the Shortest Word in a String &lt;/li&gt;
&lt;li&gt;Find the Longest Palindromic Substring&lt;/li&gt;
&lt;/ol&gt;

</description>
      <category>javascript</category>
      <category>programming</category>
      <category>webdev</category>
      <category>beginners</category>
    </item>
    <item>
      <title>Q.1 How do you check if a variable is an array?</title>
      <dc:creator>Jyoti chaudhary</dc:creator>
      <pubDate>Sat, 05 Apr 2025 08:20:40 +0000</pubDate>
      <link>https://dev.to/jyotich15/q1-how-do-you-check-if-a-variable-is-an-array-399</link>
      <guid>https://dev.to/jyotich15/q1-how-do-you-check-if-a-variable-is-an-array-399</guid>
      <description>&lt;h4&gt;
  
  
  Using Array.isArray()
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;   let arr = [1, 2, 3];
   let notArray = "Hello";
   console.log(Array.isArray(arr));      // true
   console.log(Array.isArray(notArray));  // false
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Using instanceof Operator
&lt;/h4&gt;

&lt;p&gt;The instanceof operator can be used to check if a variable is an instance of Array.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let arr = [1, 2, 3];
let notArray = "Hello";
console.log(arr instanceof Array);      // true
console.log(notArray instanceof Array); // false
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Using constructor Property
&lt;/h4&gt;

&lt;p&gt;You can check the constructor property of an object, but this method is not as reliable because the constructor property can be modified.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let arr = [1, 2, 3];
let notArray = "Hello";
console.log(arr.constructor === Array);      // true
console.log(notArray.constructor === Array); // false
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;While this works in most cases, it's generally not recommended due to potential issues with modifying the constructor property.&lt;/p&gt;

&lt;h4&gt;
  
  
  Recommended Method:
&lt;/h4&gt;

&lt;p&gt;The best and most reliable way to check if a variable is an array in JavaScript is by using Array.isArray() because it is simple, clear, and works in all scenarios.&lt;/p&gt;

</description>
      <category>interview</category>
      <category>javascript</category>
      <category>programming</category>
      <category>webdev</category>
    </item>
    <item>
      <title>Promises in JavaScript</title>
      <dc:creator>Jyoti chaudhary</dc:creator>
      <pubDate>Tue, 04 Mar 2025 17:14:05 +0000</pubDate>
      <link>https://dev.to/jyotich15/promises-in-javascript-17dp</link>
      <guid>https://dev.to/jyotich15/promises-in-javascript-17dp</guid>
      <description>&lt;h3&gt;
  
  
  Promises:
&lt;/h3&gt;

&lt;p&gt;A promise in JavaScript is an object that represents the eventual completion (or failure) of an asynchronous operation and its resulting value. It acts as a placeholder for a value that will be available in the future, allowing you to handle asynchronous operations (like fetching data from an API or reading a file) in a more structured and manageable way.&lt;/p&gt;

&lt;p&gt;In simpler terms, a promise is like a contract: it promises to provide a result (either a success or failure) at some point in the future. Until then, it can be in one of three states:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Pending:&lt;/strong&gt; The initial state; the promise is still being processed.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Fulfilled:&lt;/strong&gt; The promise has been successfully resolved with a result (i.e., the asynchronous operation has completed successfully).&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Rejected:&lt;/strong&gt; The promise has been rejected due to an error or failure in the asynchronous operation.

&lt;/li&gt;
&lt;/ol&gt;

&lt;h3&gt;
  
  
  Why promises are used?
&lt;/h3&gt;

&lt;p&gt;Promises are used to make working with asynchronous code easier and more readable. Before promises, JavaScript relied on callbacks to handle asynchronous operations, which could lead to callback hell—a situation where callbacks are nested within each other, making the code hard to read and maintain.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Here are the main reasons promises are used:&lt;/strong&gt;&lt;/p&gt;

&lt;h5&gt;
  
  
  1. Cleaner Asynchronous Code (Avoid Callback Hell)
&lt;/h5&gt;

&lt;p&gt;Promises allow you to chain multiple asynchronous operations without nesting callbacks, making the code more readable and easier to manage. This helps avoid callback hell (deeply nested callbacks) that often results in complex and hard-to-debug code.&lt;/p&gt;

&lt;h6&gt;
  
  
  Example with Callbacks:
&lt;/h6&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;readFile('file1.txt', function(err, data1) {
    if (err) throw err;
    readFile('file2.txt', function(err, data2) {
        if (err) throw err;
        readFile('file3.txt', function(err, data3) {
            if (err) throw err;
            // Do something with data3
        });
    });
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h6&gt;
  
  
  Example with Promises:
&lt;/h6&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;readFile('file1.txt')
  .then(data1 =&amp;gt; readFile('file2.txt'))
  .then(data2 =&amp;gt; readFile('file3.txt'))
  .then(data3 =&amp;gt; {
    // Do something with data3
  })
  .catch(err =&amp;gt; console.error(err));  // Catch any error in the chain

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h5&gt;
  
  
  2. Better Error Handling
&lt;/h5&gt;

&lt;p&gt;With callbacks, errors need to be passed around manually, which can lead to confusion or missing error handling. Promises make it easy to handle errors using .catch(), and they also ensure that errors are propagated correctly through the chain of promises.&lt;/p&gt;

&lt;h6&gt;
  
  
  Example:
&lt;/h6&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;someAsyncOperation()
  .then(result =&amp;gt; {
    return anotherAsyncOperation(result);
  })
  .catch(err =&amp;gt; {
    // Handle error here
    console.error('Error:', err);
  });

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h5&gt;
  
  
  3. Handling Multiple Asynchronous Operations
&lt;/h5&gt;

&lt;p&gt;Promises provide tools like Promise.all() and Promise.race() that allow you to handle multiple asynchronous operations simultaneously, making it easier to work with parallel tasks.&lt;/p&gt;

&lt;h6&gt;
  
  
  Example with Promise.all():
&lt;/h6&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Promise.all([task1(), task2(), task3()])
  .then(results =&amp;gt; {
    // Handle results from all tasks
  })
  .catch(err =&amp;gt; {
    // Handle any error from any task
  });

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;Promise.all()&lt;/code&gt; waits for all promises to resolve before moving on. If any promise is rejected, it will reject immediately.&lt;/p&gt;

&lt;h5&gt;
  
  
  4. Composing Asynchronous Code
&lt;/h5&gt;

&lt;p&gt;Promises make it easier to compose multiple asynchronous operations in a sequence (using .then()) or in parallel (using Promise.all()), allowing you to build complex asynchronous workflows in a more maintainable way.&lt;/p&gt;

&lt;h6&gt;
  
  
  Example with .then() Chaining:
&lt;/h6&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fetchData()
  .then(processData)
  .then(saveData)
  .then(response =&amp;gt; console.log('Success:', response))
  .catch(error =&amp;gt; console.error('Error:', error));

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h5&gt;
  
  
  Basic Promise Example:
&lt;/h5&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let myPromise = new Promise((resolve, reject) =&amp;gt; {
  let success = true; // Simulate success or failure

  if (success) {
    resolve("Operation was successful!"); // If operation succeeds
  } else {
    reject("Operation failed!"); // If operation fails
  }
});

myPromise
  .then(result =&amp;gt; console.log(result))   // Handle success
  .catch(error =&amp;gt; console.log(error));   // Handle failure

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;h3&gt;
  
  
  Explain the difference between .then() and .catch() in promises.
&lt;/h3&gt;

&lt;p&gt;In JavaScript, .then() and .catch() are methods used to handle the resolution or rejection of promises, but they serve different purposes.&lt;/p&gt;

&lt;h5&gt;
  
  
  .then()
&lt;/h5&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;.then()&lt;/code&gt; is used to handle the successful resolution of a promise.&lt;/li&gt;
&lt;li&gt;It is called when the promise is fulfilled (i.e., it resolves with a value).&lt;/li&gt;
&lt;li&gt;It can take two arguments:

&lt;ol&gt;
&lt;li&gt;A callback function that is executed when the promise is resolved (fulfilled).&lt;/li&gt;
&lt;li&gt;An optional callback function that is executed if the promise is rejected (though it's usually better to use .catch() for handling rejections).
&lt;/li&gt;
&lt;/ol&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fetch('https://api.example.com/data')
  .then(response =&amp;gt; response.json())  // Handles success, processing the resolved value
  .then(data =&amp;gt; console.log(data))    // Handles another success case
  .catch(error =&amp;gt; console.error(error)); // Handles any rejection

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h5&gt;
  
  
  .catch()
&lt;/h5&gt;

&lt;ul&gt;
&lt;li&gt;.catch() is used to handle the rejection of a promise.&lt;/li&gt;
&lt;li&gt;It is called when the promise is rejected (i.e., it encounters an error).&lt;/li&gt;
&lt;li&gt;.catch() can be thought of as a shortcut for handling promise rejections. It is attached to the promise to deal with errors or exceptions.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fetch('https://api.example.com/data')
  .then(response =&amp;gt; response.json())
  .catch(error =&amp;gt; console.error('An error occurred:', error));  // Handles errors/rejections

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h5&gt;
  
  
  Key Differences:
&lt;/h5&gt;

&lt;h6&gt;
  
  
  1. Purpose:
&lt;/h6&gt;

&lt;ul&gt;
&lt;li&gt;.then() is for handling success (resolved promise).&lt;/li&gt;
&lt;li&gt;.catch() is for handling failure (rejected promise).&lt;/li&gt;
&lt;/ul&gt;

&lt;h6&gt;
  
  
  2. Chaining:
&lt;/h6&gt;

&lt;ul&gt;
&lt;li&gt;.then() returns a new promise, allowing you to chain multiple .then() calls.&lt;/li&gt;
&lt;li&gt;.catch() is typically used at the end of the chain to catch any errors that occurred earlier in the promise chain.&lt;/li&gt;
&lt;/ul&gt;

&lt;h6&gt;
  
  
  3. Error Handling:
&lt;/h6&gt;

&lt;ul&gt;
&lt;li&gt;.then() allows you to handle success and failure together, but .catch() is usually preferred for catching errors separately in a clean way.&lt;/li&gt;
&lt;/ul&gt;




&lt;h3&gt;
  
  
  What happens if you return a value inside .then()?
&lt;/h3&gt;

&lt;p&gt;It automatically wraps the value in a resolved promise, allowing further chaining.&lt;/p&gt;

&lt;h5&gt;
  
  
  1. Returning a non-promise value:
&lt;/h5&gt;

&lt;p&gt;If you return a regular value (e.g., a string, number, object) inside &lt;code&gt;.then()&lt;/code&gt;, that value is automatically wrapped in a resolved promise. This means the next &lt;code&gt;.then()&lt;/code&gt; in the chain will receive that value as the resolved value.&lt;/p&gt;

&lt;h5&gt;
  
  
  2. Returning a promise:
&lt;/h5&gt;

&lt;p&gt;If you return another promise inside &lt;code&gt;.then()&lt;/code&gt;, the next &lt;code&gt;.then()&lt;/code&gt; in the chain will wait for that promise to resolve and will receive the resolved value of the second promise.&lt;/p&gt;

&lt;h6&gt;
  
  
  Examples:
&lt;/h6&gt;

&lt;h6&gt;
  
  
  1. Returning a non-promise value
&lt;/h6&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let myPromise = new Promise((resolve, reject) =&amp;gt; {
  resolve('Hello');
});

myPromise
  .then(result =&amp;gt; {
    console.log(result); // Output: 'Hello'
    return 'World';     // This is returned as a normal value
  })
  .then(result =&amp;gt; {
    console.log(result); // Output: 'World' (received from previous .then())
  })
  .catch(error =&amp;gt; {
    console.log(error);
  });

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this case, the value 'World' is returned from the first &lt;code&gt;.then()&lt;/code&gt;, which is automatically wrapped in a resolved promise. The second &lt;code&gt;.then()&lt;/code&gt; receives 'World' as its argument.&lt;/p&gt;

&lt;h6&gt;
  
  
  2. Returning a promise:
&lt;/h6&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let myPromise = new Promise((resolve, reject) =&amp;gt; {
  resolve('Hello');
});

myPromise
  .then(result =&amp;gt; {
    console.log(result); // Output: 'Hello'
    return new Promise((resolve, reject) =&amp;gt; {
      setTimeout(() =&amp;gt; resolve('World'), 1000);
    });  // Returning a promise
  })
  .then(result =&amp;gt; {
    console.log(result); // Output: 'World' (after 1 second)
  })
  .catch(error =&amp;gt; {
    console.log(error);
  });

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this case, the first &lt;code&gt;.then()&lt;/code&gt; returns a &lt;code&gt;new promise&lt;/code&gt;. The second &lt;code&gt;.then()&lt;/code&gt; doesn’t execute until the new promise resolves, and once it does, it receives 'World' as the resolved value after 1 second.&lt;/p&gt;




&lt;h3&gt;
  
  
  How to handle multiple promises efficiently?
&lt;/h3&gt;

&lt;p&gt;In JavaScript, multiple promises can be handled in several ways depending on whether you want to handle the promises in &lt;code&gt;parallel&lt;/code&gt;, &lt;code&gt;sequentially&lt;/code&gt;, or &lt;code&gt;based on certain conditions&lt;/code&gt;.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Parallel execution&lt;/strong&gt; (use &lt;code&gt;Promise.all()&lt;/code&gt; or &lt;code&gt;Promise.allSettled()&lt;/code&gt;) when you want to run multiple independent promises at once.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;First result&lt;/strong&gt; wins (use &lt;code&gt;Promise.race()&lt;/code&gt; or &lt;code&gt;Promise.any()&lt;/code&gt;) when you care about the first promise to resolve or the first one that completes.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Sequential execution&lt;/strong&gt; (chain &lt;code&gt;.then()&lt;/code&gt; calls) when you need the promises to run one after another.&lt;/li&gt;
&lt;/ul&gt;

&lt;h5&gt;
  
  
  1. Promise.all() – Handle multiple promises in &lt;code&gt;parallel&lt;/code&gt;
&lt;/h5&gt;

&lt;p&gt;&lt;code&gt;Promise.all()&lt;/code&gt; takes an array of promises and returns a single promise. This new promise is resolved when all the promises in the array have been resolved (or it is rejected as soon as any of the promises is rejected).&lt;/p&gt;

&lt;h6&gt;
  
  
  Example:
&lt;/h6&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const promise1 = new Promise(resolve =&amp;gt; setTimeout(() =&amp;gt; resolve('First'), 1000));
const promise2 = new Promise(resolve =&amp;gt; setTimeout(() =&amp;gt; resolve('Second'), 2000));
const promise3 = new Promise(resolve =&amp;gt; setTimeout(() =&amp;gt; resolve('Third'), 1500));

Promise.all([promise1, promise2, promise3])
  .then(results =&amp;gt; {
    console.log(results);  // Output: ['First', 'Second', 'Third']
  })
  .catch(error =&amp;gt; {
    console.error('One of the promises failed', error);
  });

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h6&gt;
  
  
  Benefits:
&lt;/h6&gt;

&lt;ul&gt;
&lt;li&gt;It runs all the promises in parallel, speeding up execution when there’s no dependency between them.&lt;/li&gt;
&lt;li&gt;The promise returned by &lt;code&gt;Promise.all()&lt;/code&gt; resolves when all promises have successfully resolved, providing an array of results in the same order they were passed to &lt;code&gt;Promise.all()&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Note:&lt;/strong&gt; If any promise fails, &lt;code&gt;Promise.all()&lt;/code&gt; will reject immediately, and the subsequent promises will not continue.

&lt;/li&gt;
&lt;/ul&gt;

&lt;h5&gt;
  
  
  2. Promise.allSettled() – Wait for all promises to settle, regardless of success or failure
&lt;/h5&gt;

&lt;p&gt;&lt;code&gt;Promise.allSettled()&lt;/code&gt;returns a promise that resolves after all the promises have either resolved or rejected. It always resolves with an array of objects, each describing the outcome of each promise (either fulfilled or rejected).&lt;/p&gt;

&lt;p&gt;Example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const promise1 = new Promise(resolve =&amp;gt; setTimeout(() =&amp;gt; resolve('First'), 1000));
const promise2 = new Promise((_, reject) =&amp;gt; setTimeout(() =&amp;gt; reject('Second Error'), 1500));
const promise3 = new Promise(resolve =&amp;gt; setTimeout(() =&amp;gt; resolve('Third'), 2000));

Promise.allSettled([promise1, promise2, promise3])
  .then(results =&amp;gt; {
    console.log(results);
    // Output: 
    // [
    //   { status: 'fulfilled', value: 'First' },
    //   { status: 'rejected', reason: 'Second Error' },
    //   { status: 'fulfilled', value: 'Third' }
    // ]
  });

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h6&gt;
  
  
  Benefits:
&lt;/h6&gt;

&lt;p&gt;Unlike &lt;code&gt;Promise.all()&lt;/code&gt;, &lt;code&gt;Promise.allSettled()&lt;/code&gt; waits for all promises to settle (whether they resolve or reject), and returns a summary of the result.&lt;br&gt;
It’s useful when you want to track the status of all promises without stopping execution due to a rejection.&lt;/p&gt;




&lt;h5&gt;
  
  
  3. Promise.race() – Resolve as soon as the first promise resolves or rejects
&lt;/h5&gt;

&lt;p&gt;&lt;code&gt;Promise.race()&lt;/code&gt; takes an array of promises and returns a promise that settles as soon as the first promise in the array resolves or rejects. If the first promise is rejected, the returned promise will reject.&lt;/p&gt;

&lt;h6&gt;
  
  
  Example:
&lt;/h6&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const promise1 = new Promise(resolve =&amp;gt; setTimeout(() =&amp;gt; resolve('First'), 2000));
const promise2 = new Promise(resolve =&amp;gt; setTimeout(() =&amp;gt; resolve('Second'), 1000));

Promise.race([promise1, promise2])
  .then(result =&amp;gt; {
    console.log(result);  // Output: 'Second' (since it resolves first)
  })
  .catch(error =&amp;gt; {
    console.error(error);
  });

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h6&gt;
  
  
  Benefits:
&lt;/h6&gt;

&lt;ul&gt;
&lt;li&gt;It’s useful when you only care about the first result (whether it’s a success or failure).&lt;/li&gt;
&lt;li&gt;If you have multiple competing asynchronous operations and just want the one that completes first, Promise.race() is the way to go.

&lt;/li&gt;
&lt;/ul&gt;

&lt;h5&gt;
  
  
  4. Promise.any() – Resolves as soon as one promise resolves, rejects if all promises are rejected
&lt;/h5&gt;

&lt;p&gt;&lt;code&gt;Promise.any()&lt;/code&gt; takes an array of promises and returns a single promise that resolves as soon as any one of the promises resolves. If all promises are rejected, it will reject with an AggregateError containing all the rejection reasons.&lt;/p&gt;

&lt;h6&gt;
  
  
  Example:
&lt;/h6&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const promise1 = new Promise((_, reject) =&amp;gt; setTimeout(() =&amp;gt; reject('First Error'), 1000));
const promise2 = new Promise((_, reject) =&amp;gt; setTimeout(() =&amp;gt; reject('Second Error'), 1500));
const promise3 = new Promise(resolve =&amp;gt; setTimeout(() =&amp;gt; resolve('Third'), 2000));

Promise.any([promise1, promise2, promise3])
  .then(result =&amp;gt; {
    console.log(result);  // Output: 'Third' (since it's the first to resolve)
  })
  .catch(error =&amp;gt; {
    console.error(error); // Will not reach here in this example
  });

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h6&gt;
  
  
  Benefits:
&lt;/h6&gt;

&lt;ul&gt;
&lt;li&gt;Useful when you only care about the first successful result and can ignore failures.&lt;/li&gt;
&lt;li&gt;If all promises fail, it will reject with an AggregateError.

&lt;/li&gt;
&lt;/ul&gt;

&lt;h5&gt;
  
  
  Chaining Promises (Sequential Execution)
&lt;/h5&gt;

&lt;p&gt;If you need to handle promises sequentially (i.e., one promise must resolve before the next one starts), you can simply chain .then() methods.&lt;/p&gt;

&lt;h6&gt;
  
  
  Example:
&lt;/h6&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const task1 = () =&amp;gt; new Promise(resolve =&amp;gt; setTimeout(() =&amp;gt; resolve('Task 1 complete'), 1000));
const task2 = () =&amp;gt; new Promise(resolve =&amp;gt; setTimeout(() =&amp;gt; resolve('Task 2 complete'), 500));

task1()
  .then(result1 =&amp;gt; {
    console.log(result1); // Output: Task 1 complete
    return task2();       // Return the next promise to chain
  })
  .then(result2 =&amp;gt; {
    console.log(result2); // Output: Task 2 complete
  })
  .catch(error =&amp;gt; {
    console.error('Error:', error);
  });

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h6&gt;
  
  
  Benefits:
&lt;/h6&gt;

&lt;ul&gt;
&lt;li&gt;Guarantees that each promise will only start after the previous one completes, making it perfect for operations that must be executed in order.&lt;/li&gt;
&lt;li&gt;This method ensures sequential execution, which might be necessary in some scenarios (e.g., making multiple API calls in order).

&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>programming</category>
      <category>javascript</category>
      <category>webdev</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>Ways to convert a specified number to an array of digits</title>
      <dc:creator>Jyoti chaudhary</dc:creator>
      <pubDate>Fri, 28 Feb 2025 06:57:47 +0000</pubDate>
      <link>https://dev.to/jyotich15/ways-to-convert-a-specified-number-to-an-array-of-digits-18j4</link>
      <guid>https://dev.to/jyotich15/ways-to-convert-a-specified-number-to-an-array-of-digits-18j4</guid>
      <description>&lt;h5&gt;
  
  
  Method: 1. Using toString() and for loop
&lt;/h5&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const numberToArray = (number) =&amp;gt;  {
    let str = number.toString();
    let result = [];
    for (let i = 0; i &amp;lt; str.length; i++) {
        result.push(Number(str[i]));
    }
    return result;
}
console.log(numberToArray(12345)); // Output:  [1, 2, 3, 4, 5]

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h5&gt;
  
  
  Method: 2.Using toString(), split(), and map()
&lt;/h5&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const numberToArray = (number) =&amp;gt;  {
     return number.toString().split('').map(Number);
}
console.log(numberToArray(123456)); // Output:  [1, 2, 3, 4, 5, 6]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h5&gt;
  
  
  Method: 3. Using Math.floor() and a while loop
&lt;/h5&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const numberToArray = (number) =&amp;gt;  {
let result = [];
    while (number &amp;gt; 0) {
        result.unshift(number % 10);  // Get the last digit
        number = Math.floor(number / 10);  // Remove the last digit
    }
    return result;
}
console.log(numberToArray(123456));  // Output:  [1, 2, 3, 4, 5, 6]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h5&gt;
  
  
  Method: 4. Using Array.from()
&lt;/h5&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const numberToArray = (number) =&amp;gt;  {
  return Array.from(number.toString(), Number);
}
console.log(numberToArray(123456)); // Output:  [1, 2, 3, 4, 5, 6]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h5&gt;
  
  
  Method: 5. Using reduce()
&lt;/h5&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const numberToArray = (number) =&amp;gt;  {
   return number
        .toString()
        .split('')
        .reduce((acc, digit) =&amp;gt; {
            acc.push(Number(digit));
            return acc;
        }, []);
}
console.log("Number to array: ", numberToArray(123456));
// Output: Number to array: [1, 2, 3, 4, 5, 6]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h5&gt;
  
  
  Method: 6. Using Recursion
&lt;/h5&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function numberToArray(number) {
    if (number === 0) return [];
    return [...numberToArray(Math.floor(number / 10)), number % 10];
}
let result = numberToArray(123456)
 console.log("Result: ", result); // Output: Result:  [ 1, 2, 3, 4, 5, 6 ]

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
      <category>programming</category>
      <category>javascript</category>
      <category>tutorial</category>
      <category>webdev</category>
    </item>
    <item>
      <title>useState and useReducer which should we use?</title>
      <dc:creator>Jyoti chaudhary</dc:creator>
      <pubDate>Thu, 20 Feb 2025 16:09:15 +0000</pubDate>
      <link>https://dev.to/jyotich15/usestate-and-usereducer-which-should-we-use-4h7o</link>
      <guid>https://dev.to/jyotich15/usestate-and-usereducer-which-should-we-use-4h7o</guid>
      <description>&lt;p&gt;When it comes to state management in React, two commonly used hooks are &lt;strong&gt;useState&lt;/strong&gt; and &lt;strong&gt;useReducer&lt;/strong&gt;. These hooks play a crucial role in managing state within functional components. The choice between &lt;code&gt;useState&lt;/code&gt; and &lt;code&gt;useReducer&lt;/code&gt; in React depends on the complexity of your state management and how the state interacts within your component. Both hooks allow you to manage state, but they serve different purposes that developers should be aware of.. Here's a deeper dive into both hooks, comparing when to use each one and why.&lt;/p&gt;

&lt;h3&gt;
  
  
  1. useState Hook:
&lt;/h3&gt;

&lt;p&gt;&lt;code&gt;useState&lt;/code&gt; is the simplest hook to manage state in functional components. It's suitable when you only need to manage simple or isolated pieces of state.&lt;/p&gt;

&lt;p&gt;Syntax:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const [state, setState] = useState(initialState);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h5&gt;
  
  
  When to Use:
&lt;/h5&gt;

&lt;ul&gt;
&lt;li&gt;Simple state: When your component has small, isolated pieces of state that don't have complicated logic or interactions.&lt;/li&gt;
&lt;li&gt;One state change: If your state can be described with one value or a simple array/object, then useState is easy to use and direct.&lt;/li&gt;
&lt;li&gt;Local state management: It's great for form fields, toggling UI elements, or small flags.&lt;/li&gt;
&lt;/ul&gt;

&lt;h6&gt;
  
  
  Example:
&lt;/h6&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);

  const increment = () =&amp;gt; setCount(count + 1);
  const decrement = () =&amp;gt; setCount(count - 1);

  return (
    &amp;lt;div&amp;gt;
      &amp;lt;h1&amp;gt;{count}&amp;lt;/h1&amp;gt;
      &amp;lt;button onClick={increment}&amp;gt;Increment&amp;lt;/button&amp;gt;
      &amp;lt;button onClick={decrement}&amp;gt;Decrement&amp;lt;/button&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example, &lt;code&gt;useState&lt;/code&gt; is ideal because the state is a &lt;code&gt;single number (count)&lt;/code&gt; and it's not dependent on any complex logic or actions.&lt;/p&gt;

&lt;h5&gt;
  
  
  Use Cases for useState:
&lt;/h5&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;Simple state variables:&lt;/code&gt;&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;When the state is a simple value (like a number, string, or boolean), &lt;code&gt;useState&lt;/code&gt; is the easiest and most intuitive choice.&lt;br&gt;
Example: Toggling a modal, showing or hiding UI elements, updating form fields.&lt;/p&gt;

&lt;h6&gt;
  
  
  Example:
&lt;/h6&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const [isVisible, setIsVisible] = useState(false);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;Form Inputs:&lt;/code&gt;&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;code&gt;useState&lt;/code&gt; is ideal for handling individual form fields or a set of fields where each field has its own independent state.&lt;br&gt;
Example: Handling a user’s name and email input in a form.&lt;/p&gt;

&lt;h6&gt;
  
  
  Example:
&lt;/h6&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const [name, setName] = useState('');
const [email, setEmail] = useState('');
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;Single values with minimal logic:&lt;/code&gt;&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;If you need to keep track of a single piece of state like a counter, a boolean flag, or a single input field, &lt;code&gt;useState&lt;/code&gt; provides an easy, straightforward solution.&lt;/p&gt;

&lt;h6&gt;
  
  
  Example:
&lt;/h6&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const [count, setCount] = useState(0);
const increment = () =&amp;gt; setCount(count + 1);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;Local component state:&lt;/code&gt;&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;When the state is specific to a single component and doesn’t need to be shared across components, &lt;code&gt;useState&lt;/code&gt; is perfect.&lt;/p&gt;

&lt;h5&gt;
  
  
  Limitations of useState:
&lt;/h5&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;&lt;code&gt;Scaling issues with multiple state variables:&lt;/code&gt;&lt;/strong&gt;
As a component grows in complexity, managing multiple pieces of state with individual &lt;code&gt;useState&lt;/code&gt; calls can become cumbersome and harder to maintain.&lt;/li&gt;
&lt;/ul&gt;

&lt;h6&gt;
  
  
  Example:
&lt;/h6&gt;

&lt;p&gt;If you have a complex form with many fields, you’ll end up with several &lt;code&gt;useState&lt;/code&gt; hooks, which can lead to messy code and potential bugs.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;&lt;code&gt;Difficulties with dependent states:&lt;/code&gt;&lt;/strong&gt;
If your state updates depend on previous values of the state, it can be tricky. Using a functional update inside &lt;code&gt;setState&lt;/code&gt; is necessary, but can still get confusing when dealing with multiple dependencies.&lt;/li&gt;
&lt;/ul&gt;

&lt;h6&gt;
  
  
  Example:
&lt;/h6&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;setCount(prevCount =&amp;gt; prevCount + 1);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;No centralized state logic:&lt;/code&gt;&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;There’s no central place to manage complex state transitions. Each &lt;code&gt;useState&lt;/code&gt; hook operates independently, making state management harder when actions depend on each other.&lt;/p&gt;

&lt;h3&gt;
  
  
  2. useReducer Hook:
&lt;/h3&gt;

&lt;p&gt;&lt;code&gt;useReducer&lt;/code&gt; is more powerful than &lt;code&gt;useState&lt;/code&gt; and is usually preferred for managing more complex state logic, especially when the state depends on multiple actions or needs to be updated based on previous state values.&lt;/p&gt;

&lt;h6&gt;
  
  
  Syntax:
&lt;/h6&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const [state, dispatch] = useReducer(reducer, initialState);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;&lt;code&gt;reducer:&lt;/code&gt;&lt;/strong&gt; A function that determines how the state should change based on the dispatched action.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;&lt;code&gt;initialState:&lt;/code&gt;&lt;/strong&gt; The initial value of the state.&lt;/li&gt;
&lt;/ul&gt;

&lt;h5&gt;
  
  
  When to Use:
&lt;/h5&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;&lt;code&gt;Complex state logic:&lt;/code&gt;&lt;/strong&gt; If the state has multiple sub-values, or when state transitions depend on multiple actions, &lt;code&gt;useReducer&lt;/code&gt; can be a cleaner solution.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;&lt;code&gt;State transitions based on actions:&lt;/code&gt;&lt;/strong&gt; If you need to manage a state object or array that gets updated based on a series of actions (like increment, decrement, reset, etc.), &lt;code&gt;useReducer&lt;/code&gt; is a better choice because it centralizes the state logic.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;&lt;code&gt;Avoiding too many useState hooks:&lt;/code&gt;&lt;/strong&gt; If you have a component with a lot of state variables or complex interactions between them, using multiple &lt;code&gt;useState&lt;/code&gt; can get hard to manage. &lt;code&gt;useReducer&lt;/code&gt; can help centralize and clean up the state logic.&lt;/li&gt;
&lt;/ul&gt;

&lt;h6&gt;
  
  
  Example:
&lt;/h6&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, { useReducer } from 'react';

const initialState = { count: 0 };

function counterReducer(state, action) {
  switch (action.type) {
    case 'increment':
      return { count: state.count + 1 };
    case 'decrement':
      return { count: state.count - 1 };
    case 'reset':
      return { count: 0 };
    default:
      return state;
  }
}

function Counter() {
  const [state, dispatch] = useReducer(counterReducer, initialState);

  return (
    &amp;lt;div&amp;gt;
      &amp;lt;h1&amp;gt;{state.count}&amp;lt;/h1&amp;gt;
      &amp;lt;button onClick={() =&amp;gt; dispatch({ type: 'increment' })}&amp;gt;Increment&amp;lt;/button&amp;gt;
      &amp;lt;button onClick={() =&amp;gt; dispatch({ type: 'decrement' })}&amp;gt;Decrement&amp;lt;/button&amp;gt;
      &amp;lt;button onClick={() =&amp;gt; dispatch({ type: 'reset' })}&amp;gt;Reset&amp;lt;/button&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example, &lt;code&gt;useReducer&lt;/code&gt; is beneficial because the state consists of an object ({ count: 0 }) and the state updates depend on multiple actions (increment, decrement, reset). The &lt;code&gt;counterReducer&lt;/code&gt; function determines how to update the state based on the action type, making the logic more centralized and easier to manage.&lt;/p&gt;

&lt;h3&gt;
  
  
  Use Cases for &lt;code&gt;useReducer&lt;/code&gt;:
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;Complex state logic:&lt;/code&gt;&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;When the state changes based on multiple actions or conditions, using &lt;code&gt;useReducer&lt;/code&gt; centralizes the state management and makes it more organized.&lt;br&gt;
Example: A complex form with multiple fields, each with its own validation state and error messages.&lt;/p&gt;

&lt;h6&gt;
  
  
  Example:
&lt;/h6&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const initialState = { count: 0, status: 'idle' };
function reducer(state, action) {
  switch (action.type) {
    case 'increment':
      return { ...state, count: state.count + 1 };
    case 'reset':
      return { ...state, count: 0 };
    default:
      return state;
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;State transitions involving multiple actions:&lt;/code&gt;&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;When state changes involve multiple steps or actions, &lt;code&gt;useReducer&lt;/code&gt; allows for more predictable transitions, especially in components where the state changes are complex.&lt;br&gt;
Example: A component that handles a user’s authentication state (login, logout, session expired).&lt;/p&gt;

&lt;h6&gt;
  
  
  Example:
&lt;/h6&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const initialState = { user: null, loading: false, error: null };
function authReducer(state, action) {
  switch (action.type) {
    case 'LOGIN_REQUEST':
      return { ...state, loading: true };
    case 'LOGIN_SUCCESS':
      return { ...state, loading: false, user: action.user };
    case 'LOGIN_FAILURE':
      return { ...state, loading: false, error: action.error };
    default:
      return state;
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;Handling complex state objects or arrays:&lt;/code&gt;&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;If your state is an object or array with several sub-properties that require specific updates, &lt;code&gt;useReducer&lt;/code&gt; can be used to structure and manage the state more effectively.&lt;br&gt;
Example: Managing a form with different input fields, each with its own error message, validity, and other related data.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;Decoupling UI logic from business logic:&lt;/code&gt;&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;code&gt;useReducer&lt;/code&gt; is useful when you want to separate how the UI updates from the business logic that defines how the state should change.&lt;br&gt;
Example: For complex workflows, like a multi-step form, that require a defined flow for state transitions.&lt;/p&gt;

&lt;h3&gt;
  
  
  Limitations of &lt;code&gt;useReducer&lt;/code&gt;:
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;More boilerplate:&lt;/code&gt;&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;code&gt;useReducer&lt;/code&gt; introduces more boilerplate code compared to &lt;code&gt;useState&lt;/code&gt;. You'll need to define a reducer function and action types, which might feel overkill for simple state management.&lt;br&gt;
Example: Writing a reducer function with a switch statement can be more verbose than simply using &lt;code&gt;useState&lt;/code&gt;.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;Learning curve:&lt;/code&gt;&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;For beginners, &lt;code&gt;useReducer&lt;/code&gt; might seem like overkill because it requires understanding of reducers, actions, and the concept of immutability. It’s a bit harder to get started with compared to &lt;code&gt;useState&lt;/code&gt;.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;Not necessary for simple state:&lt;/code&gt;&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;If your component’s state is simple, like a single boolean or number, using &lt;code&gt;useReducer&lt;/code&gt; adds unnecessary complexity. It’s better to reserve &lt;code&gt;useReducer&lt;/code&gt; for scenarios where you have complex state logic.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;strong&gt;&lt;code&gt;Dispatching actions and managing flow:&lt;/code&gt;&lt;/strong&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;If you don’t need to centralize your state logic, managing each action type and dispatching it properly can lead to unnecessary complexity, especially if you're only working with a small amount of state.&lt;/p&gt;

&lt;h3&gt;
  
  
  Comparison:
&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F484ta8xw1rz83ajww700.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F484ta8xw1rz83ajww700.png" alt="compare image" width="594" height="231"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Which One to Use?
&lt;/h3&gt;

&lt;h5&gt;
  
  
  1. Use &lt;code&gt;useState&lt;/code&gt; if:
&lt;/h5&gt;

&lt;ul&gt;
&lt;li&gt;The state is simple (e.g., a number, string, or boolean).&lt;/li&gt;
&lt;li&gt;You don't have complex state transitions.&lt;/li&gt;
&lt;li&gt;You have one or a few state variables that are not interdependent.&lt;/li&gt;
&lt;/ul&gt;

&lt;h5&gt;
  
  
  2. Use &lt;code&gt;useReducer&lt;/code&gt; if:
&lt;/h5&gt;

&lt;ul&gt;
&lt;li&gt;The state logic is complex or involves multiple actions that update different parts of state.&lt;/li&gt;
&lt;li&gt;You have a state that changes based on multiple conditions.&lt;/li&gt;
&lt;li&gt;You want a more organized and scalable way of managing state in large components.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Best Practice:
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;If you’re just building a small form or handling simple interactions like toggling visibility, &lt;code&gt;useState&lt;/code&gt; is often the best choice.&lt;/li&gt;
&lt;li&gt;For more advanced or large components with multiple, interdependent pieces of state or complex updates (e.g., multi-step forms, managing arrays/objects, etc.), &lt;code&gt;useReducer&lt;/code&gt; can lead to more maintainable code.&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>webdev</category>
      <category>react</category>
      <category>tutorial</category>
      <category>javascript</category>
    </item>
    <item>
      <title>How frontend interact with backend?</title>
      <dc:creator>Jyoti chaudhary</dc:creator>
      <pubDate>Fri, 14 Feb 2025 08:16:26 +0000</pubDate>
      <link>https://dev.to/jyotich15/how-frontend-interact-with-backend-2a6e</link>
      <guid>https://dev.to/jyotich15/how-frontend-interact-with-backend-2a6e</guid>
      <description>&lt;p&gt;In a &lt;strong&gt;MERN&lt;/strong&gt; stack &lt;code&gt;(MongoDB, Express, React, Node.js)&lt;/code&gt;, the frontend &lt;code&gt;(React)&lt;/code&gt; interacts with the backend &lt;code&gt;(Node.js + Express)&lt;/code&gt; primarily through &lt;code&gt;HTTP&lt;/code&gt; requests. The backend handles these requests, processes them (often involving interactions with a &lt;code&gt;database&lt;/code&gt; like &lt;code&gt;MongoDB&lt;/code&gt;), and returns a response to the frontend.&lt;/p&gt;

&lt;h4&gt;
  
  
  How the Frontend (React) and Backend (Node.js/Express) Interact:
&lt;/h4&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fs4ta1rwnjnsc6ijxpabq.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fs4ta1rwnjnsc6ijxpabq.png" alt="Backend Image" width="701" height="502"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fe8n2fp1qahhswkfxv55p.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fe8n2fp1qahhswkfxv55p.png" alt="frontend+backend" width="800" height="414"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h6&gt;
  
  
  1. Frontend (React):
&lt;/h6&gt;

&lt;ul&gt;
&lt;li&gt;The frontend is responsible for displaying the user interface, handling user input, and making HTTP requests to the backend when it needs data or to perform actions (such as submitting a form).&lt;/li&gt;
&lt;li&gt;In technically terms, we call frontend as &lt;code&gt;client&lt;/code&gt;, it can be anything your web application, mobile application or any user facing application.&lt;/li&gt;
&lt;li&gt;Client talk via APIs to the server(backend).&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;React&lt;/code&gt; uses libraries like &lt;code&gt;Axios&lt;/code&gt; or the native &lt;code&gt;Fetch API&lt;/code&gt; to make HTTP requests (GET, POST, PUT, DELETE, etc.) to the backend.&lt;/li&gt;
&lt;/ul&gt;

&lt;h6&gt;
  
  
  2. Backend (Node.js +Express):
&lt;/h6&gt;

&lt;ul&gt;
&lt;li&gt;The backend (Express) receives the HTTP requests from the frontend, processes them (such as fetching or modifying data from MongoDB), and sends back a response, which could be data (JSON) or an acknowledgment of the operation.&lt;/li&gt;
&lt;li&gt;These fetch calls have routes(like /product, /home, /profile, or ...) and all the code for these routes will be written in Express.&lt;/li&gt;
&lt;li&gt;Express also known as &lt;code&gt;routing library&lt;/code&gt;, but it's more accurate to call it a   &lt;code&gt;web application framework&lt;/code&gt; for &lt;code&gt;Node.js&lt;/code&gt;. It provides a set of tools that make it easier to build web applications and APIs, and one of its core functionalities is routing.&lt;/li&gt;
&lt;li&gt;Server talks database, to get data or to send data by queries (like find, findOne, findById, findByIdAndDelete, findByIdAndUpdate or more queries).&lt;/li&gt;
&lt;li&gt;The backend typically exposes routes (API endpoints) for the frontend to call.&lt;/li&gt;
&lt;/ul&gt;

&lt;h6&gt;
  
  
  3. Database (MongoDB):
&lt;/h6&gt;

&lt;ul&gt;
&lt;li&gt;MongoDB is a NoSQL database where data is stored in collections and documents. The backend uses MongoDB to store and retrieve data in response to requests from the frontend.&lt;/li&gt;
&lt;li&gt;The most commonly used &lt;strong&gt;ODM&lt;/strong&gt; &lt;code&gt;(Object Data Modeling)&lt;/code&gt; for &lt;strong&gt;MongoDB&lt;/strong&gt; in Node.js applications is &lt;strong&gt;Mongoose&lt;/strong&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;Mongoose&lt;/code&gt; is an ODM library that provides a straightforward way to interact with MongoDB from a Node.js environment. It allows you to define data schemas, validate data, perform CRUD (Create, Read, Update, Delete) operations, and more, in an object-oriented way.&lt;/li&gt;
&lt;/ul&gt;

&lt;h5&gt;
  
  
  Example: Frontend (React) Making a GET Request to Backend (Express) to Fetch Data
&lt;/h5&gt;

&lt;ul&gt;
&lt;li&gt;Backend (Express):&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Let's start by setting up a basic Express server with one API endpoint to get a list of items from the database.&lt;/p&gt;

&lt;h6&gt;
  
  
  server.js(Backend)
&lt;/h6&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');

const app = express();
const PORT = 5000;

// Use CORS to allow requests from the frontend
app.use(cors());

// MongoDB connection
mongoose.connect('mongodb://localhost:27017/mern-demo', 
  { 
    useNewUrlParser: true,
    useUnifiedTopology: true 
  });

// Sample MongoDB schema and model
const Item = mongoose.model('Item', new mongoose.Schema({ name: String }));

// Route to fetch items from MongoDB
app.get('/api/items', async (req, res) =&amp;gt; {
  try {
    const items = await Item.find();
    res.json(items);  // Send items as JSON response
  } catch (err) {
    res.status(500).send('Server Error');
  }
});

// Route to Add items to MongoDB
app.post('/api/items', async (req, res) =&amp;gt; {
  const { name } = req.body;  // Extract 'name' from request body

  try {
    const newItem = new Item({ name });
    await newItem.save();  // Save the item to MongoDB
    res.json(newItem);  // Send the saved item back as a response
  } catch (err) {
    res.status(500).send('Server Error');
  }
});


// Start server
app.listen(PORT, () =&amp;gt; {
  console.log(`Server is running on port ${PORT}`);
});

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Frontend (React):&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Now, on the frontend (React), we can make a GET request to this API to fetch the items.&lt;/p&gt;

&lt;h6&gt;
  
  
  App.js
&lt;/h6&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, { useState, useEffect } from 'react';
import axios from 'axios';

function App() {
  const [items, setItems] = useState([]);

  useEffect(() =&amp;gt; {
    // Fetch data from the backend
    axios.get('http://localhost:5000/api/items')
      .then(response =&amp;gt; {
        setItems(response.data);  // Set items to state
      })
      .catch(error =&amp;gt; {
        console.error('There was an error fetching the items!', error);
      });
  }, []);  // Empty array means this effect runs only once when the component mounts

  return (
    &amp;lt;div&amp;gt;
      &amp;lt;h1&amp;gt;Item List&amp;lt;/h1&amp;gt;
      &amp;lt;ul&amp;gt;
        {items.map(item =&amp;gt; (
          &amp;lt;li key={item._id}&amp;gt;{item.name}&amp;lt;/li&amp;gt;
        ))}
      &amp;lt;/ul&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}

export default App;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h6&gt;
  
  
  CreateItems.js
&lt;/h6&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, { useState } from 'react';
import axios from 'axios';

const CreateItems = () =&amp;gt; {
  const [name, setName] = useState('');

  const addItem = async () =&amp;gt; {
    try {
      const response = await axios.post('http://localhost:5000/api/items', { name });
      console.log('Item added:', response.data);
      setName(''); // Reset input field
    } catch (error) {
      console.error('There was an error adding the item!', error);
    }
  };

  return (
    &amp;lt;div&amp;gt;
      &amp;lt;h1&amp;gt;Add Item&amp;lt;/h1&amp;gt;
      &amp;lt;input
        type="text"
        value={name}
        onChange={(e) =&amp;gt; setName(e.target.value)}
        placeholder="Enter item name"
      /&amp;gt;
      &amp;lt;button onClick={addItem}&amp;gt;Add Item&amp;lt;/button&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}

export default CreateItems;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h6&gt;
  
  
  Explanation:
&lt;/h6&gt;

&lt;h5&gt;
  
  
  1. Backend (Express) Setup:
&lt;/h5&gt;

&lt;ul&gt;
&lt;li&gt;The backend has a two routes, one get(/api/items) that fetches a list of items and second post(/api/items) create a item to the MongoDB database using Mongoose.&lt;/li&gt;
&lt;li&gt;The Item model is a simple schema that has a name field (you can add more fields as per your requirement).&lt;/li&gt;
&lt;li&gt;The server listens on port 5000, and CORS is enabled to allow requests from the React frontend (which typically runs on port 3000 in development).&lt;/li&gt;
&lt;/ul&gt;

&lt;h5&gt;
  
  
  2. Frontend (React) Setup:
&lt;/h5&gt;

&lt;ul&gt;
&lt;li&gt;In the App.js file, the useEffect hook is used to fetch data when the component mounts (i.e., when the app is first loaded).&lt;/li&gt;
&lt;li&gt;The axios.get method is used to make an HTTP GET request to the backend's /api/items endpoint.&lt;/li&gt;
&lt;li&gt;When the data is fetched, it's stored in the component's state (items), and the list of items is rendered in an unordered list.&lt;/li&gt;
&lt;/ul&gt;

&lt;h5&gt;
  
  
  3. CORS:
&lt;/h5&gt;

&lt;ul&gt;
&lt;li&gt;CORS (Cross-Origin Resource Sharing) is enabled in the Express server to allow the React frontend to make requests to the backend even though they are running on different ports (React usually runs on port 3000, while Express runs on port 5000).&lt;/li&gt;
&lt;/ul&gt;

&lt;h5&gt;
  
  
  Summary:
&lt;/h5&gt;

&lt;ul&gt;
&lt;li&gt;The React frontend makes HTTP requests (GET, POST, etc.) to the Express backend.&lt;/li&gt;
&lt;li&gt;The Express server handles the requests, interacts with the MongoDB database, and sends responses (data or acknowledgment) back to the frontend.&lt;/li&gt;
&lt;li&gt;This communication typically happens via RESTful APIs exposed by the backend.&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>webdev</category>
      <category>javascript</category>
      <category>tutorial</category>
      <category>react</category>
    </item>
    <item>
      <title>Shallow copy and Deep copy</title>
      <dc:creator>Jyoti chaudhary</dc:creator>
      <pubDate>Tue, 11 Feb 2025 05:57:59 +0000</pubDate>
      <link>https://dev.to/jyotich15/shallow-copy-and-deep-copy-man</link>
      <guid>https://dev.to/jyotich15/shallow-copy-and-deep-copy-man</guid>
      <description>&lt;h3&gt;
  
  
  1. Shallow Copy
&lt;/h3&gt;

&lt;p&gt;A shallow copy creates a new object or array but does not recursively copy the nested objects/arrays inside it. Instead, the references to the nested objects are copied, so changes to nested objects affect both the original and the copied objects.&lt;br&gt;
In this process, only the top-level properties are copied, while nested objects or arrays still reference the original memory location. This means that if you change the nested properties in one object, those changes will reflect in the other because they share the same memory reference.&lt;/p&gt;

&lt;h6&gt;
  
  
  Example 1: Shallow Copy using Object.assign():
&lt;/h6&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Original Object
const original = {
  name: "John",
  age: 30,
  address: {
    city: "New York",
    zip: "10001"
  }
};

// Shallow copy using Object.assign()
const shallowCopy = Object.assign({}, original);

// Modify the nested object in the shallow copy
shallowCopy.address.city = "Los Angeles";
shallowCopy.name = "Sumit";

console.log(original.address.city);     // Output: "Los Angeles"

console.log(shallowCopy.address.city);    // Output: "Los Angeles"

console.log(original);     // Output: {name: 'John', age: 30, address: {city: 'Los Angeles', zip: '10001'}}

console.log(shallowCopy);   // Output: {name: 'Sumit', age: 30, address: {city: 'Los Angeles', zip: '10001'}}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h6&gt;
  
  
  Explanation: In the above example:
&lt;/h6&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;original&lt;/code&gt; is an object with a nested object address.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;shallowCopy&lt;/code&gt; is created using &lt;code&gt;Object.assign()&lt;/code&gt;, which copies only the first level of properties from &lt;code&gt;original&lt;/code&gt; to &lt;code&gt;shallowCopy&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;However, since &lt;code&gt;address&lt;/code&gt; is a reference to the same object in both &lt;code&gt;original&lt;/code&gt; and &lt;code&gt;shallowCopy&lt;/code&gt; modifying &lt;code&gt;shallowCopy.address&lt;/code&gt; affects both objects, but not &lt;code&gt;name&lt;/code&gt; which shares different memory, so it doesn't affect the 'original' object.&lt;/li&gt;
&lt;/ul&gt;

&lt;h6&gt;
  
  
  Example 2: Shallow Copy using the Spread Operator
&lt;/h6&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Original object
const book = {
  title: 'JavaScript Guide',
  author: 'John Doe',
  publisher: {
    name: 'Tech Books',
    year: 2020
  }
};

// Shallow copy using the spread operator
const bookCopy = { ...book };

// Modify the nested object in the copied object
bookCopy.publisher.year = 2023;

console.log(book.publisher.year); // Output: 2023 (affected)
console.log(bookCopy.publisher.year); // Output: 2023

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h6&gt;
  
  
  Explanation:
&lt;/h6&gt;

&lt;p&gt;The spread operator &lt;code&gt;({...book})&lt;/code&gt; creates a shallow copy of the object. However, since &lt;code&gt;publisher&lt;/code&gt; is a nested object, both the original and the copied object share the same reference for the &lt;code&gt;publisher&lt;/code&gt; object.&lt;/p&gt;

&lt;h6&gt;
  
  
  Example 3: Shallow Copy with Arrays using the Spread Operator
&lt;/h6&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Original array
const colors = ['red', 'green', 'blue'];

// Shallow copy using the spread operator
const colorsCopy = [...colors];

// Modify an element in the copied array
colorsCopy[0] = 'yellow';

console.log(colors); // Output: ['red', 'green', 'blue']
console.log(colorsCopy); // Output: ['yellow', 'green', 'blue']

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h6&gt;
  
  
  Explanation:
&lt;/h6&gt;

&lt;p&gt;In this case, the spread operator creates a shallow copy of the array. Since the array doesn't contain any nested objects or arrays, changes to the copied array don’t affect the original.&lt;/p&gt;

&lt;h6&gt;
  
  
  Example 4: Shallow Copy with Arrays using Slice
&lt;/h6&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Original array
const numbers = [1, 2, [3, 4]];

// Shallow copy using slice method
const numbersCopy = numbers.slice();

// Modify the nested array in the copied array
numbersCopy[2][0] = 99;
numbersCopy[1] = 12

console.log(numbers); // Output: [1, 2, [99, 4]
console.log(numbersCopy); // Output: [1, 12, [99, 4]

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h6&gt;
  
  
  Explanation:
&lt;/h6&gt;

&lt;ul&gt;
&lt;li&gt;The shallow copy with &lt;code&gt;.slice()&lt;/code&gt; only copied the references for the nested arrays.&lt;/li&gt;
&lt;li&gt;Modifying the nested array &lt;code&gt;(numbersCopy[2][0] = 99)&lt;/code&gt; affected both &lt;code&gt;numbers&lt;/code&gt; and &lt;code&gt;numbersCopy&lt;/code&gt; because they share the same reference to the nested array.&lt;/li&gt;
&lt;li&gt;Modifying a non-nested element (numbersCopy[1] = 12) only affected &lt;code&gt;numbersCopy&lt;/code&gt;, not &lt;code&gt;numbers&lt;/code&gt;, because it is a primitive value (non-reference type).&lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;
&lt;p&gt;Thus, the shallow copy mechanism with &lt;code&gt;.slice()&lt;/code&gt; works at the top level for the array but does not fully isolate nested objects or arrays.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h6&gt;
  
  
  Example 5: Shallow Copy with Objects Containing Arrays
&lt;/h6&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const config = {
  theme: 'dark',
  colors: ['red', 'green'],
};

// Shallow copy using Object.assign()
const configCopy = Object.assign({}, config);

// Modify the array in the copied object
configCopy.colors[0] = 'yellow';
config.theme = "light"

console.log(config); // Output: {theme: 'light', colors: ['yellow', 'green']}
console.log(configCopy); // Output: {theme: 'dark', colors: ['yellow', 'green']}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h6&gt;
  
  
  Explanation:
&lt;/h6&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;configCopy.theme&lt;/code&gt; remains 'dark' because &lt;code&gt;theme&lt;/code&gt; is a primitive, and the shallow copy copied the value, not the reference.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;configCopy.colors&lt;/code&gt; still points to the array ['yellow', 'green'], but this change was due to the shared reference between &lt;code&gt;config&lt;/code&gt; and &lt;code&gt;configCopy&lt;/code&gt; (they both point to the same array).&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;Shallow copy&lt;/code&gt; means that the top-level properties are copied, but for reference types (arrays, objects), only the reference is copied, not the actual values.&lt;/li&gt;
&lt;/ul&gt;

&lt;h6&gt;
  
  
  Example 6: Shallow Copy with Arrays Containing Objects
&lt;/h6&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Original array containing objects
const products = [
  { name: 'Laptop', price: 1000 },
  { name: 'Phone', price: 500 }
];

// Shallow copy using slice
const productsCopy = products.slice();

// Modify the object in the copied array
productsCopy[0].price = 1200;

console.log(products[0]); // Output: {name: 'Laptop', price: 1200}
console.log(productsCopy[0]); // Output: {name: 'Laptop', price: 1200}

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h6&gt;
  
  
  Explanation:
&lt;/h6&gt;

&lt;p&gt;Since the &lt;code&gt;products&lt;/code&gt; array contains objects, and slice() creates a shallow copy, both &lt;code&gt;products&lt;/code&gt; and &lt;code&gt;productsCopy&lt;/code&gt; refer to the same object for each element in the array. Changing the &lt;code&gt;price&lt;/code&gt; in the copied array also affects the &lt;code&gt;original&lt;/code&gt; array.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;In a shallow copy, primitive values are copied by value, so changing them doesn’t affect the original, but nested objects are copied by reference, so changes reflect in both.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h3&gt;
  
  
  2.Deep Copy
&lt;/h3&gt;

&lt;p&gt;A &lt;code&gt;Deep Copy&lt;/code&gt; creates a completely independent copy of the object, and recursively copies all nested objects and arrays, meaning that changes to the deep copy will not affect the original object and vice versa. This ensures that changes made to one object do not affect the others. Each object is stored in a separate memory location, making them entirely independent.&lt;/p&gt;

&lt;h6&gt;
  
  
  Example:
&lt;/h6&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Original Object
const original = {
  name: "John",
  age: 30,
  address: {
    city: "New York",
    zip: "10001"
  }
};

// Deep copy using JSON methods
const deepCopy = JSON.parse(JSON.stringify(original));

// Modify the nested object in the deep copy
deepCopy.address.city = "Los Angeles";

console.log(original.address.city); // Output: "New York"
console.log(deepCopy.address.city); // Output: "Los Angeles"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h6&gt;
  
  
  Explanation:
&lt;/h6&gt;

&lt;ul&gt;
&lt;li&gt;JSON.stringify() converts the object into a JSON string.&lt;/li&gt;
&lt;li&gt;JSON.parse() parses the string back into a new object.&lt;/li&gt;
&lt;li&gt;This creates a new, independent object where all nested objects are copied, and any modifications to the deep copy do not affect the original object.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Important Differences:
&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fp16d0qq28vh9nb6tgunk.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fp16d0qq28vh9nb6tgunk.png" alt="Differences" width="588" height="170"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h6&gt;
  
  
  Deep Copy with Arrays:
&lt;/h6&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Original Array
const originalArray = [1, 2, [3, 4]];

// Deep copy using JSON methods
const deepCopyArray = JSON.parse(JSON.stringify(originalArray));

// Modify the nested array
deepCopyArray[2][0] = 99;
deepCopyArray[1] = 12

console.log(originalArray); // Output: [1, 2, [3, 4]
console.log(deepCopyArray); // Output: [1, 12, [99, 4]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h6&gt;
  
  
  Explanation:
&lt;/h6&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const deepCopyArray = JSON.parse(JSON.stringify(originalArray));
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h6&gt;
  
  
  &lt;code&gt;JSON.stringify(originalArray):&lt;/code&gt;
&lt;/h6&gt;

&lt;ul&gt;
&lt;li&gt;This converts the entire &lt;code&gt;originalArray&lt;/code&gt; into a &lt;strong&gt;JSON string&lt;/strong&gt;. The nested array [3, 4] is also converted to its JSON representation (a string representation).&lt;/li&gt;
&lt;/ul&gt;

&lt;h6&gt;
  
  
  &lt;code&gt;JSON.parse():&lt;/code&gt;
&lt;/h6&gt;

&lt;ul&gt;
&lt;li&gt;The &lt;code&gt;JSON.parse()&lt;/code&gt; method takes the JSON string and converts it back into a new &lt;code&gt;object or array&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;The key point here is that &lt;code&gt;nested objects (like the array [3, 4])&lt;/code&gt; are also deep-copied, not just the top-level array.&lt;/li&gt;
&lt;li&gt;As a result, &lt;code&gt;deepCopyArray&lt;/code&gt; is an entirely new array with a &lt;code&gt;new reference&lt;/code&gt;, and the nested array [3, 4] is also a &lt;code&gt;new reference&lt;/code&gt; in &lt;code&gt;deepCopyArray&lt;/code&gt;. This is the key difference between deep copy and shallow copy.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;deepCopyArray[2][0] = 99;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Here, &lt;code&gt;deepCopyArray[2]&lt;/code&gt; refers to the nested array &lt;code&gt;[3, 4]&lt;/code&gt;, which is a new, independent array from the one in &lt;code&gt;originalArray&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;We change the first element of this nested array to &lt;code&gt;99&lt;/code&gt;. This does not affect &lt;code&gt;originalArray&lt;/code&gt; because the nested arrays are &lt;code&gt;deeply copied&lt;/code&gt;.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;originalArray: [1, 2, [3, 4]]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;This remains unchanged because we performed a &lt;code&gt;deep copy&lt;/code&gt;, meaning the original array and the copied array are completely independent, including their nested arrays.
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;deepCopyArray: [1, 12, [99, 4]]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;This reflects the changes we made:&lt;/li&gt;
&lt;li&gt;The second element was changed from 2 to 12.&lt;/li&gt;
&lt;li&gt;The first element of the nested array was changed from 3 to 99.&lt;/li&gt;
&lt;/ul&gt;

&lt;h4&gt;
  
  
  Caveats:
&lt;/h4&gt;

&lt;ul&gt;
&lt;li&gt;Using &lt;code&gt;JSON.parse(JSON.stringify())&lt;/code&gt; for deep copying has limitations:&lt;/li&gt;
&lt;li&gt;It cannot copy functions, &lt;code&gt;undefined&lt;/code&gt;, &lt;code&gt;RegExp&lt;/code&gt;, &lt;code&gt;Date&lt;/code&gt;, or circular references.&lt;/li&gt;
&lt;li&gt;It might not preserve special object types (e.g., &lt;code&gt;Map&lt;/code&gt;, &lt;code&gt;Set&lt;/code&gt;, or &lt;code&gt;Date&lt;/code&gt;).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;For these cases, libraries like &lt;code&gt;Lodash&lt;/code&gt; provide more robust deep copying utilities (e.g., &lt;code&gt;_.cloneDeep())&lt;/code&gt;, which handle these edge cases more gracefully.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;Shallow Copy&lt;/code&gt; is faster but links to nested objects, meaning changes to nested structures will reflect in both the original and the copy.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;Deep Copy&lt;/code&gt; is slower but creates a fully independent copy, including all nested objects, which makes it more suitable when you need complete isolation between the original and the copied object.&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>programming</category>
      <category>javascript</category>
      <category>beginners</category>
      <category>webdev</category>
    </item>
    <item>
      <title>Why Serverless Architecture is the Future of Web Development: Pros and Cons</title>
      <dc:creator>Jyoti chaudhary</dc:creator>
      <pubDate>Fri, 07 Feb 2025 10:44:54 +0000</pubDate>
      <link>https://dev.to/jyotich15/why-serverless-architecture-is-the-future-of-web-development-pros-and-cons-hlj</link>
      <guid>https://dev.to/jyotich15/why-serverless-architecture-is-the-future-of-web-development-pros-and-cons-hlj</guid>
      <description>&lt;p&gt;Serverless architecture is an innovative cloud computing solution where &lt;br&gt;
developers build and run applications without managing servers. Thus, developers can focus solely on the application code. Serverless doesn't mean that servers are absent but developers don’t have to deal with server management handled by providers.&lt;/p&gt;

&lt;p&gt;Instead of provisioning and maintaining servers, developers rely on cloud providers like AWS (Amazon Web Services), Google Cloud, or Microsoft Azure to automatically scale and manage the infrastructure for them.&lt;br&gt;
The idea is that you only pay for what you use, and the cloud provider automatically scales resources based on demand.&lt;/p&gt;

&lt;h3&gt;
  
  
  Serverless Architecture:
&lt;/h3&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fuvm7rpekiaecjf5lpwa8.jpg" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fuvm7rpekiaecjf5lpwa8.jpg" alt="Serverless" width="800" height="404"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  How Serverless Works (Example):
&lt;/h3&gt;

&lt;p&gt;Imagine you're building an e-commerce website:&lt;/p&gt;

&lt;h5&gt;
  
  
  1. User Places an Order:
&lt;/h5&gt;

&lt;ul&gt;
&lt;li&gt;When a user places an order on your site, an API Gateway receives the request.&lt;/li&gt;
&lt;li&gt;The API Gateway triggers a serverless function (like AWS Lambda) that handles payment processing.&lt;/li&gt;
&lt;li&gt;The serverless function processes the payment and updates the order status in a database.&lt;/li&gt;
&lt;/ul&gt;

&lt;h5&gt;
  
  
  2. Scalability Example:
&lt;/h5&gt;

&lt;ul&gt;
&lt;li&gt;If 10,000 people place orders at once, the cloud provider automatically scales the number of serverless functions to handle the traffic. You only pay for the computation time of those functions during the orders' processing.&lt;/li&gt;
&lt;/ul&gt;




&lt;h3&gt;
  
  
  Serverless Computing Providers and Platforms
&lt;/h3&gt;

&lt;p&gt;With distinct platforms and features suited to various development requirements, serverless computing has emerged as a key area of attention for numerous cloud service providers. These are a few of the top platforms and providers of serverless computing:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;b&gt;AWS Lambda: &lt;/b&gt; Without having to provision or manage servers, developers may use AWS Lambda, perhaps the most well-known serverless computing tool, to execute code in response to events from more than 200 AWS services and SaaS apps.&lt;/li&gt;
&lt;li&gt;
&lt;b&gt;Azure Functions:&lt;/b&gt; With Azure Functions, a serverless compute solution from Microsoft, you can execute event-triggered code without explicitly provisioning or managing infrastructure. Azure Functions easily connects with other Azure services and supports a large number of programming languages.&lt;/li&gt;
&lt;li&gt;
&lt;b&gt;Google Cloud Functions:&lt;/b&gt; This is the serverless execution environment used by Google to create and link cloud services. All you have to do with Google Cloud Functions is write your code; Google handles the management, scaling, and underlying infrastructure.&lt;/li&gt;
&lt;li&gt;
&lt;b&gt;Oracle Cloud Functions:&lt;/b&gt; Using functions that are triggered by HTTP requests or events coming from Oracle Cloud services, developers can create apps with Oracle's serverless architecture. It is intended to provide an integrated cloud experience by integrating easily with Oracle's existing cloud products.&lt;/li&gt;
&lt;/ul&gt;




&lt;p&gt;Developing serverless applications requires a shift in how you approach traditional application architecture, focusing on cloud-based services that handle infrastructure management for you. Here's a step-by-step guide to building a serverless application:&lt;/p&gt;

&lt;h4&gt;
  
  
  Steps for Developing Serverless Applications
&lt;/h4&gt;

&lt;h5&gt;
  
  
  1. Define the Application’s Requirements
&lt;/h5&gt;

&lt;p&gt;Before diving into the technical details, you need to outline the business logic and functionality of your serverless application. Consider the following:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Event-driven: What events will trigger the functions? (e.g., user requests, database changes, file uploads)&lt;/li&gt;
&lt;li&gt;Services needed: What AWS services (or services from other cloud providers) will be used? (e.g., AWS Lambda, DynamoDB, S3, API Gateway)&lt;/li&gt;
&lt;li&gt;Scalability and performance needs: Estimate expected usage to decide if serverless fits well or if you need hybrid architectures.&lt;/li&gt;
&lt;/ul&gt;

&lt;h5&gt;
  
  
  2. Choose Your Cloud Provider
&lt;/h5&gt;

&lt;p&gt;Most serverless platforms are tied to a particular cloud provider. You’ll need to pick one based on your requirements:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;AWS Lambda&lt;/strong&gt; (Amazon Web Services)&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Google Cloud Functions&lt;/strong&gt; (Google Cloud)&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Azure Functions&lt;/strong&gt; (Microsoft Azure)
Other providers such as IBM Cloud Functions or Oracle Functions also offer serverless computing.&lt;/li&gt;
&lt;/ul&gt;

&lt;h5&gt;
  
  
  3. Define and Create Serverless Functions
&lt;/h5&gt;

&lt;p&gt;Serverless functions (e.g., AWS Lambda functions) are the heart of your serverless application. Each function is responsible for executing a small unit of work.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Write your function code: Develop small, stateless functions that are triggered by events like HTTP requests, file uploads, or database changes.&lt;/li&gt;
&lt;li&gt;For example, a function might process an incoming HTTP request to fetch user data from a database.&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;Function Triggers: Define how the function will be triggered. These triggers can include:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;HTTP requests (via an API Gateway)&lt;/li&gt;
&lt;li&gt;Changes in a database (using DynamoDB Streams or Google Firestore)&lt;/li&gt;
&lt;li&gt;File uploads to cloud storage (S3, Google Cloud Storage)&lt;/li&gt;
&lt;li&gt;Scheduled tasks (using CloudWatch Events or Google Cloud Scheduler)&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;li&gt;&lt;p&gt;Example: A function in AWS Lambda that sends a welcome email when a new user signs up for an app.&lt;/p&gt;&lt;/li&gt;

&lt;/ul&gt;

&lt;h5&gt;
  
  
  4. Set Up API Gateway (for HTTP-based Applications)
&lt;/h5&gt;

&lt;p&gt;If your serverless application interacts with web clients, you'll likely need an API Gateway to expose your serverless functions as HTTP endpoints.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;Create API Gateway: This will act as a frontend to route incoming HTTP requests to the appropriate serverless function.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;For example, AWS API Gateway can expose HTTP endpoints that route requests to Lambda functions.&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;li&gt;

&lt;p&gt;Define routes and methods: Set up HTTP methods (GET, POST, PUT, DELETE) to connect specific routes to functions.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Example: /users/{userId} might be routed to a Lambda function that fetches user information.&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;li&gt;&lt;p&gt;Authentication and Authorization: Implement security features like OAuth or API keys to secure your API endpoints, if necessary.&lt;/p&gt;&lt;/li&gt;

&lt;/ul&gt;

&lt;h5&gt;
  
  
  5. Set Up Data Storage (Database and File Storage)
&lt;/h5&gt;

&lt;p&gt;Even though serverless removes the need to manage traditional servers, you still need to store and access data.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;NoSQL Databases: Serverless applications often use managed NoSQL databases like:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Amazon DynamoDB (AWS)&lt;/li&gt;
&lt;li&gt;Firestore (Google Cloud)&lt;/li&gt;
&lt;li&gt;Cosmos DB (Azure)&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;/ul&gt;

&lt;p&gt;These databases can scale automatically with your application’s needs.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;Object Storage: If your application deals with files (e.g., images, documents), use cloud storage solutions like:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Amazon S3&lt;/li&gt;
&lt;li&gt;Google Cloud Storage&lt;/li&gt;
&lt;li&gt;Azure Blob Storage&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;/ul&gt;

&lt;p&gt;These services scale based on usage and don’t require server management.&lt;/p&gt;

&lt;h5&gt;
  
  
  6. Handle Authentication and Authorization
&lt;/h5&gt;

&lt;p&gt;For secure access, it’s essential to integrate authentication into your serverless application.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;Authentication:&lt;/code&gt; Use services like &lt;code&gt;AWS Cognito, Firebase Authentication,&lt;/code&gt; or &lt;code&gt;Azure Active Directory&lt;/code&gt; to authenticate users.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;&lt;code&gt;Authorization:&lt;/code&gt; Implement role-based access control (RBAC) or policies to control which users or services can access specific resources.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;For example:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;AWS Cognito can authenticate users, and then AWS API Gateway can authorize requests using IAM roles or Lambda authorizers.&lt;/li&gt;
&lt;/ul&gt;

&lt;h5&gt;
  
  
  7. Deploy Serverless Functions and Infrastructure
&lt;/h5&gt;

&lt;p&gt;After your functions are developed, you’ll need to deploy them to the cloud. Here’s how you can go about it:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;p&gt;&lt;code&gt;Serverless Framework:&lt;/code&gt; One of the most popular tools for deploying serverless applications is the Serverless Framework. It abstracts much of the complexity and makes deploying easier.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Command: serverless deploy to automatically upload your functions and resources to the cloud.&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;li&gt;

&lt;p&gt;&lt;code&gt;Other Deployment Tools:&lt;/code&gt; You can also use native tools provided by your cloud provider, such as:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;AWS SAM (Serverless Application Model)&lt;/li&gt;
&lt;li&gt;Google Cloud Deployment Manager&lt;/li&gt;
&lt;li&gt;Azure Functions Deployment&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;li&gt;&lt;p&gt;&lt;code&gt;CI/CD Pipeline:&lt;/code&gt; Set up continuous integration and delivery (CI/CD) pipelines using tools like GitLab CI, GitHub Actions, or AWS CodePipeline to automate deployments and updates.&lt;/p&gt;&lt;/li&gt;

&lt;/ul&gt;

&lt;h5&gt;
  
  
  8. Monitor and Log Serverless Functions
&lt;/h5&gt;

&lt;p&gt;Monitoring and logging are vital for debugging and understanding how your functions are performing in the cloud.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;Cloud-native Monitoring:&lt;/code&gt; Use services like &lt;code&gt;AWS CloudWatch, Google Stackdriver, or Azure Monitor&lt;/code&gt; to track the performance and logs of your serverless functions.&lt;/li&gt;
&lt;li&gt;
&lt;p&gt;&lt;code&gt;Metrics to Monitor:&lt;/code&gt; Keep an eye on:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Function execution times&lt;/li&gt;
&lt;li&gt;Invocation counts&lt;/li&gt;
&lt;li&gt;Errors and failures&lt;/li&gt;
&lt;li&gt;Cold start durations&lt;/li&gt;
&lt;/ul&gt;


&lt;/li&gt;

&lt;li&gt;&lt;p&gt;Example: AWS Lambda’s CloudWatch Logs provide detailed logs of function execution, which can help debug errors or optimize performance.&lt;/p&gt;&lt;/li&gt;

&lt;/ul&gt;

&lt;h5&gt;
  
  
  9. Implement Caching and Optimization (Optional)
&lt;/h5&gt;

&lt;p&gt;For performance optimization, serverless applications often require caching mechanisms to minimize response time and reduce costs.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;Cache Responses:&lt;/code&gt; Use services like AWS API Gateway caching, AWS CloudFront, or Google Cloud CDN to cache responses from your functions.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;Optimize Functions:&lt;/code&gt; Refactor serverless functions to reduce cold start times or handle higher volumes of requests effectively.&lt;/li&gt;
&lt;/ul&gt;

&lt;h5&gt;
  
  
  10. Test and Iterate
&lt;/h5&gt;

&lt;p&gt;Before launching, thoroughly test your serverless application to ensure that it meets your performance and functionality requirements:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;Unit Testing:&lt;/code&gt; Test individual functions using frameworks like Jest (for Node.js functions) or PyTest (for Python).&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;Integration Testing:&lt;/code&gt; Test the integration of serverless functions with other services (e.g., databases, storage, APIs).&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;Load Testing:&lt;/code&gt; Simulate high-traffic scenarios to ensure your serverless functions can handle sudden spikes in traffic without failing or becoming too slow.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Example Serverless Workflow for an E-commerce Application:
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;User Browsing Product:&lt;/strong&gt; User accesses the product page; a request is sent to the serverless function via API Gateway.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Fetch Product Data:&lt;/strong&gt; Lambda function queries a NoSQL database (e.g., DynamoDB) and returns product details to the front-end.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;User Makes Purchase:&lt;/strong&gt; User checks out and an API Gateway request triggers a payment processing function in Lambda.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Payment Processed:&lt;/strong&gt; Payment information is processed via an external API (e.g., Stripe) and the order is saved to DynamoDB.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Confirmation Email:&lt;/strong&gt; A separate Lambda function sends an order confirmation email using an email service like AWS SES.&lt;/li&gt;
&lt;/ol&gt;

&lt;h3&gt;
  
  
  Pros of Serverless Architecture:
&lt;/h3&gt;

&lt;h5&gt;
  
  
  1. Cost Efficiency:
&lt;/h5&gt;

&lt;ul&gt;
&lt;li&gt;Pay-per-use model: With serverless, you only pay for the compute resources you use. You aren’t paying for idle server time, which makes it a highly cost-efficient option, especially for applications with variable traffic.&lt;/li&gt;
&lt;li&gt;No infrastructure management costs: Developers don’t need to worry about managing or maintaining servers, reducing operational overhead.&lt;/li&gt;
&lt;/ul&gt;

&lt;h5&gt;
  
  
  2. Scalability:
&lt;/h5&gt;

&lt;ul&gt;
&lt;li&gt;Automatic scaling: Serverless platforms automatically scale to accommodate the demand. When there is an influx of requests, the platform scales up, and when demand decreases, it scales down without manual intervention.&lt;/li&gt;
&lt;li&gt;No need to plan for peak loads: You don’t have to worry about provisioning for peak capacity, which reduces unnecessary costs.&lt;/li&gt;
&lt;/ul&gt;

&lt;h5&gt;
  
  
  3. Faster Time to Market:
&lt;/h5&gt;

&lt;ul&gt;
&lt;li&gt;Simplified development: Since developers don’t need to manage infrastructure, they can focus purely on writing code, speeding up the development process.&lt;/li&gt;
&lt;li&gt;Managed services: Serverless platforms often come with a variety of pre-configured services such as databases, authentication, and storage, which accelerate development.&lt;/li&gt;
&lt;/ul&gt;

&lt;h5&gt;
  
  
  4. Flexibility and Focus on Code:
&lt;/h5&gt;

&lt;ul&gt;
&lt;li&gt;Developers only need to focus on the application logic, as the cloud provider handles everything else (e.g., scaling, load balancing, and provisioning).&lt;/li&gt;
&lt;li&gt;This allows businesses to innovate faster and focus on their product instead of infrastructure.&lt;/li&gt;
&lt;/ul&gt;

&lt;h5&gt;
  
  
  5. Reduced Operational Complexity:
&lt;/h5&gt;

&lt;ul&gt;
&lt;li&gt;No server management: No need to manage or patch servers, which simplifies the operational aspect of running applications.&lt;/li&gt;
&lt;li&gt;Built-in monitoring and logging: Many serverless platforms offer built-in monitoring, which helps developers track performance without extra setup.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Cons of Serverless Architecture:
&lt;/h3&gt;

&lt;h5&gt;
  
  
  1. Cold Starts:
&lt;/h5&gt;

&lt;ul&gt;
&lt;li&gt;Latency issues: When a function is called after a period of inactivity, it can experience “cold start” delays. This happens because the platform must initialize the serverless function before it can execute, leading to higher latency.&lt;/li&gt;
&lt;li&gt;Impact on performance: This can negatively affect user experience, especially in real-time applications.&lt;/li&gt;
&lt;/ul&gt;

&lt;h5&gt;
  
  
  2. Vendor Lock-in:
&lt;/h5&gt;

&lt;ul&gt;
&lt;li&gt;Dependence on cloud provider: Serverless applications are often tightly coupled with the cloud provider’s ecosystem. Migrating to a different provider could be challenging and costly, leading to vendor lock-in.&lt;/li&gt;
&lt;li&gt;Limited portability: Since each cloud provider has its own proprietary offerings and services, serverless applications may not be easily portable across different platforms.&lt;/li&gt;
&lt;/ul&gt;

&lt;h5&gt;
  
  
  3. Limited Control and Customization:
&lt;/h5&gt;

&lt;ul&gt;
&lt;li&gt;Less control over infrastructure: Since the infrastructure is abstracted away, developers have limited control over the underlying environment and configuration, which could be restrictive for certain use cases.&lt;/li&gt;
&lt;li&gt;Harder debugging and testing: Testing serverless functions locally can be difficult, and debugging issues in a cloud environment may require a different approach compared to traditional server-based applications.&lt;/li&gt;
&lt;/ul&gt;

&lt;h5&gt;
  
  
  4. Resource Limits:
&lt;/h5&gt;

&lt;ul&gt;
&lt;li&gt;Execution time limits: Many serverless providers impose execution time limits on functions, meaning that long-running processes may not be suitable for serverless architecture.&lt;/li&gt;
&lt;li&gt;Memory and storage restrictions: Some platforms may have limits on the amount of memory, storage, or concurrent executions, which could pose challenges for certain applications.&lt;/li&gt;
&lt;/ul&gt;

&lt;h5&gt;
  
  
  5. Security Concerns:
&lt;/h5&gt;

&lt;ul&gt;
&lt;li&gt;Surface area for attacks: Serverless applications might increase the attack surface since each function can be seen as an individual service. Ensuring proper security configurations for each function is crucial.&lt;/li&gt;
&lt;li&gt;Cold start vulnerability: Cold starts could also potentially introduce security concerns if attackers manage to exploit the delay in execution.&lt;/li&gt;
&lt;/ul&gt;

&lt;h5&gt;
  
  
  6. Harder for Stateful Applications:
&lt;/h5&gt;

&lt;ul&gt;
&lt;li&gt;Not ideal for long-running, stateful applications: Serverless functions are inherently stateless, so handling stateful workloads (like sessions or persistent user data) requires additional architecture, often involving external services like databases or storage.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Real-Life Examples of Serverless Usage:
&lt;/h3&gt;

&lt;h5&gt;
  
  
  1. Netflix:
&lt;/h5&gt;

&lt;ul&gt;
&lt;li&gt;Netflix uses AWS Lambda to handle tasks like user authentication and video streaming events. The platform's scalability is enhanced by serverless architecture to handle massive traffic spikes.&lt;/li&gt;
&lt;/ul&gt;

&lt;h5&gt;
  
  
  2. Airbnb:
&lt;/h5&gt;

&lt;ul&gt;
&lt;li&gt;Airbnb utilizes AWS Lambda for serverless functions to manage reservations and user notifications, benefiting from the automatic scaling during traffic spikes (e.g., peak booking seasons).&lt;/li&gt;
&lt;/ul&gt;

&lt;h5&gt;
  
  
  3. Slack:
&lt;/h5&gt;

&lt;ul&gt;
&lt;li&gt;Slack uses serverless functions to handle real-time notifications and interactions, which can scale up and down as needed based on user activity.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Serverless Architecture Use Cases
&lt;/h3&gt;

&lt;p&gt;Serverless architecture is ideal for many types of applications due to its scalability, flexibility, and cost efficiency. Here are several use cases where serverless architecture excels:&lt;/p&gt;

&lt;h5&gt;
  
  
  1. Web and Mobile Backends
&lt;/h5&gt;

&lt;p&gt;Serverless is well-suited for building backends for web or mobile applications because it scales automatically based on demand.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;h6&gt;
  
  
  Example Use Case: E-commerce application backend
&lt;/h6&gt;

&lt;p&gt;When users visit an e-commerce website, serverless functions can handle requests like searching for products, checking out, and updating user information. Since traffic can vary (more during sales or peak hours), serverless applications automatically scale to handle surges, and you only pay for the time spent processing requests.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;h6&gt;
  
  
  Why Serverless?:
&lt;/h6&gt;

&lt;p&gt;Serverless architectures, such as AWS Lambda and Google Cloud Functions, automatically scale based on incoming requests. With serverless, developers can focus on business logic without worrying about managing infrastructure, providing cost-efficient and responsive web and mobile app backends.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;h5&gt;
  
  
  2. Real-Time Data Processing
&lt;/h5&gt;

&lt;p&gt;Serverless architectures are great for processing streams of data in real-time.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;h6&gt;
  
  
  Example Use Case: Real-time analytics
&lt;/h6&gt;

&lt;p&gt;Consider a service like Twitter that processes massive streams of tweets or a stock trading platform analyzing real-time data. Serverless functions can be used to process and transform real-time data, aggregate results, and store them in databases.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;h6&gt;
  
  
  Why Serverless?:
&lt;/h6&gt;

&lt;p&gt;Serverless functions are well-suited for short-lived, event-driven tasks. Cloud services such as AWS Lambda or Azure Functions can process events as they come, such as data streams from Kafka, Kinesis, or Google Cloud Pub/Sub, without requiring a full-time server.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;h5&gt;
  
  
  3. Image or File Processing
&lt;/h5&gt;

&lt;p&gt;Serverless functions can handle image manipulation, video encoding, or file format conversion tasks. This is especially useful when working with images, audio files, or videos uploaded by users.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;h6&gt;
  
  
  Example Use Case: Image resizing and thumbnail generation
&lt;/h6&gt;

&lt;p&gt;When a user uploads an image to a site like Instagram or Flickr, serverless functions can automatically resize the image into multiple formats or create thumbnails for faster display.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;h6&gt;
  
  
  Why Serverless?:
&lt;/h6&gt;

&lt;p&gt;Serverless functions can be triggered by file uploads to cloud storage (e.g., AWS S3, Google Cloud Storage). Functions only run when needed (e.g., to resize or optimize an image), and you pay for the actual processing time. This makes it cost-effective, as you don’t need to run a server waiting for uploads.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;h5&gt;
  
  
  4. Chatbots and AI/ML Integration
&lt;/h5&gt;

&lt;p&gt;Serverless is a great fit for running small, event-driven tasks like processing chatbot messages, executing machine learning models, or interacting with AI APIs.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;h6&gt;
  
  
  Example Use Case: Customer support chatbot
&lt;/h6&gt;

&lt;p&gt;A company integrates a serverless chatbot to handle customer inquiries, where serverless functions process natural language queries and connect to an AI backend (like AWS Lex or Google Dialogflow) to generate responses.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;h6&gt;
  
  
  Why Serverless?:
&lt;/h6&gt;

&lt;p&gt;Serverless functions handle individual requests, and they scale up or down based on the volume of queries. Machine learning or AI models can be invoked via serverless functions to process requests in real-time, without requiring a long-running backend server.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;h5&gt;
  
  
  5. Event-Driven Applications
&lt;/h5&gt;

&lt;p&gt;Serverless is perfect for applications that require event-driven workflows, such as responding to events or triggers from other services.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;h6&gt;
  
  
  Example Use Case: IoT device data processing
&lt;/h6&gt;

&lt;p&gt;In an Internet of Things (IoT) setup, data from sensors or devices can be processed in real-time using serverless functions. For example, data from a smart thermostat (temperature readings) can trigger a serverless function that adjusts a home’s heating or cooling system.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;h6&gt;
  
  
  Why Serverless?:
&lt;/h6&gt;

&lt;p&gt;Serverless functions are ideal for event-driven workloads. The architecture works well with services that generate events or notifications, such as cloud storage (file uploads), databases (data changes), or messaging queues. Since serverless functions are triggered by events, they can process these events as they happen.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;h5&gt;
  
  
  6. Handling Webhooks and APIs
&lt;/h5&gt;

&lt;p&gt;Serverless is a natural fit for handling webhooks and lightweight API processing.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;h6&gt;
  
  
  Example Use Case: Processing payment gateway notifications
&lt;/h6&gt;

&lt;p&gt;When a payment is processed via a service like Stripe, a webhook is triggered to notify your system. A serverless function can process the webhook, update the user’s account, and handle any further actions.&lt;/p&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;h6&gt;
  
  
  Why Serverless?:
&lt;/h6&gt;

&lt;p&gt;Serverless functions are lightweight, cost-efficient, and can easily handle webhooks or lightweight API requests. You can create endpoints using API Gateway (AWS, Azure, etc.) that invoke serverless functions upon receiving an HTTP request.&lt;/p&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  The Future of Serverless Computing
&lt;/h3&gt;

&lt;p&gt;The future of serverless computing appears incredibly bright as the technology continues to evolve and adapt to new challenges and opportunities. As we look forward, we can anticipate significant advancements that will enhance the security and reliability of serverless platforms, addressing the notable limitations.&lt;/p&gt;

&lt;p&gt;One of the primary benefits of serverless computing is its ability to scale effortlessly according to application demands without manual intervention in server management. Future developments will further capitalize on this advantage, refining auto-scaling capabilities to become more responsive and cost-effective.&lt;/p&gt;

&lt;p&gt;Moreover, integrating serverless architecture with cutting-edge technologies like artificial intelligence (AI) and machine learning (ML) promises to revolutionize how businesses approach problem-solving and innovation.&lt;/p&gt;

&lt;p&gt;When discussing serverless pros and cons, it’s also worth mentioning security as a critical concern for many organizations considering serverless. This aspect will likely see robust enhancements soon. As serverless platforms mature, we expect more sophisticated security protocols embedded into the architecture. Such technologies offer tighter controls and more robust protection measures against potential cyber threats.&lt;/p&gt;

&lt;p&gt;In summary, the future of serverless computing is not just about maintaining the status quo but pushing the boundaries of cloud technology possibilities.&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>javascript</category>
      <category>programming</category>
      <category>beginners</category>
    </item>
    <item>
      <title>Reverse an array in different ways.</title>
      <dc:creator>Jyoti chaudhary</dc:creator>
      <pubDate>Thu, 06 Feb 2025 10:18:43 +0000</pubDate>
      <link>https://dev.to/jyotich15/reverse-an-array-in-different-ways-8kk</link>
      <guid>https://dev.to/jyotich15/reverse-an-array-in-different-ways-8kk</guid>
      <description>&lt;p&gt;There is a built-in array method in Javascript that reverses the array i.e. &lt;code&gt;reverse()&lt;/code&gt; method.&lt;/p&gt;

&lt;h5&gt;
  
  
  1. Using reverse() method:
&lt;/h5&gt;

&lt;blockquote&gt;
&lt;p&gt;reverse() method: The reverse() method reverses the array in place, meaning it modifies the original array directly and does not return a new array.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h6&gt;
  
  
  Example:
&lt;/h6&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const givenArr = [5, 2, 3, 7, 9, 15, 20];
const reversedArr1 = givenArr.reverse();

// Prints the reversed array
console.log(reversedArr1);  // Output: [20, 15, 9, 7, 3, 2, 5]
console.log(givenArr);  // Output: [20, 15, 9, 7, 3, 2, 5]

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;The reverse() method directly modifies the original array by reversing its elements.&lt;/li&gt;
&lt;li&gt;The reversed array is also returned as the result of the method&lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;code&gt;In the above example, If you want to avoid modifying the original array, you can first create a copy of the array using .slice() and then apply .reverse() to the copy.&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;
&lt;/blockquote&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const givenArr = [5, 2, 3, 7, 9, 15, 20];

// Create a copy of the array and reverse the copy
const reversedArr = givenArr.slice().reverse();

console.log(reversedArr);  // Output: [20, 15, 9, 7, 3, 2, 5]
console.log(givenArr);   // Output: [5, 2, 3, 7, 9, 15, 20]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h5&gt;
  
  
  2. Using a for-loop:
&lt;/h5&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const givenArr = [5, 12, 3, 7, 21, 9, 45, 90];
const printReversedArr = (arr) =&amp;gt; {
    const arrLen = arr.length;
    for(let i = 0; i &amp;lt; arrLen / 2; i++) {
        let temp = arr[i];
        arr[i] = arr[arrLen - 1 - i];
        arr[arrLen - 1 - i] = temp
    }
    return arr ;
}
console.log(printReversedArr(givenArr));  // Output: [90, 45, 9, 21, 7, 3, 12, 5]

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h5&gt;
  
  
  3. Using a for-loop (with a new array):
&lt;/h5&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const givenArr = [5, 12, 3, 7, 21, 9, 45, 90];
const getReverseArr = (arr) =&amp;gt; {
    let reversedArr = [];
    for(let i = arr.length - 1; i &amp;gt;= 0 ; i --) {
        reversedArr.push(arr[i]);
    }
    return reversedArr;
}
console.log(getReverseArr(givenArr));  // Output: [90, 45, 9, 21, 7, 3, 12, 5]

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h5&gt;
  
  
  4. Using forEach() method:
&lt;/h5&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const givenArr = [ 12, 3, 21, 9, 45, 22, 7];
const reverseArray = (arr) =&amp;gt; {
    let reversedArr = [];
    arr.forEach(item =&amp;gt; {
        reversedArr.unshift(item);
    });
    return reversedArr;
}
console.log(reverseArray(givenArr));  // Output: [7, 22, 45, 9, 21, 3, 12]

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h5&gt;
  
  
  5. Using reduce() method:
&lt;/h5&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const givenArr = [ 12, 3, 21, 9, 45, 22, 7];
const reverseArray = (arr) =&amp;gt; {
    return arr.reduce((reversed, current) =&amp;gt; [current, ...reversed], []);
}
console.log(reverseArray(givenArr));  // Output: [7, 22, 45, 9, 21, 3, 12]

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h5&gt;
  
  
  6. Using unshift() method:
&lt;/h5&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const givenArr = [5, 2, 3, 7, 9, 15, 20];
const  reverseArray = (arr) =&amp;gt; {
    let reversedArr = [];
    for (let i = 0; i &amp;lt; arr.length; i++) {
        reversedArr.unshift(arr[i]);
    }
    return reversedArr;
}
console.log(reverseArray(givenArr));  // Output: [20, 15, 9, 7, 3, 2, 5]

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h5&gt;
  
  
  7. Using a while loop (in-place modification):
&lt;/h5&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const givenArr = [10, 6, 9, 3, 4, 5, 1];
const reverseArray = (arr) =&amp;gt; {
    let start = 0;
    let end = arr.length - 1;
    while (start &amp;lt; end) {
        // Swap elements at start and end
        let temp = arr[start];
        arr[start] = arr[end];
        arr[end] = temp;

        start++;
        end--;
    }
    return arr;
}
console.log(reverseArray(givenArr));  // Output: [1, 5, 4, 3, 9, 6, 10]

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h5&gt;
  
  
  8. Using recursion:
&lt;/h5&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const givenArr = [10, 6, 9, 3, 4, 5, 1];
const reverseArray = (arr) =&amp;gt;  {
    if (arr.length === 0) {
        return arr;
    } else {
        return reverseArray(arr.slice(1)).concat(arr[0]);
    }
}
console.log(reverseArray(givenArr));  // Output: [1, 5, 4, 3, 9, 6, 10]
console.log("Original Array: ", givenArr);  // Output: Original Array: [10, 6, 9, 3, 4, 5, 1]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



</description>
      <category>javascript</category>
      <category>webdev</category>
      <category>programming</category>
      <category>beginners</category>
    </item>
    <item>
      <title>Closure in JavaScript</title>
      <dc:creator>Jyoti chaudhary</dc:creator>
      <pubDate>Wed, 05 Feb 2025 08:57:11 +0000</pubDate>
      <link>https://dev.to/jyotich15/closure-in-javascript-1ako</link>
      <guid>https://dev.to/jyotich15/closure-in-javascript-1ako</guid>
      <description>&lt;p&gt;A closure is the combination of a function and the lexical environment within which that function was declared.&lt;br&gt;
                        &lt;code&gt;OR&lt;/code&gt;&lt;br&gt;
A closure in JavaScript is a function that remembers its lexical scope (the scope in which it was created) even when it is executed outside that scope. This means that a function can "remember" the environment in which it was created, including any variables that were in scope at the time.&lt;/p&gt;

&lt;p&gt;Imagine you want to speed posting some documents. You put all the documents in an envelope and sealed it. All the documents are inside the envelope and after speed posting from one place to another, the documents are still inside it. Similarly, a closure "remembers" the variables from the place where it was created, even after it moves to a different place in the code.&lt;/p&gt;

&lt;h4&gt;
  
  
  Lexical Scoping:
&lt;/h4&gt;

&lt;p&gt;JavaScript functions are lexically scoped, meaning that they can access variables from the surrounding code in which they were defined, even if that surrounding code is no longer in execution.&lt;/p&gt;

&lt;h6&gt;
  
  
  In simple terms:
&lt;/h6&gt;

&lt;ul&gt;
&lt;li&gt;Lexical scope means that the scope of a variable is defined by where it is written in the code, not where it is called from.&lt;/li&gt;
&lt;li&gt;A closure captures variables from the outer scope at the time the function is created, not when it is called.&lt;/li&gt;
&lt;/ul&gt;

&lt;h5&gt;
  
  
  How does closure work?
&lt;/h5&gt;

&lt;p&gt;In a closure, when a function is declared inside another function, it gets access to the outer function's variables. Even after the outer function has finished executing, the inner function retains access to those variables.&lt;/p&gt;

&lt;h6&gt;
  
  
  1: Basic Closure Example:
&lt;/h6&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function outerFunction() {
  let outerVariable = 'I am outside!';

  function innerFunction() {
    console.log(outerVariable);  // Inner function uses outerVariable
  }

  return innerFunction;
}

const closureFunc = outerFunction();  // Call the outer function
closureFunc();  // Even though outerFunction is done, innerFunction can still access outerVariable

// Output: I am outside!

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h6&gt;
  
  
  Explanation:
&lt;/h6&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;&lt;code&gt;outerFunction&lt;/code&gt;&lt;/strong&gt; has a variable called &lt;strong&gt;&lt;code&gt;outerVariable&lt;/code&gt;&lt;/strong&gt; and it returns another function (called &lt;strong&gt;&lt;code&gt;innerFunction&lt;/code&gt;&lt;/strong&gt;).&lt;/li&gt;
&lt;li&gt;When &lt;strong&gt;&lt;code&gt;outerFunction()&lt;/code&gt;&lt;/strong&gt; is called, it returns the &lt;strong&gt;&lt;code&gt;innerFunction&lt;/code&gt;&lt;/strong&gt;.&lt;/li&gt;
&lt;li&gt;Even though &lt;strong&gt;&lt;code&gt;outerFunction&lt;/code&gt;&lt;/strong&gt; has finished executing by the time &lt;strong&gt;&lt;code&gt;closureFunc&lt;/code&gt;&lt;/strong&gt; is called, the &lt;strong&gt;&lt;code&gt;innerFunction&lt;/code&gt;&lt;/strong&gt; still remembers the &lt;strong&gt;&lt;code&gt;outerVariable&lt;/code&gt;&lt;/strong&gt; that was declared in the outer function. This is the &lt;strong&gt;&lt;code&gt;closure&lt;/code&gt;&lt;/strong&gt;.&lt;/li&gt;
&lt;/ol&gt;

&lt;h6&gt;
  
  
  2: Closure with Arguments:
&lt;/h6&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function multiplier(x) {
  return function(y) {
    return x * y;
  }
}

const multiplyBy = multiplier(5);
console.log(multiplyBy(10));  // Output: 50
console.log(multiplyBy(6));  // Output: 30

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h6&gt;
  
  
  Explanation:
&lt;/h6&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;code&gt;multiplier&lt;/code&gt; is a function that takes a parameter x and returns an inner function.&lt;/li&gt;
&lt;li&gt;The inner function takes a parameter y and returns the multiply of x and y.&lt;/li&gt;
&lt;li&gt;When we call &lt;code&gt;multiplier(5)&lt;/code&gt;, it returns a new function that multiplies 5 by any number passed into it.&lt;/li&gt;
&lt;li&gt;Each call to &lt;code&gt;multiplyBy&lt;/code&gt; remembers x = 5 (from the outer scope) and can access it to calculate the result.&lt;/li&gt;
&lt;/ol&gt;

&lt;h6&gt;
  
  
  3: Closures and SetTimeout
&lt;/h6&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function createCounter() {
    let count = 0;

    function innerCounter() {
      count++;
      console.log(count);
    }
  return innerCounter;
  }

  const counter = createCounter();
  counter();                  // Immedietely Output 1
  setTimeout(counter, 1000);  // Output after 1 second: 2
  setTimeout(counter, 2000);  // Output after 2 seconds: 3
  setTimeout(counter, 3000);  // Output after 3 seconds: 4

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h6&gt;
  
  
  Explanation:
&lt;/h6&gt;

&lt;ol&gt;
&lt;li&gt;The function &lt;code&gt;createCounter&lt;/code&gt; defines a variable &lt;code&gt;count&lt;/code&gt; and returns a function &lt;code&gt;innerCounter&lt;/code&gt; that increments &lt;code&gt;count&lt;/code&gt; each time it is called.&lt;/li&gt;
&lt;li&gt;Even though &lt;code&gt;createCounter&lt;/code&gt; has finished executing, the returned function (the closure) still "remembers" &lt;code&gt;count&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;The &lt;code&gt;setTimeout&lt;/code&gt; calls invoke the returned function, and the counter continues to increment as expected.&lt;/li&gt;
&lt;/ol&gt;

&lt;h6&gt;
  
  
  4: Practical Use of Closure (Data Encapsulation)
&lt;/h6&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function Counter() {
  let count = 0;  // private variable

  this.increment = function() {
    count++;
    console.log(count);
  }

  this.decrement = function() {
    count--;
    console.log(count);
  }

  this.getCount = function() {
    return count;
  }
}

const myCounter = new Counter();
myCounter.increment(); // Output: 1
myCounter.increment(); // Output: 2
myCounter.decrement(); // Output: 1
console.log(myCounter.getCount()); // Output: 1

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h6&gt;
  
  
  Explanation:
&lt;/h6&gt;

&lt;ol&gt;
&lt;li&gt;The &lt;code&gt;Counter&lt;/code&gt; function acts as a constructor, defining a private variable &lt;code&gt;count&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;The methods &lt;code&gt;increment&lt;/code&gt;, &lt;code&gt;decrement&lt;/code&gt;, and &lt;code&gt;getCount&lt;/code&gt; form closures because they have access to the &lt;code&gt;count&lt;/code&gt; variable.&lt;/li&gt;
&lt;li&gt;Outside code cannot directly access or modify &lt;code&gt;count&lt;/code&gt;; it can only interact with it via the provided methods.&lt;/li&gt;
&lt;/ol&gt;

&lt;h5&gt;
  
  
  Why Closures are Important?
&lt;/h5&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Data Privacy/Encapsulation:&lt;/strong&gt; You can create private variables that cannot be accessed directly from the outside world, but can still be manipulated via functions (like in the Counter example above).&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Function Factories:&lt;/strong&gt; Closures allow you to create customized versions of a function, like the makeAdder example.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Asynchronous Programming:&lt;/strong&gt; Closures are useful in scenarios like asynchronous code, where functions need to "remember" their environment (like the setTimeout example).&lt;/li&gt;
&lt;/ul&gt;

&lt;h5&gt;
  
  
  Performance Consideration
&lt;/h5&gt;

&lt;p&gt;While closures are a powerful tool, they come with some potential performance implications:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Memory Usage:&lt;/strong&gt; A closure can keep a reference to its outer variables, potentially leading to higher memory usage. If you create many closures that capture large amounts of data, it could slow down the application.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Garbage Collection:&lt;/strong&gt; Closures may delay the garbage collection of variables they capture. If you no longer need the closure, ensure you release references to it.&lt;/li&gt;
&lt;/ul&gt;

&lt;h5&gt;
  
  
  Key Concept:
&lt;/h5&gt;

&lt;ul&gt;
&lt;li&gt;A closure is created &lt;strong&gt;when a function has access to its parent function’s variables&lt;/strong&gt;, even after the parent function has finished executing.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;The inner function "closes over" the variables&lt;/strong&gt; from the outer function, which is why it’s called a closure.&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>webdev</category>
      <category>javascript</category>
      <category>beginners</category>
      <category>programming</category>
    </item>
    <item>
      <title>Event Loop</title>
      <dc:creator>Jyoti chaudhary</dc:creator>
      <pubDate>Tue, 04 Feb 2025 10:50:11 +0000</pubDate>
      <link>https://dev.to/jyotich15/event-loop-49he</link>
      <guid>https://dev.to/jyotich15/event-loop-49he</guid>
      <description>&lt;p&gt;The Event Loop is a fundamental concept in JavaScript that helps manage how code is executed, particularly when dealing with asynchronous operations like fetching data from an API or setting timers. Understanding the Event Loop is key to grasping how JavaScript handles tasks in a non-blocking manner.&lt;/p&gt;

&lt;p&gt;JavaScript is a single-threaded language, meaning it can only do one thing at a time. However, JavaScript often needs to handle multiple tasks simultaneously, such as waiting for user input or fetching data from the internet. This is where the Event Loop comes in.&lt;/p&gt;

&lt;p&gt;The timers (setTimeout() and setInterval()) are handled by the event loop mechanism in JavaScript. When you use timers, you’re asking the JavaScript runtime to wait for the delay, and when the delay expires, the callback function is pushed into the event queue.&lt;/p&gt;

&lt;p&gt;Here’s what happens under the hood:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;JavaScript runs the code line by line.&lt;/li&gt;
&lt;li&gt;When a timer is called (e.g., setTimeout()), it schedules the callback function in the event queue after the specified delay.&lt;/li&gt;
&lt;li&gt;The event loop checks if the call stack is empty. Once it's empty, it pulls the callback from the event queue and executes it.&lt;/li&gt;
&lt;/ol&gt;

&lt;h4&gt;
  
  
  How Event Loop Cycle works:
&lt;/h4&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fhyo2y47k5p5pv7z9p546.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fhyo2y47k5p5pv7z9p546.png" alt="Event Loop Cycle" width="774" height="510"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h4&gt;
  
  
  Example
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;   function runTasks() {
       console.log("Running Task 1.")

        setTimeout(() =&amp;gt; {
            console.log("Running Task 2.")
        }, 5000);

        setTimeout(() =&amp;gt; {
            console.log("Running Task 3.")
        }, 0);

        setTimeout(() =&amp;gt; {
            console.log("Running Task 4.")
        }, 2000);

        console.log("Running Task 5.")
    }
  runTasks();

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Output
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Running Task 1.
Running Task 5.
Running Task 3.
Running Task 4.
Running Task 2.
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  &lt;strong&gt;Components Involved:&lt;/strong&gt;
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Call Stack:&lt;/strong&gt;

&lt;ul&gt;
&lt;li&gt;The call stack is where JavaScript keeps track of what function is currently being executed. When you call a function, it gets added to the call stack. When that function finishes, it's removed from the stack.&lt;/li&gt;
&lt;li&gt;If the call stack is empty, JavaScript can execute the next piece of code.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Web APIs:&lt;/strong&gt;

&lt;ul&gt;
&lt;li&gt;These are browser-provided features that allow JavaScript to perform tasks like making HTTP requests, setting timers.&lt;/li&gt;
&lt;li&gt;When you use a Web API like &lt;code&gt;setTimeout&lt;/code&gt;, the task is handed off to the browser, which handles it separately.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Callback Queue (Task Queue):&lt;/strong&gt;

&lt;ul&gt;
&lt;li&gt;When an asynchronous task (like an API request or a timer) is completed, the associated callback function (the code that should run after the task is done) is placed in the Callback Queue.&lt;/li&gt;
&lt;li&gt;The Callback Queue holds these functions until the call stack is empty and they can be executed.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Event Loop:&lt;/strong&gt;

&lt;ul&gt;
&lt;li&gt;The Event Loop's job is to constantly check the call stack and the callback queue. If the call stack is empty, it takes the first task from the callback queue and moves it to the call stack for execution.&lt;/li&gt;
&lt;/ul&gt;
&lt;/li&gt;
&lt;/ol&gt;

&lt;h3&gt;
  
  
  Importance of Event Loop:
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Non-blocking Operations:&lt;/strong&gt; The Event Loop allows JavaScript to handle long-running tasks (like network requests) without freezing the entire application.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Responsive User Interfaces:&lt;/strong&gt; By not blocking the tasks, the Event Loop helps keep the UI responsive, even when performing complex operations.&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>webdev</category>
      <category>javascript</category>
      <category>beginners</category>
      <category>programming</category>
    </item>
  </channel>
</rss>
