<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Tuhin Kairi on Medium]]></title>
        <description><![CDATA[Stories by Tuhin Kairi on Medium]]></description>
        <link>https://medium.com/@tuhinkairi?source=rss-486354359cd2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*awbHHLvF3REhZq_ECvjIFA.jpeg</url>
            <title>Stories by Tuhin Kairi on Medium</title>
            <link>https://medium.com/@tuhinkairi?source=rss-486354359cd2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 12:03:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tuhinkairi/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[JavaScript Functions: Declaration, Expression, Arrow, Callback, Higher-Order, Pure Functions, IIFE…]]></title>
            <link>https://medium.com/@tuhinkairi/javascript-functions-declaration-expression-arrow-callback-higher-order-pure-functions-iife-48bef3af94cb?source=rss-486354359cd2------2</link>
            <guid isPermaLink="false">https://medium.com/p/48bef3af94cb</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[recursion]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Tuhin Kairi]]></dc:creator>
            <pubDate>Tue, 08 Sep 2026 20:34:03 GMT</pubDate>
            <atom:updated>2026-09-08T20:34:03.061Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E8pieiqhlZcaXbRD5ASgFQ.png" /><figcaption>JavaScript Functions: Declaration, Expression, Arrow, Callback, Higher-Order, Pure Functions, IIFE &amp; Recursion (Day — 14)</figcaption></figure><h3>JavaScript Functions: Declaration, Expression, Arrow, Callback, Higher-Order, Pure Functions, IIFE &amp; Recursion (Day — 14)</h3><p><em>Learn JavaScript functions from beginner to advanced. Understand function declarations, function expressions, arrow functions, callbacks, higher-order functions, pure functions, IIFE, recursion, and first-class functions with simple examples.</em></p><p>In the previous parts of this <strong>JavaScript Tutorial for Beginners</strong> series, we covered JavaScript fundamentals such as variables, data types, arrays, objects, conditions, loops, and array methods.</p><p>Now it is time to understand one of the most important concepts in JavaScript: <strong>Functions</strong>.</p><p>Functions allow us to organize code into reusable blocks. As you move toward modern JavaScript, you will encounter different ways of creating and using functions, such as <strong>function declarations, function expressions, arrow functions, callbacks, higher-order functions, pure functions, IIFEs, and recursion</strong>.</p><p>Let’s understand each one step by step.</p><h3>What is a Function in JavaScript?</h3><p>A <strong>function</strong> is a reusable block of code designed to perform a specific task.</p><p>Instead of writing the same code multiple times, we can put it inside a function and execute it whenever we need it.</p><pre>function greet() {<br>    console.log(&quot;Hello, JavaScript!&quot;);<br>}<br><br>greet(); //Hello, JavaScript!<br></pre><p>Here:</p><ul><li>function is the keyword used to create a function.</li><li>greet is the function name.</li><li>{} contains the function body.</li><li>greet() calls the function.</li></ul><p>Functions become even more useful when we work with parameters and return values.</p><pre>function add(a, b) {<br>    return a + b;<br>}<br><br>const result = add(10, 20);<br><br>console.log(result);</pre><p>Output:</p><pre>30</pre><h3>1. Function Declaration</h3><p>A <strong>function declaration</strong> is the traditional way of defining a function in JavaScript.</p><pre>function greet(name) {<br>    return `Hello, ${name}`;<br>}<br><br>console.log(greet(&quot;Tuhin&quot;));</pre><p>Output:</p><pre>Hello, Tuhin</pre><h3>Syntax</h3><pre>function functionName(parameters) {<br>    // code<br>}</pre><h3>Important Feature: Hoisting</h3><p>Function declarations are <strong>hoisted</strong>, which means you can call the function before its declaration in the code.</p><pre>greet();</pre><pre>function greet() {<br>    console.log(&quot;Hello!&quot;);<br>}</pre><p>Output:</p><pre>Hello!</pre><p>JavaScript makes the function declaration available before executing the surrounding code.</p><h3>When to use it?</h3><p>Function declarations are useful when:</p><ul><li>You have a named reusable operation.</li><li>The function represents a major piece of application logic.</li><li>You want the function to be callable throughout its scope.</li><li>You prefer traditional and readable function syntax.</li></ul><h3>2. Function Expression</h3><p>A <strong>function expression</strong> is a function assigned to a variable.</p><pre>const greet = function () {<br>    console.log(&quot;Hello!&quot;);<br>};</pre><pre>greet();</pre><p>Here, the function itself is treated as a value and assigned to greet.</p><p>You can also provide a name:</p><pre>const greet = function sayHello() {<br>    console.log(&quot;Hello!&quot;);<br>};</pre><pre>greet();</pre><h3>Function Declaration vs Expression</h3><p>Declaration:</p><pre>function add(a, b) {<br>    return a + b;<br>}</pre><p>Expression:</p><pre>const add = function (a, b) {<br>    return a + b;<br>};</pre><p>One important difference is hoisting.</p><p>This works:</p><pre>greet();</pre><pre>function greet() {<br>    console.log(&quot;Hello&quot;);<br>}</pre><p>But this does not work:</p><pre>greet();</pre><pre>const greet = function () {<br>    console.log(&quot;Hello&quot;);<br>};</pre><p>The variable exists in the temporal dead zone until its declaration is initialized.</p><h3>Why are function expressions useful?</h3><p>They become particularly useful when:</p><ul><li>Functions need to be stored in variables.</li><li>Functions are passed as arguments.</li><li>Functions are returned from other functions.</li><li>You want to create functions dynamically.</li></ul><p>This leads directly to one of JavaScript’s most important concepts: <strong>functions are first-class values</strong>.</p><h3>3. Arrow Functions</h3><p><strong>Arrow functions</strong> were introduced in ES6 and provide a shorter syntax for writing functions.</p><p>Traditional function:</p><pre>function add(a, b) {<br>    return a + b;<br>}</pre><p>Arrow function:</p><pre>const add = (a, b) =&gt; {<br>    return a + b;<br>};</pre><p>You can make it even shorter when the function contains only one expression:</p><pre>const add = (a, b) =&gt; a + b;</pre><h3>Single Parameter</h3><p>Parentheses can be omitted when there is only one parameter.</p><pre>const square = number =&gt; number * number;</pre><p>Instead of:</p><pre>const square = (number) =&gt; {<br>    return number * number;<br>};</pre><h3>No Parameters</h3><p>When there are no parameters, parentheses are required.</p><pre>const greet = () =&gt; {<br>    console.log(&quot;Hello!&quot;);<br>};</pre><h3>Arrow Functions with Array Methods</h3><p>Arrow functions are heavily used with methods such as map(), filter(), and reduce().</p><pre>const numbers = [1, 2, 3, 4];<br><br>const doubled = numbers.map(number =&gt; number * 2);<br><br>console.log(doubled);</pre><p>Output:</p><pre>[2, 4, 6, 8]</pre><h3>Important Difference: this</h3><p>Arrow functions do <strong>not</strong> create their own this.</p><p>Instead, they inherit this from their surrounding lexical scope.</p><p>This makes arrow functions particularly useful in callbacks and modern JavaScript applications.</p><p>However, this also means you should not blindly replace every normal function with an arrow function.</p><h3>4. Callback Functions</h3><p>A <strong>callback function</strong> is a function passed to another function as an argument.</p><p>For example:</p><pre>function greet(name, callback) {<br>    console.log(`Hello ${name}`);<br>    callback();<br>}<br><br><br>function finish() {<br>    console.log(&quot;Finished!&quot;);<br>}<br><br><br>greet(&quot;Tuhin&quot;, finish);</pre><p>Output:</p><pre>Hello Tuhin<br>Finished!</pre><p>Here:</p><ul><li>finish is the callback function.</li><li>greet receives it as an argument.</li><li>greet executes it later.</li></ul><p>Callbacks are extremely common in JavaScript.</p><h3>Example with setTimeout()</h3><pre>setTimeout(() =&gt; {<br>    console.log(&quot;This runs later&quot;);<br>}, 2000);</pre><p>The arrow function is passed to setTimeout() as a callback.</p><p>After approximately 2 seconds, JavaScript executes it.</p><h3>Callbacks with Array Methods</h3><p>You have already seen callbacks when working with array methods.</p><pre>const numbers = [1, 2, 3, 4];</pre><pre>const result = numbers.map(number =&gt; number * 2);</pre><p>The function:</p><pre>number =&gt; number * 2</pre><p>is a callback passed to map().</p><p>This is one reason understanding functions is important before learning advanced JavaScript.</p><h3>5. Higher-Order Functions</h3><p>A <strong>Higher-Order Function (HOF)</strong> is a function that does at least one of these:</p><ul><li>Takes another function as an argument.</li><li>Returns another function.</li></ul><p>For example:</p><pre>function calculate(a, b, operation) {<br>    return operation(a, b);<br>}<br><br>const add = (a, b) =&gt; a + b;<br><br><br>console.log(calculate(10, 20, add));</pre><p>Output:</p><pre>30</pre><p>Here:</p><pre>calculate()</pre><p>is a higher-order function because it accepts another function.</p><h3>Higher-Order Function Returning a Function</h3><p>A function can also return another function.</p><pre>function createMultiplier(multiplier) {<br>    return function (number) {<br>        return number * multiplier;<br>    };<br>}</pre><pre>const double = createMultiplier(2);</pre><pre>console.log(double(5));</pre><p>Output:</p><pre>10</pre><p>The returned function remembers the value of multiplier.</p><p>This behavior is related to another important JavaScript concept called <strong>closures</strong>, which we can explore later in the series.</p><h3>Common Higher-Order Functions</h3><p>You have already used several higher-order functions:</p><ul><li>map()</li><li>filter()</li><li>reduce()</li><li>find()</li><li>some()</li><li>every()</li><li>setTimeout()</li></ul><p>For example:</p><pre>const numbers = [1, 2, 3, 4, 5];</pre><pre>const evenNumbers = numbers.filter(number =&gt; number % 2 === 0);</pre><pre>console.log(evenNumbers);</pre><p>filter() receives a function, so it is a higher-order function.</p><h3>6. Pure Functions</h3><p>A <strong>pure function</strong> is a function that:</p><ul><li>Produces the same output for the same input.</li><li>Does not modify external state or cause unwanted side effects.</li></ul><p>Example:</p><pre>function add(a, b) {<br>    return a + b;<br>}<br><br>console.log(add(10, 20));<br><br>console.log(add(10, 20));</pre><p>Every time we provide 10 and 20, the result is always:</p><pre>30</pre><p>The function does not depend on external variables.</p><h3>Example of an Impure Function</h3><pre>let total = 10;</pre><pre>function addToTotal(value) {<br>    total += value;<br>}</pre><p>This function changes a variable outside itself.</p><p>Therefore, its behavior depends on external state.</p><p>Another example:</p><pre>function addItem(items, item) {<br>    items.push(item);<br>}</pre><p>This modifies the original array.</p><p>A safer approach is to create a new array:</p><pre>function addItem(items, item) {<br>    return [...items, item];<br>}</pre><p>Now the original array remains unchanged.</p><h3>Why Pure Functions Matter</h3><p>Pure functions make code:</p><ul><li>Easier to test.</li><li>Easier to debug.</li><li>More predictable.</li><li>Easier to reuse.</li><li>Safer when managing application state.</li></ul><p>Pure functions are heavily used in functional programming and modern application architecture.</p><h3>7. IIFE — Immediately Invoked Function Expression</h3><p><strong>IIFE</strong> stands for <strong>Immediately Invoked Function Expression</strong>.</p><p>It is a function that is created and executed immediately.</p><pre>(function () {<br>    console.log(&quot;Hello!&quot;);<br>})();</pre><p>Output:</p><pre>Hello!</pre><p>The function does not need to be called separately.</p><h3>IIFE with Parameters</h3><p>You can also pass arguments to an IIFE.</p><pre>(function (name) {<br>    console.log(`Hello ${name}`);<br>})(&quot;Tuhin&quot;);</pre><p>Output:</p><pre>Hello Tuhin</pre><h3>Why Were IIFEs Used?</h3><p>Before modern JavaScript features such as modules and block scope became common, IIFEs were frequently used to create private scopes.</p><p>For example:</p><pre>(function () {<br>    const secret = &quot;hidden&quot;;<br>    console.log(secret);<br>})();</pre><p>The variable secret is not directly accessible outside the function.</p><pre>console.log(secret);</pre><p>This results in an error because secret exists only inside the IIFE.</p><h3>Modern JavaScript</h3><p>IIFEs are less common in modern applications because we now have:</p><ul><li>let</li><li>const</li><li>Block scope</li><li>ES Modules</li></ul><p>However, you may still encounter IIFEs in older JavaScript codebases, libraries, and technical interviews.</p><h3>8. Recursion</h3><p><strong>Recursion</strong> is a technique where a function calls itself.</p><p>A recursive function generally needs two things:</p><ul><li><strong>Base case</strong> → tells the function when to stop.</li><li><strong>Recursive case</strong> → calls the function again with a smaller or simpler problem.</li></ul><p>For example, counting down:</p><pre>function countdown(number) {<br>    if (number === 0) {<br>        return;<br>    }<br>    <br>    console.log(number);<br>    <br>    countdown(number - 1);<br>}<br>countdown(5);</pre><p>Output:</p><pre>5<br>4<br>3<br>2<br>1</pre><p>The important part is:</p><pre>countdown(number - 1);</pre><p>The function calls itself with a smaller value.</p><h3>Factorial Using Recursion</h3><p>A classic recursion example is factorial.</p><p>For example:</p><pre>5! = 5 × 4 × 3 × 2 × 1</pre><p>We can write:</p><pre>function factorial(number) {<br>    if (number === 1) {<br>        return 1;<br>    }<br>    <br>    return number * factorial(number - 1);<br>}<br><br>console.log(factorial(5));</pre><p>Output:</p><pre>120</pre><p>The execution can be understood as:</p><pre>factorial(5)<br>→ 5 × factorial(4)<br>→ 5 × 4 × factorial(3)<br>→ 5 × 4 × 3 × factorial(2)<br>→ 5 × 4 × 3 × 2 × factorial(1)<br>→ 120</pre><h3>Be Careful with Recursion</h3><p>If you forget the base case:</p><pre>function test(number) {<br>    test(number - 1);<br>}</pre><p>the function keeps calling itself until JavaScript eventually throws a <strong>Maximum call stack size exceeded</strong> error.</p><p>Recursion is especially useful for problems involving:</p><ul><li>Trees</li><li>Graph traversal</li><li>Nested data</li><li>Divide-and-conquer algorithms</li><li>Backtracking</li><li>Mathematical problems</li></ul><h3>Functions as First-Class Citizens</h3><p>One concept connects almost everything we discussed today:</p><p><strong>JavaScript treats functions as values.</strong></p><p>This means functions can be:</p><ul><li>Stored in variables.</li><li>Passed as arguments.</li><li>Returned from other functions.</li><li>Stored inside objects or arrays.</li><li>Used as callbacks.</li></ul><p>For example:</p><pre>const greet = function () {<br>    return &quot;Hello&quot;;<br>};</pre><pre>function executeFunction(fn) {<br>    console.log(fn());<br>}</pre><pre>executeFunction(greet);</pre><p>Here, greet is passed into executeFunction() just like any other value.</p><p>This behavior is the foundation for:</p><ul><li>Callbacks</li><li>Higher-order functions</li><li>Functional programming</li><li>Event handling</li><li>Array methods</li><li>Promises</li><li>Async programming</li></ul><p>Understanding this concept will make many advanced JavaScript topics much easier.</p><h3>Quick Summary</h3><ul><li><strong>Function Declaration</strong> → Traditional way to define a named function.</li><li><strong>Function Expression</strong> → Store a function inside a variable.</li><li><strong>Arrow Function</strong> → Shorter function syntax introduced in ES6.</li><li><strong>Callback Function</strong> → A function passed to another function.</li><li><strong>Higher-Order Function</strong> → A function that accepts or returns another function.</li><li><strong>Pure Function</strong> → Same input produces the same output without unwanted side effects.</li><li><strong>IIFE</strong> → Function that executes immediately after being created.</li><li><strong>Recursion</strong> → A function calling itself until a base condition is reached.</li><li><strong>First-Class Functions</strong> → JavaScript allows functions to be treated as values.</li></ul><h3>What’s Next?</h3><p>In the next part of this JavaScript series, we’ll learn how <strong>JavaScript handles errors and exceptions</strong> so our applications can fail gracefully instead of crashing unexpectedly.</p><p>We will cover:</p><ul><li><strong>try</strong> → Run code that might cause an error.</li><li><strong>catch</strong> → Handle the error when one occurs.</li><li><strong>finally</strong> → Run cleanup code regardless of whether an error occurred.</li><li><strong>throw</strong> → Manually create and raise an error.</li><li><strong>Custom Errors</strong> → Create application-specific error types.</li></ul><p>We’ll understand each concept with simple examples and practical use cases.</p><h3>SEO Keywords</h3><p>JavaScript error handling, JavaScript try catch, JavaScript try catch finally, JavaScript finally, JavaScript throw, JavaScript custom errors, JavaScript Error object, JavaScript exceptions, JavaScript error handling for beginners, JavaScript tutorial for beginners, JavaScript errors, handling errors in JavaScript, throw custom error JavaScript, JavaScript custom error class, JavaScript exception handling</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=48bef3af94cb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript Control Flow: if, switch, Loops, break & continue | Day — 13]]></title>
            <link>https://medium.com/@tuhinkairi/javascript-control-flow-if-switch-loops-break-continue-day-13-a5c4d9790734?source=rss-486354359cd2------2</link>
            <guid isPermaLink="false">https://medium.com/p/a5c4d9790734</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[conditional-statements]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[frontend]]></category>
            <dc:creator><![CDATA[Tuhin Kairi]]></dc:creator>
            <pubDate>Tue, 01 Sep 2026 02:03:28 GMT</pubDate>
            <atom:updated>2026-09-01T02:03:28.042Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="JavaScript Control Flow: if, switch, Loops, break &amp; continue | Day — 13" src="https://cdn-images-1.medium.com/max/1024/1*7PhY8dDmtCNCq7hLg3UH-A.png" /><figcaption>JavaScript Control Flow: if, switch, Loops, break &amp; continue | Day — 13</figcaption></figure><p>J<em>avaScript doesn’t always execute code from top to bottom. </em><strong><em>Conditional statements and control flow</em></strong><em> allow your program to make decisions, repeat tasks, and control execution based on different conditions. In this part, we’ll explore </em><em>if, </em><em>else, </em><em>switch, loops, </em><em>break, and </em><em>continue with simple examples that are easy to understand for beginners.</em></p><p>Welcome to <strong>Day — 13 of the JavaScript Tutorial series</strong>.</p><p>So far, we have covered JavaScript fundamentals such as <strong>variables, data types, strings, numbers, arrays, type conversion, and objects</strong>.</p><p>But writing JavaScript isn’t just about storing and manipulating data. We also need to control <strong>which code runs, when it runs, and how many times it runs</strong>.</p><p>This is where <strong>control flow</strong> comes in.</p><p>In this article, we’ll learn:</p><ul><li>if statements</li><li>switch statements</li><li>Loops</li><li>break</li><li>continue</li></ul><h3>What Is Control Flow in JavaScript?</h3><p>Normally, JavaScript executes code from <strong>top to bottom</strong>.</p><pre>console.log(&quot;First&quot;);<br>console.log(&quot;Second&quot;);<br>console.log(&quot;Third&quot;);</pre><p>Output:</p><pre>First<br>Second<br>Third</pre><p>But real applications need decisions and repetition.</p><p>For example:</p><ul><li>If a user is logged in → show the dashboard</li><li>If payment succeeds → create the order</li><li>Repeat a task → use a loop</li><li>Stop a loop early → use break</li><li>Skip the current iteration → use continue</li></ul><p>These are all examples of <strong>control flow</strong>.</p><h3>1. if Statement</h3><p>The if statement allows JavaScript to execute code <strong>only when a condition is true</strong>.</p><h3>Syntax</h3><pre>if (condition) {<br>    // code<br>}</pre><p>Example:</p><pre>const age = 20;</pre><pre>if (age &gt;= 18) {<br>    console.log(&quot;You are an adult&quot;);<br>}</pre><p>Output:</p><pre>You are an adult</pre><p>The condition:</p><pre>age &gt;= 18</pre><p>evaluates to true, so the code inside the if block executes.</p><h3>if…else</h3><p>Sometimes we want to execute one block when the condition is true and another when it is false.</p><pre>const age = 16;</pre><pre>if (age &gt;= 18) {<br>    console.log(&quot;You can vote&quot;);<br>} else {<br>    console.log(&quot;You cannot vote&quot;);<br>}</pre><p>Output:</p><pre>You cannot vote</pre><p>Think of it as:</p><pre>Condition?<br>   |<br>   ├── true  → if block<br>   |<br>   └── false → else block</pre><h3>else if</h3><p>When there are multiple conditions, we can use else if.</p><pre>const marks = 75;</pre><pre>if (marks &gt;= 90) {<br>    console.log(&quot;Grade A+&quot;);<br>} else if (marks &gt;= 80) {<br>    console.log(&quot;Grade A&quot;);<br>} else if (marks &gt;= 70) {<br>    console.log(&quot;Grade B&quot;);<br>} else {<br>    console.log(&quot;Grade C&quot;);<br>}</pre><p>Output:</p><pre>Grade B</pre><p>JavaScript checks the conditions <strong>from top to bottom</strong>.</p><p>Once it finds a true condition, it executes that block and skips the remaining conditions.</p><h3>Nested if</h3><p>An if statement can also exist inside another if.</p><pre>const age = 22;<br>const hasID = true;</pre><pre>if (age &gt;= 18) {<br>    if (hasID) {<br>        console.log(&quot;Entry allowed&quot;);<br>    }<br>}</pre><p>Nested conditions can be useful, but too many nested if statements can make code difficult to maintain.</p><h3>2. switch Statement</h3><p>The switch statement is useful when you want to compare <strong>one value against multiple possible values</strong>.</p><h3>Example</h3><pre>const day = 2;</pre><pre>switch (day) {<br><br>    case 1:<br>        console.log(&quot;Monday&quot;);<br>        break;<br><br>    case 2:<br>        console.log(&quot;Tuesday&quot;);<br>        break;<br><br>    case 3:<br>        console.log(&quot;Wednesday&quot;);<br>        break;<br><br>    default:<br>        console.log(&quot;Invalid day&quot;);<br>}</pre><p>Output:</p><pre>Tuesday</pre><h3>How switch Works</h3><p>JavaScript checks:</p><pre>day === 1<br>day === 2<br>day === 3</pre><p>When it finds a match, it executes that case.</p><p>The break prevents JavaScript from continuing into the next cases.</p><h3>Why Do We Use break?</h3><p>Consider:</p><pre>const day = 2;</pre><pre>switch (day) {<br><br>    case 1:<br>        console.log(&quot;Monday&quot;);<br><br>    case 2:<br>        console.log(&quot;Tuesday&quot;);<br><br>    case 3:<br>        console.log(&quot;Wednesday&quot;);<br>}</pre><p>Output:</p><pre>Tuesday<br>Wednesday</pre><p>Why?</p><p>Because there is no break.</p><p>JavaScript continues executing the following cases. This behavior is called <strong>fall-through</strong>.</p><p>That’s why you’ll commonly see:</p><pre>case 2:<br>    console.log(&quot;Tuesday&quot;);<br>    break;</pre><h3>default</h3><p>The default block runs when none of the cases match.</p><pre>const day = 10;</pre><pre>switch (day) {<br>    <br>     case 1:<br>        console.log(&quot;Monday&quot;);<br>        break;<br>    <br>    case 2:<br>        console.log(&quot;Tuesday&quot;);<br>        break;<br>    <br>    default:<br>        console.log(&quot;Invalid day&quot;);<br>}</pre><p>Output:</p><pre>Invalid day</pre><h3>if vs switch</h3><p>Both can be used for decision-making, but they are suited to different situations.</p><h3>if</h3><p>Good for conditions and ranges:</p><pre>if (age &gt;= 18) {<br>    console.log(&quot;Adult&quot;);<br>}</pre><h3>switch</h3><p>Good for comparing a single value against specific cases:</p><pre>switch (role) {<br>    case &quot;admin&quot;:<br>        console.log(&quot;Full access&quot;);<br>        break;<br>    case &quot;user&quot;:<br>        console.log(&quot;Limited access&quot;);<br>        break;<br>}</pre><p>A simple rule:</p><blockquote><strong><em>Use </em></strong><strong><em>if for conditions and </em></strong><strong><em>switch for multiple exact matches.</em></strong></blockquote><h3>3. Loops</h3><p>Sometimes we need to execute the same block of code multiple times.</p><p>Instead of writing:</p><pre>console.log(1);<br>console.log(2);<br>console.log(3);<br>console.log(4);<br>console.log(5);</pre><p>we can use a loop.</p><p>JavaScript provides several types of loops:</p><ul><li>for</li><li>while</li><li>do...while</li><li>for...of</li><li>for...in</li></ul><h3>for Loop</h3><p>The for loop is one of the most commonly used loops.</p><pre>for (let i = 1; i &lt;= 5; i++) {<br>    console.log(i);<br>}</pre><p>Output:</p><pre>1<br>2<br>3<br>4<br>5</pre><p>A for loop has three important parts:</p><pre>for (initialization; condition; update) {<br>    // code<br>}</pre><p>For our example:</p><pre>for (<br>    let i = 1;   // initialization<br>    i &lt;= 5;      // condition<br>    i++          // update<br>)</pre><p>The flow looks like:</p><pre>Initialize i = 1<br>       ↓<br>Check condition<br>       ↓<br>Run code<br>       ↓<br>Increment i<br>       ↓<br>Check condition again<br>       ↓<br>...</pre><h3>while Loop</h3><p>A while loop runs as long as its condition is true.</p><pre>let i = 1;</pre><pre>while (i &lt;= 5) {<br>    console.log(i);<br>    i++;<br>}</pre><p>Output:</p><pre>1<br>2<br>3<br>4<br>5</pre><p>The condition is checked <strong>before</strong> each iteration.</p><p>Be careful to update the variable.</p><pre>let i = 1;</pre><pre>while (i &lt;= 5) {<br>    console.log(i);<br>}</pre><p>This creates an <strong>infinite loop</strong> because i never changes.</p><h3>do…while Loop</h3><p>A do...while loop is slightly different.</p><p>It executes the code <strong>at least once</strong>, even if the condition is false.</p><pre>let i = 10;</pre><pre>do {<br>    console.log(i);<br>    i++;<br>} while (i &lt;= 5);</pre><p>Output:</p><pre>10</pre><p>Even though:</p><pre>i &lt;= 5</pre><p>is false, the code runs once before the condition is checked.</p><h3>for…of</h3><p>for...of is useful when working with iterable values such as arrays and strings.</p><pre>const languages = [&quot;JavaScript&quot;, &quot;Python&quot;, &quot;C++&quot;];</pre><pre>for (const language of languages) {<br>    console.log(language);<br>}</pre><p>Output:</p><pre>JavaScript<br>Python<br>C++</pre><p>Here, language directly represents each value.</p><h3>for…in</h3><p>for...in is commonly used to iterate over the <strong>keys of an object</strong>.</p><pre>const user = {<br>    name: &quot;Tuhin&quot;,<br>    age: 22,<br>    role: &quot;Developer&quot;<br>};</pre><pre>for (const key in user) {<br>    console.log(key);<br>}</pre><p>Output:</p><pre>name<br>age<br>role</pre><p>To access the values:</p><pre>for (const key in user) {<br>    console.log(user[key]);<br>}</pre><p>Output:</p><pre>Tuhin<br>22<br>Developer</pre><h3>for…of vs for…in</h3><pre>for...of → values<br>for...in → keys</pre><p>For example:</p><pre>const numbers = [10, 20, 30];</pre><pre>for (const value of numbers) {<br>    console.log(value);<br>}</pre><pre>10<br>20<br>30</pre><p>While:</p><pre>for (const index in numbers) {<br>    console.log(index);<br>}</pre><pre>0<br>1<br>2</pre><h3>4. break</h3><p>The break statement immediately <strong>stops a loop</strong>.</p><pre>for (let i = 1; i &lt;= 10; i++) {<br>    if (i === 5) {<br>        break;<br>    }<br>    console.log(i);<br>}</pre><p>Output:</p><pre>1<br>2<br>3<br>4</pre><p>When i becomes 5, break stops the loop.</p><p>Think of it as:</p><blockquote><strong><em>“Stop the loop completely.”</em></strong></blockquote><p>break is also commonly used with switch.</p><h3>5. continue</h3><p>The continue statement does something different.</p><p>It <strong>skips the current iteration</strong> and moves to the next one.</p><pre>for (let i = 1; i &lt;= 5; i++) {<br>    if (i === 3) {<br>        continue;<br>    }<br>    console.log(i);<br>}</pre><p>Output:</p><pre>1<br>2<br>4<br>5</pre><p>When i is 3, JavaScript skips that iteration.</p><p>The loop itself continues.</p><p>Think of it as:</p><blockquote><strong><em>“Skip this iteration and continue with the next one.”</em></strong></blockquote><h3>break vs continue</h3><p>This is an important distinction.</p><h3>break</h3><pre>for (let i = 1; i &lt;= 5; i++) {<br>    if (i === 3) {<br>        break;<br>    }<br>    console.log(i);<br>}</pre><p>Output:</p><pre>1<br>2</pre><p>The <strong>entire loop stops</strong>.</p><h3>continue</h3><pre>for (let i = 1; i &lt;= 5; i++) {<br>    if (i === 3) {<br>        continue;<br>    }<br>    console.log(i);<br>}</pre><p>Output:</p><pre>1<br>2<br>4<br>5</pre><p>Only the <strong>current iteration is skipped</strong>.</p><p>Remember:</p><pre>break    → Stop the loop<br>continue → Skip current iteration</pre><h3>A Practical Example</h3><p>Suppose we have a list of users:</p><pre>const users = [<br>    { name: &quot;A&quot;, active: true },<br>    { name: &quot;B&quot;, active: false },<br>    { name: &quot;C&quot;, active: true }<br>];</pre><p>We only want to process active users.</p><pre>for (const user of users) {<br><br>    if (!user.active) {<br>        continue;<br>    }<br><br>    console.log(`Processing ${user.name}`);<br>}</pre><p>Output:</p><pre>Processing A<br>Processing C</pre><p>The inactive user is skipped using continue.</p><p>This type of control flow appears frequently in real-world application logic.</p><h3>Quick Summary</h3><ul><li><strong>if</strong> → Execute code when a condition is true.</li><li><strong>else</strong> → Execute code when the if condition is false.</li><li><strong>else if</strong> → Check multiple conditions.</li><li><strong>switch</strong> → Match one value against multiple cases.</li><li><strong>for</strong> → Repeat code a specific number of times.</li><li><strong>while</strong> → Repeat code while a condition is true.</li><li><strong>do...while</strong> → Execute the code at least once, then check the condition.</li><li><strong>for...of</strong> → Iterate over values.</li><li><strong>for...in</strong> → Iterate over keys.</li><li><strong>break</strong> → Stop the loop completely.</li><li><strong>continue</strong> → Skip the current iteration and move to the next one.</li></ul><h3>Final Takeaway</h3><p>Control flow is the mechanism that allows your JavaScript program to <strong>make decisions and repeat operations</strong>.</p><p>The core concepts to remember are:</p><pre>if        → Make decisions<br>switch    → Match multiple cases<br>loops     → Repeat operations<br>break     → Stop<br>continue  → Skip and move to the next iteration</pre><p>These concepts may look simple, but they form the foundation of almost every JavaScript application.</p><p>Once you understand control flow, you can start combining it with <strong>arrays, objects, functions, and methods</strong> to build much more complex logic.</p><h3>What’s Next?</h3><p>In the next part of this JavaScript series, we’ll move into <strong>Functions</strong>, where we’ll learn about function declarations, parameters, return values, function expressions, arrow functions, callbacks, and more.</p><h3>Keywords</h3><p>JavaScript Conditional Statements, JavaScript if else, JavaScript if statement, JavaScript else if, JavaScript switch statement, JavaScript switch case, JavaScript loops, JavaScript for loop, JavaScript while loop, JavaScript do while loop, JavaScript for of loop, JavaScript for in loop, JavaScript break statement, JavaScript continue statement, JavaScript control flow, JavaScript control flow statements, JavaScript decision making, JavaScript tutorial for beginners, JavaScript beginner tutorial, Learn JavaScript, JavaScript programming</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a5c4d9790734" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Remove Element — LeetCode #27 | Part — 5]]></title>
            <link>https://medium.com/@tuhinkairi/remove-element-leetcode-27-part-4-9e272287dec5?source=rss-486354359cd2------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e272287dec5</guid>
            <category><![CDATA[data-structure-algorithm]]></category>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[dsa-courses]]></category>
            <dc:creator><![CDATA[Tuhin Kairi]]></dc:creator>
            <pubDate>Sun, 30 Aug 2026 19:16:26 GMT</pubDate>
            <atom:updated>2026-09-01T01:44:44.842Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G13Q-T_yw1cusVBtKPajbA.png" /><figcaption>Remove Element — LeetCode #27 | Part — 5</figcaption></figure><p><em>Learn how to solve </em><strong><em>LeetCode 27 — Remove Element</em></strong><em> using the </em><strong><em>two-pointer technique</em></strong><em> in C++. This article provides a simple problem breakdown, step-by-step walkthrough, and optimal in-place solution with </em><strong><em>O(n) time and O(1) space complexity</em></strong><em>.</em></p><p>This is the next problem in the <strong>Arrays</strong>, right after <strong>Remove Duplicates from Sorted Array</strong>. The same in-place array manipulation idea continues here, but the condition changes: instead of removing duplicates, we remove every occurrence of a specific value.</p><p><a href="https://leetcode.com/problems/remove-element/description/">LeetCode — Remove Element #27</a></p><h3>The Problem</h3><p>You are given:</p><pre>nums = [0,1,2,2,3,0,4,2]<br>val = 2</pre><p>Remove every occurrence of 2 <strong>in-place</strong> and return the number of elements that remain.</p><p>The important part is:</p><blockquote><em>We don’t actually need to resize the array.</em></blockquote><p>LeetCode only cares about the <strong>first </strong><strong>k positions</strong>, where k is the number of elements that are not equal to val. Anything after that doesn&#39;t matter. (<a href="https://leetcode.com/problems/remove-element/description/">LeetCode</a>)</p><p>So:</p><pre>Before:<br>[0, 1, 2, 2, 3, 0, 4, 2]</pre><pre>After:<br>[0, 1, 3, 0, 4, _, _, _]<br>              ↑<br>             k = 5</pre><p>Return:</p><pre>5</pre><h3>Decode the Problem</h3><p>Don’t think:</p><blockquote><em>“How do I delete elements from an array?”</em></blockquote><p>Think:</p><blockquote><strong><em>“How do I move every element that I want to keep toward the front?”</em></strong></blockquote><p>That’s the key shift.</p><p>We don’t need to physically delete anything.</p><p>We simply <strong>overwrite the positions containing </strong><strong>val</strong> with elements we want to keep.</p><h3>Before We Code — Think About It</h3><p>Let’s use:</p><pre>nums = [0, 1, 2, 2, 3, 0, 4, 2]<br>val = 2</pre><h3>Stage 1 — Start scanning</h3><pre>0 → keep</pre><p>We want 0 at the beginning.</p><pre>[0, 1, 2, 2, 3, 0, 4, 2]<br> ↑</pre><p><strong>Thought:</strong><br>0 != 2, so keep it.</p><h3>Stage 2</h3><pre>1 → keep</pre><pre>[0, 1, 2, 2, 3, 0, 4, 2]<br>    ↑</pre><p><strong>Thought:</strong><br>1 != 2, so keep it.</p><h3>Stage 3</h3><pre>2 → remove</pre><p><strong>Thought:</strong><br>This is the value we’re looking for, so simply skip it.</p><pre>[0, 1, 2, 2, 3, 0, 4, 2]<br>       X</pre><p>No shifting. No deletion.</p><h3>Stage 4</h3><p>Another:</p><pre>2 → remove</pre><p>Again, skip it.</p><pre>[0, 1, 2, 2, 3, 0, 4, 2]<br>          X</pre><h3>Stage 5</h3><pre>3 → keep</pre><p>But the next valid position is where the first 2 was.</p><p>So:</p><pre>[0, 1, 3, 2, 3, 0, 4, 2]<br>       ↑</pre><p><strong>Thought:</strong></p><blockquote><em>“I found something worth keeping. Put it into the next available position.”</em></blockquote><h3>Stage 6</h3><pre>0 → keep</pre><p>Write it into the next available position:</p><pre>[0, 1, 3, 0, 3, 0, 4, 2]<br>          ↑</pre><h3>Stage 7</h3><pre>4 → keep</pre><pre>[0, 1, 3, 0, 4, 0, 4, 2]<br>             ↑</pre><p>Now we’ve collected <strong>5 valid elements</strong>.</p><pre>[0, 1, 3, 0, 4, _, _, _]</pre><p>So:</p><pre>k = 5</pre><h3>The Pattern</h3><p>This is essentially the same <strong>read/write pointer idea</strong> you saw in the previous array problem.</p><p>We maintain:</p><pre>read → scans every element<br>write → tells us where the next valid element goes</pre><p>The rule is simple:</p><pre>if nums[read] != val<br>    nums[write] = nums[read]<br>    write++</pre><p>If:</p><pre>nums[read] == val</pre><p>we simply skip it.</p><h3>Your Turn</h3><p>Before looking at the code, try implementing it yourself.</p><p>You already have the entire logic:</p><ol><li>Traverse the array.</li><li>Check whether the current element equals val.</li><li>If it doesn’t, write it at the next valid position.</li><li>Return the number of valid elements.</li></ol><p>Try writing the C++ solution on LeetCode first.</p><p><strong>Don’t worry about making it perfect. The goal here is to convert the walkthrough into code.</strong></p><p>Once you’ve attempted it, compare it with the optimal solution below.</p><h3>Optimal C++ Solution</h3><pre>class Solution {<br>public:<br>    int removeElement(vector&lt;int&gt;&amp; nums, int val) {<br>        int k = 0;<br>        <br>        for (int i = 0; i &lt; nums.size(); i++) {<br>            if (nums[i] != val) {<br>                nums[k] = nums[i];<br>                k++;<br>            }<br>        }<br>        return k;<br>    }<br>};</pre><h3>Quick Code Walkthrough</h3><h3>k = 0</h3><pre>int k = 0;</pre><p>k represents:</p><blockquote><em>The next position where we can place an element that should be kept.</em></blockquote><h3>Scan the array</h3><pre>for (int i = 0; i &lt; nums.size(); i++)</pre><p>i reads every element.</p><h3>Ignore val</h3><pre>if (nums[i] != val)</pre><p>If the current value is val, do nothing.</p><h3>Keep valid elements</h3><pre>nums[k] = nums[i];</pre><p>Copy the valid element to the next available position.</p><p>Then:</p><pre>k++;</pre><p>Move the write position forward.</p><h3>Return k</h3><pre>return k;</pre><p>k is exactly the number of elements that survived.</p><h3>Complexity</h3><p>Operation Complexity</p><p>Time<strong>O(n), </strong>Space<strong>O(1)</strong></p><p>We scan the array once and modify it in-place, so this is optimal for the problem’s requirements. LeetCode classifies the problem under <strong>Array</strong> and <strong>Two Pointers</strong>.</p><h3>Interview Takeaway</h3><p>The important idea isn’t “remove an element.”</p><p>It’s:</p><blockquote><strong><em>Scan → Keep valid elements → Write them forward → Return the valid count.</em></strong></blockquote><p>This is another variation of the <strong>in-place two-pointer technique</strong>, which will become increasingly useful in the upcoming Two Pointer section of the roadmap.</p><p><strong>Next in the Arrays roadmap:</strong> Contains Duplicate.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e272287dec5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript Objects: Object Literals, Methods, Descriptors, Copying, Freeze & Seal (Day — 12)]]></title>
            <link>https://medium.com/@tuhinkairi/javascript-objects-object-literals-methods-descriptors-copying-freeze-seal-day-12-06f238f94205?source=rss-486354359cd2------2</link>
            <guid isPermaLink="false">https://medium.com/p/06f238f94205</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Tuhin Kairi]]></dc:creator>
            <pubDate>Sun, 30 Aug 2026 10:14:52 GMT</pubDate>
            <atom:updated>2026-08-30T10:14:52.141Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HXfQjrWYC50utt-nCJDQkA.png" /><figcaption>JavaScript Objects: Object Literals, Methods, Descriptors, Copying, Freeze &amp; Seal (Day — 12)</figcaption></figure><p><em>Learn JavaScript Objects from basics to advanced concepts. This beginner-friendly tutorial explains object literals, property descriptors, object methods, shallow vs deep copy, Object.freeze(), and Object.seal() with practical examples.</em></p><p>Welcome to <strong>Part 12 of the JavaScript Tutorial series</strong>.</p><p>In the previous parts, we explored JavaScript <strong>variables, data types, strings, numbers, arrays, type conversion, and loops</strong>.</p><p>Now it’s time to move into one of the most important concepts in JavaScript:</p><blockquote><strong><em>Objects</em></strong></blockquote><p>Objects are everywhere in JavaScript. They are used to represent users, products, API responses, configurations, application state, and much more.</p><p>In this article, we’ll learn:</p><ul><li>Object Literals</li><li>Property Descriptors</li><li>Object Methods</li><li>Shallow vs Deep Copy</li><li>Object.freeze()</li><li>Object.seal()</li></ul><h3>1. Object Literals</h3><p>An <strong>object literal</strong> is the simplest way to create an object in JavaScript.</p><pre>const user = {<br>    name: &quot;Tuhin&quot;,<br>    age: 22,<br>    role: &quot;Developer&quot;<br>};</pre><p>Here:</p><ul><li>name is a property</li><li>age is a property</li><li>role is a property</li><li>&quot;Tuhin&quot;, 22, and &quot;Developer&quot; are their values</li></ul><p>You can access object properties in two common ways.</p><h3>Dot Notation</h3><pre>console.log(user.name);</pre><p>Output:</p><pre>Tuhin</pre><h3>Bracket Notation</h3><pre>console.log(user[&quot;age&quot;]);</pre><p>Output:</p><pre>22</pre><p>Bracket notation becomes especially useful when the property name is stored inside a variable.</p><pre>const property = &quot;role&quot;;</pre><pre>console.log(user[property]);</pre><p>Output:</p><pre>Developer</pre><h3>Adding Properties</h3><p>You can add new properties after creating an object.</p><pre>user.country = &quot;India&quot;;</pre><p>Now:</p><pre>console.log(user);</pre><pre>{<br>    name: &quot;Tuhin&quot;,<br>    age: 22,<br>    role: &quot;Developer&quot;,<br>    country: &quot;India&quot;<br>}</pre><h3>Updating Properties</h3><pre>user.age = 23;</pre><h3>Deleting Properties</h3><pre>delete user.country;</pre><h3>2. Property Descriptors</h3><p>JavaScript properties have additional configuration behind the scenes.</p><p>These configurations are called <strong>property descriptors</strong>.</p><p>The main descriptor properties are:</p><ul><li>value</li><li>writable</li><li>enumerable</li><li>configurable</li></ul><p>Let’s look at an example.</p><pre>const user = {<br>    name: &quot;Tuhin&quot;<br>};</pre><pre>console.log(<br>    Object.getOwnPropertyDescriptor(user, &quot;name&quot;)<br>);</pre><p>You will get something similar to:</p><pre>{<br>    value: &quot;Tuhin&quot;,<br>    writable: true,<br>    enumerable: true,<br>    configurable: true<br>}</pre><p>Let’s understand them.</p><h3>value</h3><p>Stores the actual value of the property.</p><pre>value: &quot;Tuhin&quot;</pre><h3>writable</h3><p>Determines whether the property’s value can be changed.</p><pre>writable: true</pre><p>If it is false:</p><pre>const user = {};</pre><pre>Object.defineProperty(user, &quot;name&quot;, {<br>    value: &quot;Tuhin&quot;,<br>    writable: false<br>});</pre><p>Trying to change it:</p><pre>user.name = &quot;Rahul&quot;;</pre><p>The value cannot be changed.</p><h3>enumerable</h3><p>Determines whether the property appears during enumeration, such as with:</p><pre>Object.keys(user);</pre><p>Example:</p><pre>const user = {};</pre><pre>Object.defineProperty(user, &quot;name&quot;, {<br>    value: &quot;Tuhin&quot;,<br>    enumerable: false<br>});</pre><pre>console.log(Object.keys(user));</pre><p>Output:</p><pre>[]</pre><p>The property exists, but it isn’t enumerable.</p><h3>configurable</h3><p>Determines whether the property’s descriptor can be changed or the property can be deleted.</p><pre>const user = {};</pre><pre>Object.defineProperty(user, &quot;name&quot;, {<br>    value: &quot;Tuhin&quot;,<br>    configurable: false<br>});</pre><p>The property can no longer be deleted or reconfigured.</p><h3>Why Property Descriptors Matter</h3><p>Property descriptors are useful when you need <strong>fine-grained control over object properties</strong>.</p><p>They are commonly used in:</p><ul><li>Libraries</li><li>Framework internals</li><li>APIs</li><li>Data models</li><li>Advanced JavaScript programming</li></ul><h3>3. Object Methods</h3><p>Objects can contain functions.</p><p>When a function belongs to an object, we commonly call it a <strong>method</strong>.</p><pre>const user = {<br>    name: &quot;Tuhin&quot;,<br>    greet: function() {<br>        console.log(&quot;Hello!&quot;);<br>    }<br>};</pre><p>We can call it using:</p><pre>user.greet();</pre><p>Output:</p><pre>Hello!</pre><h3>Modern Method Syntax</h3><p>JavaScript provides a shorter syntax for defining methods.</p><pre>const user = {<br>    name: &quot;Tuhin&quot;,<br>    greet() {<br>        console.log(`Hello ${this.name}`);<br>    }<br>};</pre><pre>user.greet();</pre><p>Output:</p><pre>Hello Tuhin</pre><p>Here, this refers to the object that is calling the method.</p><h3>Common Object Methods</h3><p>JavaScript also provides several built-in methods for working with objects.</p><h3>Object.keys()</h3><p>Returns an array containing the object’s keys.</p><pre>const user = {<br>    name: &quot;Tuhin&quot;,<br>    age: 22<br>};</pre><pre>console.log(Object.keys(user));</pre><p>Output:</p><pre>[&quot;name&quot;, &quot;age&quot;]</pre><h3>Object.values()</h3><p>Returns the object’s values.</p><pre>console.log(Object.values(user));</pre><p>Output:</p><pre>[&quot;Tuhin&quot;, 22]</pre><h3>Object.entries()</h3><p>Returns key-value pairs.</p><pre>console.log(Object.entries(user));</pre><p>Output:</p><pre>[<br>    [&quot;name&quot;, &quot;Tuhin&quot;],<br>    [&quot;age&quot;, 22]<br>]</pre><h3>Object.assign()</h3><p>Copies properties from one or more objects into another object.</p><pre>const user = {<br>    name: &quot;Tuhin&quot;<br>};</pre><pre>const details = {<br>    age: 22<br>};</pre><pre>const result = Object.assign({}, user, details);</pre><pre>console.log(result);</pre><p>Output:</p><pre>{<br>    name: &quot;Tuhin&quot;,<br>    age: 22<br>}</pre><h3>4. Shallow Copy vs Deep Copy</h3><p>Copying objects is one of the places where JavaScript can become confusing.</p><p>Consider this:</p><pre>const user = {<br>    name: &quot;Tuhin&quot;,<br>    age: 22<br>};</pre><pre>const copy = user;</pre><p>This does <strong>not</strong> create a new object.</p><p>Both variables point to the same object.</p><pre>copy.name = &quot;Rahul&quot;;</pre><pre>console.log(user.name);</pre><p>Output:</p><pre>Rahul</pre><p>So how do we actually copy an object?</p><h3>Shallow Copy</h3><p>A shallow copy creates a new object, but nested objects are still shared.</p><p>One common approach is the spread operator:</p><pre>const user = {<br>    name: &quot;Tuhin&quot;,<br>    age: 22<br>};</pre><pre>const copy = { ...user };</pre><p>Now:</p><pre>copy.name = &quot;Rahul&quot;;</pre><pre>console.log(user.name);</pre><p>Output:</p><pre>Tuhin</pre><p>The top-level properties are copied.</p><p>But consider a nested object:</p><pre>const user = {<br>    name: &quot;Tuhin&quot;,<br>    address: {<br>        city: &quot;Kolkata&quot;<br>    }<br>};</pre><pre>const copy = { ...user };</pre><pre>copy.address.city = &quot;Delhi&quot;;</pre><pre>console.log(user.address.city);</pre><p>Output:</p><pre>Delhi</pre><p>Why?</p><p>Because the nested address object is still shared.</p><p>That’s why it is called a <strong>shallow copy</strong>.</p><h3>Deep Copy</h3><p>A deep copy creates a completely independent copy, including nested objects.</p><p>One modern approach is:</p><pre>const copy = structuredClone(user);</pre><p>Example:</p><pre>const user = {<br>    name: &quot;Tuhin&quot;,<br>    address: {<br>        city: &quot;Kolkata&quot;<br>    }<br>};</pre><pre>const copy = structuredClone(user);</pre><pre>copy.address.city = &quot;Delhi&quot;;</pre><pre>console.log(user.address.city);</pre><p>Output:</p><pre>Kolkata</pre><p>Now the nested object is also independent.</p><h3>Quick Difference</h3><p><strong>Shallow Copy</strong></p><ul><li>Top-level properties → Copied</li><li>Nested objects → Shared references</li></ul><p><strong>Deep Copy</strong></p><ul><li>Top-level properties → Copied</li><li>Nested objects → Independently copied</li></ul><p>The important concept here is:</p><blockquote><strong><em>Shallow copy copies the object structure, while deep copy recursively copies nested data.</em></strong></blockquote><h3>5. Object.freeze()</h3><p>Sometimes you don’t want an object to be modified.</p><p>JavaScript provides:</p><pre>Object.freeze()</pre><p>Example:</p><pre>const user = {<br>    name: &quot;Tuhin&quot;,<br>    age: 22<br>};</pre><pre>Object.freeze(user);</pre><p>Now you cannot:</p><ul><li>Add properties</li><li>Delete properties</li><li>Modify existing properties</li></ul><pre>user.age = 23;<br>user.country = &quot;India&quot;;<br>delete user.name;</pre><p>The object remains unchanged.</p><p>You can check whether an object is frozen:</p><pre>console.log(Object.isFrozen(user));</pre><p>Output:</p><pre>true</pre><h3>Important: freeze() is Shallow</h3><p>This is an important point.</p><pre>const user = {<br>    name: &quot;Tuhin&quot;,<br>    address: {<br>        city: &quot;Kolkata&quot;<br>    }<br>};</pre><pre>Object.freeze(user);</pre><pre>user.address.city = &quot;Delhi&quot;;</pre><pre>console.log(user.address.city);</pre><p>Output:</p><pre>Delhi</pre><p>The nested address object wasn&#39;t frozen.</p><p>So:</p><blockquote><strong><em>Object.freeze() only freezes the object at the first level.</em></strong></blockquote><h3>6. Object.seal()</h3><p>Another useful method is:</p><pre>Object.seal()</pre><p>Object.seal() prevents:</p><ul><li>Adding new properties</li><li>Deleting existing properties</li></ul><p>But existing properties can still be modified.</p><p>Example:</p><pre>const user = {<br>    name: &quot;Tuhin&quot;,<br>    age: 22<br>};</pre><pre>Object.seal(user);</pre><p>We can still modify:</p><pre>user.age = 23;</pre><p>But we cannot add:</p><pre>user.country = &quot;India&quot;;</pre><p>And we cannot delete:</p><pre>delete user.name;</pre><p>You can check whether an object is sealed:</p><pre>console.log(Object.isSealed(user));</pre><p>Output:</p><pre>true</pre><h3>Freeze vs Seal</h3><p>This is a common JavaScript interview question.</p><h4>Normal Object</h4><ul><li>Add properties → Yes</li><li>Delete properties → Yes</li><li>Modify properties → Yes</li><li>Nested objects protected → No</li></ul><h4>Object.seal()</h4><ul><li>Add properties → No</li><li>Delete properties → No</li><li>Modify properties → Yes</li><li>Nested objects protected → No</li></ul><h4>Object.freeze()</h4><ul><li>Add properties → No</li><li>Delete properties → No</li><li>Modify properties → No</li><li>Nested objects protected → No</li></ul><p>The easiest way to remember:</p><p><strong>Seal → Structure locked, values can change</strong></p><p><strong>Freeze → Structure + values locked</strong></p><h3>Final Example</h3><p>Let’s combine some of these concepts.</p><pre>const user = {<br>    name: &quot;Tuhin&quot;,<br>    age: 22,<br>    skills: {<br>        primary: &quot;JavaScript&quot;<br>    },<br>    greet() {<br>        console.log(`Hello ${this.name}`);<br>    }<br>};<br>user.greet();</pre><p>Create a shallow copy:</p><pre>const shallowCopy = { ...user };</pre><p>Create a deep copy:</p><pre>const deepCopy = structuredClone(user);</pre><p>Freeze the object:</p><pre>Object.freeze(user);</pre><p>Or seal it:</p><pre>Object.seal(user);</pre><p>Each operation solves a different problem.</p><h3>Quick Summary</h3><ul><li><strong>Object Literal</strong> → Create objects easily</li><li><strong>Property Descriptor</strong> → Control property behavior</li><li><strong>Object Method</strong> → Store functions inside objects</li><li><strong>Shallow Copy</strong> → Copy top-level properties</li><li><strong>Deep Copy</strong> → Copy nested data independently</li><li><strong>Object.freeze()</strong> → Prevent modifications</li><li><strong>Object.seal()</strong> → Prevent adding and deleting properties</li></ul><h3>What’s Next?</h3><p>Objects are one of the foundations of JavaScript, and understanding how they work becomes extremely important when working with <strong>React, Node.js, APIs, and modern JavaScript applications</strong>.</p><p>In the next part, we explore concepts such as <strong>if-else, switch, loops, break, continue</strong>.</p><p>If you’re following this series from the beginning, make sure to check out the previous parts as well.</p><h3>SEO Keywords</h3><p>JavaScript Objects, JavaScript Object Literals, JavaScript Object Methods, Property Descriptors JavaScript, JavaScript Shallow Copy, JavaScript Deep Copy, Object.freeze JavaScript, Object.seal JavaScript, JavaScript Tutorial for Beginners, JavaScript Objects Explained</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=06f238f94205" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Remove Duplicates from Sorted Array — LeetCode 26 | Part — 4]]></title>
            <link>https://medium.com/@tuhinkairi/remove-duplicates-from-sorted-array-leetcode-26-part-4-94bde817c2d4?source=rss-486354359cd2------2</link>
            <guid isPermaLink="false">https://medium.com/p/94bde817c2d4</guid>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[dsa-courses]]></category>
            <category><![CDATA[arrays]]></category>
            <category><![CDATA[leetcode-easy]]></category>
            <category><![CDATA[data-structure-algorithm]]></category>
            <dc:creator><![CDATA[Tuhin Kairi]]></dc:creator>
            <pubDate>Fri, 14 Aug 2026 18:46:09 GMT</pubDate>
            <atom:updated>2026-08-14T18:46:09.971Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Tfg9MIsW4j2IuZsUEQ09qQ.png" /><figcaption>Remove Duplicates from Sorted Array — LeetCode 26 | Part — 4</figcaption></figure><p><em>Learn how to solve </em><strong><em>LeetCode 26: Remove Duplicates from Sorted Array</em></strong><em> using the </em><strong><em>Two Pointer pattern</em></strong><em> in C++. This walkthrough explains the problem in simple terms, breaks down the fast and slow pointer approach, provides a step-by-step dry run, and covers the optimal </em><strong><em>O(n) time and O(1) space</em></strong><em> solution for coding interviews and DSA preparation.</em></p><p>This is the <strong>next problem in the Arrays roadmap</strong>, immediately after <strong>Two Sum</strong>. The roadmap places it under Arrays and later connects it directly with the <strong>Two Pointer</strong> pattern.</p><p>Since the fundamentals were already covered earlier, we’ll keep this focused on <strong>problem decoding → thought process → walkthrough → optimal approach</strong>.</p><p><a href="https://leetcode.com/problems/remove-duplicates-from-sorted-array/?utm_source=chatgpt.com">LeetCode — Remove Duplicates from Sorted Array</a></p><h3>1. The Problem</h3><p>LeetCode gives us a <strong>sorted integer array</strong>.</p><p>Our job is to:</p><ul><li>Remove duplicate values.</li><li>Keep each value only once.</li><li>Modify the <strong>same array</strong> instead of creating another one.</li><li>Return k, the number of unique elements.</li><li>The first k positions of the array must contain the unique values.</li></ul><p>For example:</p><pre>Input:<br>[1, 1, 2]</pre><pre>After processing:<br>[1, 2, _]</pre><pre>Return:<br>2</pre><p>The _ values don&#39;t matter. LeetCode only checks the first k elements. (<a href="https://leetcode.com/problems/remove-duplicates-from-sorted-array/?lang=c&amp;utm_source=chatgpt.com">LeetCode</a>)</p><p>Another example:</p><pre>Input:<br>[0,0,1,1,1,2,2,3,3,4]</pre><pre>Output:<br>[0,1,2,3,4,_,_,_,_,_]</pre><pre>k = 5</pre><h3>2. Decode the Question</h3><p>The important words are:</p><blockquote><strong><em>Sorted array</em></strong></blockquote><p>This is the first clue.</p><p>Because the array is sorted:</p><pre>[1,1,1,2,2,3,3,4]</pre><p>duplicates are always next to each other.</p><p>So instead of asking:</p><blockquote><em>“Have I seen this number before?”</em></blockquote><p>we can simply ask:</p><blockquote><strong><em>“Is this number different from the previous unique number?”</em></strong></blockquote><p>That’s the key observation.</p><h3>3. Before Thinking About Code</h3><p>Take:</p><pre>[0,0,1,1,1,2,2,3,3,4]</pre><p>We want:</p><pre>[0,1,2,3,4]</pre><p>Now think about what we actually need to do.</p><p>We need one pointer to <strong>look through the array</strong>.</p><p>And another pointer to tell us:</p><blockquote><em>“Where should the next unique number be placed?”</em></blockquote><p>That naturally leads us toward <strong>Two Pointers</strong>.</p><h3>4. Simple Walkthrough</h3><p>Let’s use:</p><pre>nums = [0,0,1,1,1,2,2,3,3,4]</pre><p>We’ll use two pointers:</p><pre>slow → position where the next unique value goes</pre><pre>fast → scans the array</pre><p>Initially:</p><pre>slow = 1<br>fast = 1</pre><p>Why slow = 1?</p><p>Because the first element is automatically unique.</p><pre>[0, 0, 1, 1, 1, 2, 2, 3, 3, 4]<br> ↑<br> already unique</pre><h3>Stage 1</h3><pre>fast → 0<br>slow → position 1</pre><p>Compare:</p><pre>nums[fast] == nums[slow - 1]<br>0 == 0</pre><p>Duplicate.</p><p><strong>Thought process:</strong></p><blockquote><em>“I’ve already stored this </em><em>0. Skip it.&quot;</em></blockquote><h3>Stage 2</h3><p>fast moves:</p><pre>[0, 0, 1, 1, 1, 2, 2, 3, 3, 4]<br>       ↑<br>      fast</pre><p>Now:</p><pre>1 != 0</pre><p>This is a new value.</p><p><strong>Thought process:</strong></p><blockquote><em>“I found a new unique number. Put it at the </em><em>slow position.&quot;</em></blockquote><p>So:</p><pre>nums[slow] = nums[fast]</pre><p>Array becomes:</p><pre>[0, 1, 1, 1, 1, 2, 2, 3, 3, 4]<br>   ↑<br>  slow</pre><p>Then:</p><pre>slow++</pre><h3>Stage 3</h3><p>fast encounters the next 1.</p><pre>1 == previous unique value</pre><p>Duplicate.</p><p><strong>Thought process:</strong></p><blockquote><em>“Already stored </em><em>1. Skip.&quot;</em></blockquote><h3>Stage 4</h3><p>Eventually fast reaches 2.</p><pre>2 != 1</pre><p>New unique value.</p><p>Write it at slow.</p><pre>[0,1,2,1,1,2,2,3,3,4]<br>     ↑<br>    slow</pre><p>Again:</p><pre>slow++</pre><h3>Continue</h3><p>The same process continues:</p><pre>fast finds 3<br>    ↓<br>3 is new<br>    ↓<br>write 3 at slow<br>    ↓<br>slow++</pre><pre>fast finds 4<br>    ↓<br>4 is new<br>    ↓<br>write 4 at slow</pre><p>Eventually:</p><pre>[0,1,2,3,4,_,_,_,_,_]</pre><p>And:</p><pre>slow = 5</pre><p>Therefore:</p><pre>return 5</pre><h3>5. The Pattern</h3><p>The entire logic can be reduced to this:</p><pre>fast → scans everything</pre><pre>slow → stores unique elements</pre><p>Whenever fast finds a new value:</p><pre>nums[slow] = nums[fast]<br>slow++</pre><p>Whenever it finds a duplicate:</p><pre>skip it</pre><p>This is the <strong>fast/slow Two Pointer pattern</strong>.</p><p>The problem itself is tagged by LeetCode as <strong>Array + Two Pointers</strong>.</p><h3>6. Your Turn Before the Code</h3><p>Don’t look at the implementation yet.</p><p>Try writing the solution yourself based on this logic:</p><pre>1. First element is already unique.<br>2. Start a slow pointer at index 1.<br>3. Use a fast pointer to scan from index 1.<br>4. If current value is different from the previous unique value:<br>      put it at slow<br>      move slow<br>5. Return slow</pre><p>Try implementing this in <strong>C++</strong>.</p><h3>Test it with:</h3><pre>[1,1,2]</pre><p>and:</p><pre>[0,0,1,1,1,2,2,3,3,4]</pre><h3>Optimal C++ Solution</h3><pre>class Solution {<br>public:<br>    int removeDuplicates(vector&lt;int&gt;&amp; nums) {<br>        int slow = 1;<br><br>        for (int fast = 1; fast &lt; nums.size(); fast++) {<br>            if (nums[fast] != nums[slow - 1]) {<br>                nums[slow] = nums[fast];<br>                slow++;<br>            }<br>        }<br>        return slow;<br>      }<br>  };</pre><h3>Line-by-line walkthrough</h3><pre>int slow = 1;</pre><p>The first element is already unique.</p><p>So slow starts at 1.</p><p>Think of slow as:</p><blockquote><strong><em>The position where the next unique element should be placed.</em></strong></blockquote><pre>for (int fast = 1; fast &lt; nums.size(); fast++)</pre><p>fast scans the array from left to right.</p><p>We start at 1 because index 0 is already handled.</p><p>So:</p><pre>slow → position to write<br>fast → position to inspect</pre><pre>if (nums[fast] != nums[slow - 1])</pre><p>This is the key line.</p><p>Because the array is <strong>sorted</strong>, duplicates are next to each other.</p><p>So we compare the current element with the <strong>last unique element</strong>.</p><p>For example:</p><pre>[1, 1, 2, 2, 3]<br>    ↑<br>   fast</pre><pre>last unique = 1<br>current     = 1</pre><pre>1 == 1 → duplicate → skip</pre><p>But:</p><pre>[1, 1, 2, 2, 3]<br>       ↑<br>      fast</pre><pre>2 != 1 → new unique value</pre><pre>nums[slow] = nums[fast];</pre><p>We’ve found a new unique value.</p><p>Put it into the next available position.</p><p>Example:</p><pre>[1, 1, 2, 2, 3]<br>       ↑<br>      fast</pre><pre>slow = 1</pre><p>We write:</p><pre>nums[1] = nums[2]</pre><p>Result:</p><pre>[1, 2, 2, 2, 3]<br>    ↑<br>   slow</pre><p>The important part is that we’re modifying the <strong>same array</strong>.</p><pre>slow++;</pre><p>We’ve successfully stored one more unique element.</p><p>So move slow forward.</p><p>It now points to where the <strong>next unique element</strong> should go.</p><pre>return slow;</pre><p>slow represents the number of unique elements.</p><p>For:</p><pre>[1,1,2,2,3]</pre><p>we finish with:</p><pre>[1,2,3,_,_]</pre><p>and:</p><pre>slow = 3</pre><p>So we return:</p><pre>3</pre><h3>Complete Dry Run</h3><p>Sure. For the article, you can present the dry run as a simple step-by-step list instead of a table:</p><p>Input:</p><pre>[0, 0, 1, 1, 1, 2, 2, 3, 3, 4]</pre><p><strong>Step 1</strong></p><ul><li>fast = 1</li><li>Current = 0</li><li>Last unique = 0</li><li>Action → Duplicate, skip</li><li>slow = 1</li></ul><p><strong>Step 2</strong></p><ul><li>fast = 2</li><li>Current = 1</li><li>Last unique = 0\</li><li>Action → New value, write 1</li><li>slow = 2</li></ul><p><strong>Step 3</strong></p><ul><li>fast = 3</li><li>Current = 1</li><li>Last unique = 1</li><li>Action → Duplicate, skip</li><li>slow = 2</li></ul><p><strong>Step 4</strong></p><ul><li>fast = 4</li><li>Current = 1</li><li>Last unique = 1</li><li>Action → Duplicate, skip</li><li>slow = 2</li></ul><p><strong>Step 5</strong></p><ul><li>fast = 5</li><li>Current = 2</li><li>Last unique = 1</li><li>Action → New value, write 2</li><li>slow = 3</li></ul><p><strong>Step 6</strong></p><ul><li>fast = 6</li><li>Current = 2</li><li>Last unique = 2</li><li>Action → Duplicate, skip</li><li>slow = 3</li></ul><p><strong>Step 7</strong></p><ul><li>fast = 7</li><li>Current = 3</li><li>Last unique = 2</li><li>Action → New value, write 3</li><li>slow = 4</li></ul><p><strong>Step 8</strong></p><ul><li>fast = 8</li><li>Current = 3</li><li>Last unique = 3</li><li>Action → Duplicate, skip</li><li>slow = 4</li></ul><p><strong>Step 9</strong></p><ul><li>fast = 9</li><li>Current = 4</li><li>Last unique = 3</li><li>Action → New value, write 4</li><li>slow = 5</li></ul><h3>Final Result</h3><pre>[0, 1, 2, 3, 4, _, _, _, _, _]</pre><pre>k = 5</pre><p>Only the first k elements matter:</p><pre>[0, 1, 2, 3, 4]</pre><p>Final relevant portion:</p><pre>[0, 1, 2, 3, 4, _, _, _, _, _]</pre><p>Return:</p><pre>5</pre><h3>Complexity Analysis</h3><h3>Time: O(n)</h3><p>fast moves through the array exactly once.</p><pre>n elements → n iterations</pre><p>So:</p><pre>Time = O(n)</pre><h3>Space: O(1)</h3><p>We only use two integer variables:</p><pre>slow<br>fast</pre><p>No additional array, hash map, or set is created.</p><pre>Space = O(1)</pre><blockquote><strong><em>Interview takeaway:</em></strong><em> The sorted property eliminates the need for a hash set. The array’s ordering lets us detect duplicates with a </em><strong><em>fast/slow pointer technique</em></strong><em> in </em><em>O(n) time and </em><em>O(1) extra space.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=94bde817c2d4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript Array Methods Explained: map(), filter(), reduce(), find(), flat() & Sorting (Day — 11)]]></title>
            <link>https://medium.com/@tuhinkairi/javascript-array-methods-explained-map-filter-reduce-find-flat-sorting-day-11-d5951f677277?source=rss-486354359cd2------2</link>
            <guid isPermaLink="false">https://medium.com/p/d5951f677277</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[100daysofcode]]></category>
            <category><![CDATA[array-methods]]></category>
            <dc:creator><![CDATA[Tuhin Kairi]]></dc:creator>
            <pubDate>Thu, 13 Aug 2026 19:14:48 GMT</pubDate>
            <atom:updated>2026-08-13T19:14:48.297Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tMZ0BSxNAaurqR3NXpVw9A.png" /><figcaption>JavaScript Array Methods Explained: map(), filter(), reduce(), find(), flat() &amp; Sorting (Day — 11)</figcaption></figure><p>Learn the most important <strong>JavaScript Array Methods</strong> with simple, practical examples. This beginner-friendly tutorial covers map(), filter(), reduce(), find(), some(), every(), flat(), flatMap(), and sort(). Understand when and why to use each method, how they work with real-world data, and the key differences between them. Perfect for beginners learning JavaScript, preparing for coding interviews, or improving their frontend development skills.</p><p>JavaScript arrays are one of the most commonly used data structures in programming.</p><p>In the previous part of this series, we learned about <strong>JavaScript Arrays, data types, traversal, and loops</strong>. Now it is time to go deeper into the most useful part of working with arrays: <strong>Array Methods</strong>.</p><p>Array methods help us transform, search, filter, combine, and organize data without writing everything manually with traditional loops.</p><p>In this article, we will cover:</p><ul><li>map() → Transform data</li><li>filter() → Select data</li><li>reduce() → Build a single result</li><li>find() → Find an element</li><li>some() → Check if at least one matches</li><li>every() → Check if all match</li><li>flat() → Flatten nested arrays</li><li>flatMap() → Map and flatten</li><li>sort() → Sort array elements</li></ul><h3>1. map() — Transform Data</h3><p>The map() method creates a <strong>new array</strong> by applying a function to every element.</p><h3>Example</h3><pre>const numbers = [1, 2, 3, 4];</pre><pre>const doubled = numbers.map(num =&gt; num * 2);</pre><pre>console.log(doubled);<br>// [2, 4, 6, 8]</pre><p>Think of map() as:</p><blockquote><em>“Take every item and transform it into something else.”</em></blockquote><h3>Working with objects</h3><pre>const users = [<br>  { name: &quot;Tuhin&quot;, age: 24 },<br>  { name: &quot;Rahul&quot;, age: 25 }<br>];</pre><pre>const names = users.map(user =&gt; user.name);</pre><pre>console.log(names);<br>// [&quot;Tuhin&quot;, &quot;Rahul&quot;]</pre><p>map() is extremely common when working with API responses and React components.</p><h3>2. filter() — Select Data</h3><p>filter() creates a new array containing only the elements that satisfy a condition.</p><pre>const numbers = [1, 2, 3, 4, 5, 6];</pre><pre>const evenNumbers = numbers.filter(num =&gt; num % 2 === 0);</pre><pre>console.log(evenNumbers);<br>// [2, 4, 6]</pre><p>Think of filter() as:</p><blockquote><em>“Keep the elements that match my condition.”</em></blockquote><h3>Example with objects</h3><pre>const users = [<br>  { name: &quot;Tuhin&quot;, age: 24 },<br>  { name: &quot;Rahul&quot;, age: 17 },<br>  { name: &quot;Amit&quot;, age: 22 }<br>];</pre><pre>const adults = users.filter(user =&gt; user.age &gt;= 18);</pre><pre>console.log(adults);</pre><h3>3. reduce() — Build a Single Result</h3><p>reduce() is used when you want to process an entire array and produce <strong>one final result</strong>.</p><p>For example, calculating a total:</p><pre>const numbers = [10, 20, 30, 40];</pre><pre>const total = numbers.reduce((sum, num) =&gt; {<br>  return sum + num;<br>}, 0);</pre><pre>console.log(total);<br>// 100</pre><p>Here:</p><pre>sum</pre><p>is the accumulated result, while:</p><pre>num</pre><p>is the current element.</p><p>The 0 is the initial value of the accumulator.</p><h3>Another example</h3><pre>const prices = [100, 200, 300];</pre><pre>const total = prices.reduce((sum, price) =&gt; sum + price, 0);</pre><pre>console.log(total);<br>// 600</pre><p>Think of reduce() as:</p><blockquote><em>“Process all elements and reduce them into one result.”</em></blockquote><p>It can be used for totals, averages, counting, grouping, building objects, and many other operations.</p><h3>4. find() — Find an Element</h3><p>find() returns the <strong>first element</strong> that satisfies a condition.</p><pre>const numbers = [5, 10, 15, 20];</pre><pre>const result = numbers.find(num =&gt; num &gt; 10);</pre><pre>console.log(result);<br>// 15</pre><p>Notice that it returns the element itself, not an array.</p><p>If nothing matches:</p><pre>const result = numbers.find(num =&gt; num &gt; 100);</pre><pre>console.log(result);<br>// undefined</pre><h3>Example with objects</h3><pre>const users = [<br>  { id: 1, name: &quot;Tuhin&quot; },<br>  { id: 2, name: &quot;Rahul&quot; }<br>];</pre><pre>const user = users.find(user =&gt; user.id === 2);</pre><pre>console.log(user);<br>// { id: 2, name: &quot;Rahul&quot; }</pre><h3>5. some() — Does At Least One Match?</h3><p>some() checks whether <strong>at least one element</strong> satisfies a condition.</p><p>It returns either true or false.</p><pre>const numbers = [1, 3, 5, 8];</pre><pre>const hasEven = numbers.some(num =&gt; num % 2 === 0);</pre><pre>console.log(hasEven);<br>// true</pre><p>There is an 8, which is even, so the result is true.</p><p>Think:</p><blockquote><em>“Does at least one item match?”</em></blockquote><h3>6. every() — Do All Elements Match?</h3><p>every() checks whether <strong>all elements</strong> satisfy a condition.</p><pre>const numbers = [2, 4, 6, 8];</pre><pre>const allEven = numbers.every(num =&gt; num % 2 === 0);</pre><pre>console.log(allEven);<br>// true</pre><p>But:</p><pre>const numbers = [2, 4, 5, 8];</pre><pre>const allEven = numbers.every(num =&gt; num % 2 === 0);</pre><pre>console.log(allEven);<br>// false</pre><p>Think:</p><blockquote><em>some() → At least one?</em></blockquote><blockquote><em>every() → All of them?</em></blockquote><h3>7. flat() — Flatten Nested Arrays</h3><p>Sometimes arrays contain other arrays.</p><pre>const numbers = [1, [2, 3], [4, 5]];</pre><pre>const result = numbers.flat();</pre><pre>console.log(result);<br>// [1, 2, 3, 4, 5]</pre><p>By default, flat() removes one level of nesting.</p><p>For deeper nesting:</p><pre>const numbers = [1, [2, [3, 4]]];</pre><pre>console.log(numbers.flat(2));<br>// [1, 2, 3, 4]</pre><p>You can also use:</p><pre>numbers.flat(Infinity);</pre><p>to flatten all levels.</p><h3>8. flatMap() — Map + Flatten</h3><p>flatMap() combines two operations:</p><pre>map() + flat()</pre><p>Example:</p><pre>const numbers = [1, 2, 3];</pre><pre>const result = numbers.flatMap(num =&gt; [num, num * 2]);</pre><pre>console.log(result);<br>// [1, 2, 2, 4, 3, 6]</pre><p>Without flatMap():</p><pre>const result = numbers<br>  .map(num =&gt; [num, num * 2])<br>  .flat();</pre><p>flatMap() is useful when each element needs to produce multiple values.</p><h3>9. sort() — Sort Array Elements</h3><p>The sort() method is used to sort an array.</p><p>For strings:</p><pre>const names = [&quot;Tuhin&quot;, &quot;Amit&quot;, &quot;Rahul&quot;];</pre><pre>names.sort();</pre><pre>console.log(names);<br>// [&quot;Amit&quot;, &quot;Rahul&quot;, &quot;Tuhin&quot;]</pre><p>But numbers require special attention.</p><h3>The common mistake</h3><pre>const numbers = [10, 2, 30, 4];</pre><pre>numbers.sort();</pre><pre>console.log(numbers);<br>// [10, 2, 30, 4]</pre><p>Why?</p><p>Because sort() converts elements to strings by default and sorts them lexicographically.</p><p>For numerical sorting, provide a comparison function.</p><h3>Ascending order</h3><pre>const numbers = [10, 2, 30, 4];</pre><pre>numbers.sort((a, b) =&gt; a - b);</pre><pre>console.log(numbers);<br>// [2, 4, 10, 30]</pre><h3>Descending order</h3><pre>numbers.sort((a, b) =&gt; b - a);</pre><p>This gives:</p><pre>// [30, 10, 4, 2]</pre><h3>Important: sort() modifies the original array</h3><pre>const numbers = [3, 1, 2];</pre><pre>numbers.sort();</pre><pre>console.log(numbers);<br>// [1, 2, 3]</pre><p>The original array has been changed.</p><p>If you want to create a sorted copy:</p><pre>const numbers = [3, 1, 2];</pre><pre>const sorted = [...numbers].sort((a, b) =&gt; a - b);</pre><pre>console.log(numbers);<br>// [3, 1, 2]</pre><pre>console.log(sorted);<br>// [1, 2, 3]</pre><h3>map() vs filter() vs reduce()</h3><p>These three methods are extremely important.</p><p>MethodPurposeReturnsmap()Transform every elementNew arrayfilter()Select matching elementsNew arrayreduce()Build one final resultAny value</p><p>A simple way to remember them:</p><pre>map()    → Change<br>filter() → Select<br>reduce() → Combine</pre><h3>find() vs some() vs every()</h3><p>These methods are also easy to confuse.</p><pre>find()  → Give me the first matching element<br>some()  → Is there at least one match?<br>every() → Do all elements match?</pre><p>Example:</p><pre>const numbers = [2, 4, 7, 8];</pre><pre>numbers.find(num =&gt; num &gt; 5);<br>// 7</pre><pre>numbers.some(num =&gt; num &gt; 5);<br>// true</pre><pre>numbers.every(num =&gt; num &gt; 5);<br>// false</pre><h3>A Practical Example</h3><p>Suppose we have products:</p><pre>const products = [<br>  { name: &quot;Laptop&quot;, price: 800 },<br>  { name: &quot;Mouse&quot;, price: 20 },<br>  { name: &quot;Keyboard&quot;, price: 50 }<br>];</pre><h3>Get product names</h3><pre>const names = products.map(product =&gt; product.name);</pre><h3>Find expensive products</h3><pre>const expensive = products.filter(product =&gt; product.price &gt; 100);</pre><h3>Calculate total price</h3><pre>const total = products.reduce(<br>  (sum, product) =&gt; sum + product.price,<br>  0<br>);</pre><h3>Find a specific product</h3><pre>const laptop = products.find(<br>  product =&gt; product.name === &quot;Laptop&quot;<br>);</pre><h3>Check if any product costs more than $1000</h3><pre>const hasExpensiveProduct = products.some(<br>  product =&gt; product.price &gt; 1000<br>);</pre><h3>Check if every product costs more than $10</h3><pre>const allAboveTen = products.every(<br>  product =&gt; product.price &gt; 10<br>);</pre><p>This is where array methods become powerful in real-world applications.</p><h3>Quick Summary</h3><pre>map()      → Transform every element<br>filter()   → Select matching elements<br>reduce()   → Build one final result<br>find()     → Find the first matching element<br>some()     → Check if at least one matches<br>every()    → Check if all match<br>flat()     → Flatten nested arrays<br>flatMap()  → Map and flatten<br>sort()     → Sort elements</pre><p>You don’t need to memorize every method immediately.</p><p>The important part is understanding <strong>which problem each method solves</strong>.</p><p>When you see a problem, ask:</p><pre>Do I need to transform data?<br>        ↓<br>      map()</pre><pre>Do I need to select data?<br>        ↓<br>     filter()</pre><pre>Do I need one final result?<br>        ↓<br>     reduce()</pre><pre>Do I need one matching element?<br>        ↓<br>      find()</pre><pre>Do I need a true/false check?<br>        ↓<br>   some() / every()</pre><pre>Do I need to flatten arrays?<br>        ↓<br> flat() / flatMap()</pre><pre>Do I need to organize elements?<br>        ↓<br>      sort()</pre><p>These methods are fundamental to modern JavaScript development and appear frequently when working with APIs, frontend applications, databases, and frameworks such as React.</p><h3>What’s Next?</h3><p>In the next part of this JavaScript series, we’ll move deeper into <strong>JavaScript Objects</strong>, including:</p><ul><li>Object Literals</li><li>Property Descriptors</li><li>Object Methods</li><li>Shallow vs Deep Copy</li><li>Object.freeze()</li><li>Object.seal()</li></ul><p>Understanding arrays and objects together will give you a much stronger foundation for working with real-world JavaScript data.</p><p>If you found this article useful, follow along with the series as we continue building JavaScript fundamentals step by step.</p><p>🔗 Follow the playlist —<a href="https://medium.com/@tuhinkairi/list/js-tutorial-beginner-to-advanced-b66cdf33a203"> Link</a></p><p>happy coding 🫰🏻❤️</p><h3><strong>Keywords</strong></h3><p>#JavaScript #WebDevelopment #Programming #JavaScriptTutorial #100DaysOfCode</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d5951f677277" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Two Sum: Decode the Problem and Find the Optimal Solution | DSA Interview Preparation | Part — 2]]></title>
            <link>https://medium.com/@tuhinkairi/two-sum-decode-the-problem-and-find-the-optimal-solution-dsa-interview-preparation-part-2-61239caf0797?source=rss-486354359cd2------2</link>
            <guid isPermaLink="false">https://medium.com/p/61239caf0797</guid>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[two-pointers]]></category>
            <category><![CDATA[cpp]]></category>
            <category><![CDATA[arrays]]></category>
            <category><![CDATA[interview]]></category>
            <dc:creator><![CDATA[Tuhin Kairi]]></dc:creator>
            <pubDate>Thu, 13 Aug 2026 18:45:05 GMT</pubDate>
            <atom:updated>2026-08-13T18:53:04.103Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zC1whvqlHfQZ_TdSVQLfDw.png" /><figcaption>Two Sum: Decode the Problem and Find the Optimal Solution | DSA Interview Preparation | Part — 2</figcaption></figure><p><em>Learn how to solve </em><strong><em>LeetCode Two Sum</em></strong><em> using a simple interview-focused approach. This walkthrough explains how to decode the problem, move from brute force to the </em><strong><em>optimal HashMap solution</em></strong><em>, and understand the complete </em><strong><em>C++ implementation, dry run, time complexity, and problem-solving pattern</em></strong><em> for coding interviews.</em></p><p>If you have already gone through the basics of arrays and traversal, this problem is where we start shifting from <strong>knowing syntax to thinking in patterns</strong>.</p><p>Today, we’ll solve <strong>LeetCode #1 — Two Sum</strong>.</p><p><a href="https://leetcode.com/problems/two-sum/?utm_source=chatgpt.com">Solve Two Sum on LeetCode</a></p><h3>The Problem</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/957/1*Sa7qEdurtFlb4RkC5hKE6w.png" /></figure><p>You are given:</p><pre>nums = [2, 7, 11, 15]<br>target = 9</pre><p>Find the <strong>indices of two numbers</strong> whose sum equals the target.</p><p>For this example:</p><pre>2 + 7 = 9</pre><pre>indices → 0, 1</pre><p>So the answer is:</p><pre>[0, 1]</pre><p>The problem guarantees that:</p><ul><li>There is exactly one valid answer.</li><li>You cannot use the same element twice.</li><li>The order of the returned indices does not matter.</li></ul><p>These are the important constraints to extract before writing any code.</p><h3>Before Coding: Decode the Problem</h3><p>Don’t immediately think about HashMaps.</p><p>First ask:</p><blockquote><strong><em>What exactly am I being asked to find?</em></strong></blockquote><p>We have:</p><pre>Input:<br>    Array + Target</pre><pre>Need:<br>    Two indices</pre><pre>Condition:<br>    nums[i] + nums[j] == target</pre><p>That’s it.</p><p>Now let’s think like we are sitting in an interview.</p><h3>Stage 1 — The Obvious Approach</h3><h3>Thought</h3><p><strong>“I need two numbers. So why not check every possible pair?”</strong></p><p>Exactly.</p><p>Start with the first element and compare it with every element after it.</p><p>Then move to the second element and do the same.</p><p>For:</p><pre>[2, 7, 11, 15]</pre><p>We check:</p><pre>2 + 7<br>2 + 11<br>2 + 15</pre><pre>7 + 11<br>7 + 15</pre><pre>11 + 15</pre><p>Eventually:</p><pre>2 + 7 = 9</pre><p>Return:</p><pre>[0, 1]</pre><h3>Interview Thought Process</h3><blockquote><em>“The straightforward solution is to generate every pair and check whether their sum equals the target.”</em></blockquote><p>This gives us a valid baseline.</p><h3>Stage 2 — What Is Costing Us?</h3><p>The problem is not that checking a pair is expensive.</p><p>The problem is <strong>how many pairs we check</strong>.</p><p>For every element, we potentially scan the remaining array.</p><p>That gives us:</p><pre>O(n²)</pre><p>So now the interviewer asks:</p><blockquote><strong><em>Can you do better than O(n²)?</em></strong></blockquote><p>This is where optimization starts.</p><h3>Stage 3 — Look at the Equation</h3><p>Instead of asking:</p><pre>Which two numbers add up to target?</pre><p>Rewrite the equation.</p><p>If:</p><pre>num1 + num2 = target</pre><p>then:</p><pre>num2 = target - num1</pre><p>This changes the question.</p><p>Instead of:</p><blockquote><em>“Which number can I pair with this?”</em></blockquote><p>We can ask:</p><blockquote><strong><em>“Have I already seen the number I need?”</em></strong></blockquote><p>For example:</p><pre>nums = [2, 7, 11, 15]<br>target = 9</pre><p>Start with:</p><pre>2</pre><p>What number do we need?</p><pre>9 - 2 = 7</pre><p>Have we seen 7?</p><pre>No</pre><p>So remember 2.</p><p>Move to:</p><pre>7</pre><p>What do we need?</p><pre>9 - 7 = 2</pre><p>Have we seen 2?</p><pre>Yes</pre><p>Done.</p><pre>[0, 1]</pre><h3>Stage 4 — What Data Structure Can Help?</h3><p>Now we have a very specific requirement:</p><blockquote><em>Store numbers we’ve already seen and quickly check whether another number exists.</em></blockquote><p>A <strong>HashMap</strong> is perfect for this.</p><p>We’ll store:</p><pre>number → index</pre><p>For example:</p><pre>2 → 0<br>7 → 1</pre><p>Now checking whether a required number exists is approximately <strong>O(1)</strong> on average.</p><p>This turns the overall solution from:</p><pre>O(n²)</pre><p>into:</p><pre>O(n)</pre><p>This is the core pattern behind Two Sum:</p><blockquote><strong><em>Use a HashMap to remember previously seen values and look for the required complement.</em></strong></blockquote><h3>The Important Interview Moment</h3><p>Before looking at the code, <strong>stop here and solve it yourself.</strong></p><p>Take:</p><pre>nums = [3, 2, 4]<br>target = 6</pre><p>Try to implement the approach we just discussed.</p><p>Ask yourself:</p><ol><li>What should the HashMap store?</li><li>What should I calculate for every number?</li><li>When should I check the HashMap?</li><li>When should I insert the current number?</li><li>What indices should I return?</li></ol><p>Try it first.</p><p><strong>Don’t jump to the solution yet.</strong></p><h3>Optimal Solution</h3><p>The implementation is actually quite small once the idea is clear.</p><pre>class Solution {<br>public:<br>    vector&lt;int&gt; twoSum(vector&lt;int&gt;&amp; nums, int target) {<br>        unordered_map&lt;int, int&gt; seen;<br><br>        for (int i = 0; i &lt; nums.size(); i++) {<br>            int complement = target - nums[i];<br>            if (seen.find(complement) != seen.end()) {<br>                return {seen[complement], i};<br>            }<br>            seen[nums[i]] = i;<br>        }<br>        return {};<br>    }<br>};</pre><h3>Code Walkthrough</h3><p>Let’s break down the important parts.</p><h3>1. Create the HashMap</h3><pre>unordered_map&lt;int, int&gt; seen;</pre><p>We store:</p><pre>number → index</pre><h3>2. Traverse the array</h3><pre>for (int i = 0; i &lt; nums.size(); i++)</pre><p>We process each element once.</p><h3>3. Find the required number</h3><pre>int complement = target - nums[i];</pre><p>If:</p><pre>target = 9<br>nums[i] = 2</pre><p>then:</p><pre>complement = 9 - 2<br>           = 7</pre><p>So we’re looking for 7.</p><h3>4. Check whether we already saw it</h3><pre>if (seen.find(complement) != seen.end())</pre><p>If the complement exists, we already have the other half of the answer.</p><p>Return:</p><pre>return {seen[complement], i};</pre><h3>5. Otherwise, remember the current number</h3><pre>seen[nums[i]] = i;</pre><p>For example:</p><pre>2 → 0</pre><p>Then continue.</p><h3>Quick Dry Run</h3><p>Input:</p><pre>nums = [2, 7, 11, 15]<br>target = 9</pre><h3>i = 0</h3><pre>num = 2<br>complement = 9 - 2 = 7</pre><p>7 isn&#39;t in the map.</p><p>Store:</p><pre>2 → 0</pre><h3>i = 1</h3><pre>num = 7<br>complement = 9 - 7 = 2</pre><p>2 exists.</p><pre>2 → index 0<br>7 → index 1</pre><p>Return:</p><pre>[0, 1]</pre><p>Done.</p><h3>Why Do We Check Before Inserting?</h3><p>This is a small but important detail.</p><p>Consider:</p><pre>nums = [3, 3]<br>target = 6</pre><p>At the first 3:</p><pre>complement = 6 - 3 = 3</pre><p>The map is empty.</p><p>So we insert:</p><pre>3 → 0</pre><p>At the second 3:</p><pre>complement = 3</pre><p>Now the map contains it.</p><p>Return:</p><pre>[0, 1]</pre><p>This also ensures we don’t accidentally use the <strong>same array position twice</strong>.</p><h3>Complexity</h3><h3>Time</h3><pre>O(n)</pre><p>We traverse the array once.</p><p>HashMap lookup and insertion are <strong>O(1) on average</strong>.</p><h3>Space</h3><pre>O(n)</pre><p>In the worst case, we may store almost every element in the HashMap.</p><h3>The Pattern to Remember</h3><p>Don’t memorize:</p><pre>unordered_map&lt;int, int&gt;</pre><p>Memorize the <strong>thinking pattern</strong>:</p><pre>Need two values<br>      ↓<br>Rewrite the equation<br>      ↓<br>required = target - current<br>      ↓<br>Have I seen required before?<br>      ↓<br>Yes → answer<br>No  → remember current</pre><p>This is the more important takeaway.</p><p>Two Sum is also your first introduction to the <strong>Hashing pattern</strong>, which will appear again later in problems such as Contains Duplicate, Group Anagrams, Top K Frequent Elements, and Longest Consecutive Sequence.</p><h3>Interview Takeaway</h3><p>When you see a problem like:</p><blockquote><em>“Find two values that satisfy some condition.”</em></blockquote><p>Don’t immediately jump to nested loops.</p><p>Ask:</p><pre>Can I calculate what the second value must be?</pre><p>If yes:</p><pre>Can I store previously seen values?</pre><p>If yes:</p><pre>HashMap might be the optimization.</pre><p>That thought process is much more valuable than memorizing the Two Sum code.</p><h3>Practice Challenge</h3><p>Before moving forward, try solving Two Sum again <strong>without looking at the solution</strong>.</p><p>Then try these variations:</p><ol><li>What if the array is already sorted?</li><li>What if you need to return the values instead of indices?</li><li>What if there can be multiple valid pairs?</li></ol><p>These variations will naturally lead us toward other patterns later in the series.</p><h3>Next</h3><p>In the next solution walkthrough, we’ll continue with the remaining Array problems and focus on recognizing <strong>which pattern fits the problem instead of trying random techniques</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=61239caf0797" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript Arrays, Data Types & Loops Explained with Simple Examples (Day — 10)]]></title>
            <link>https://medium.com/@tuhinkairi/javascript-arrays-data-types-loops-explained-with-simple-examples-day-10-108b0fb32365?source=rss-486354359cd2------2</link>
            <guid isPermaLink="false">https://medium.com/p/108b0fb32365</guid>
            <category><![CDATA[javascript-loops]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Tuhin Kairi]]></dc:creator>
            <pubDate>Mon, 10 Aug 2026 11:52:41 GMT</pubDate>
            <atom:updated>2026-08-10T11:52:41.221Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9ui0rUGhqdd7S_SdyWmmsw.png" /></figure><p><em>Learn JavaScript Arrays and Loops with simple examples. Understand array indexing, data types, length, adding and removing elements, </em><em>for, </em><em>while, </em><em>do...while, </em><em>for...of, and </em><em>for...in loops in this beginner-friendly JavaScript tutorial.</em></p><p><strong>Welcome back to Day — 10 of the JavaScript Beginner to Advanced series!</strong></p><p>In our previous session, we explored <strong>Math, Precision, and BigInt</strong>. Today, we’re diving into one of the most powerful and versatile features of JavaScript: <strong>Arrays</strong>.</p><p>Arrays are one of the most commonly used data structures in JavaScript.</p><p>Whether you are building a frontend application, working with APIs, processing data, or solving DSA problems, you will use <strong>arrays and loops</strong> constantly.</p><p>In this part of the JavaScript series, we will learn:</p><ul><li>What is an Array?</li><li>How to create an Array</li><li>Array data types</li><li>Accessing and updating elements</li><li>Adding and removing elements</li><li>Array length</li><li>Basic array traversal</li><li>for loop</li><li>while loop</li><li>do...while loop</li><li>for...of loop</li><li>for...in loop</li><li>When to use each loop</li></ul><p>you can follow the Full Series on 👉🏻 — <a href="https://medium.com/@tuhinkairi/list/js-tutorial-beginner-to-advanced-b66cdf33a203">Link</a></p><h3>What is an Array in JavaScript?</h3><p>An <strong>Array</strong> is a data structure used to store multiple values in a single variable.</p><p>Instead of creating separate variables:</p><pre>let student1 = &quot;Rahul&quot;;<br>let student2 = &quot;Priya&quot;;<br>let student3 = &quot;Amit&quot;;</pre><p>We can store them inside an array:</p><pre>let students = [&quot;Rahul&quot;, &quot;Priya&quot;, &quot;Amit&quot;];</pre><p>Now, all three values are stored inside one variable.</p><pre>console.log(students);</pre><p>Output:</p><pre>[&quot;Rahul&quot;, &quot;Priya&quot;, &quot;Amit&quot;]</pre><p>Arrays are <strong>ordered collections</strong>, meaning every element has a position called an <strong>index</strong>.</p><h3>Array Indexing</h3><p>JavaScript arrays use <strong>zero-based indexing</strong>.</p><p>That means the first element starts at index 0.</p><pre>let fruits = [&quot;Apple&quot;, &quot;Banana&quot;, &quot;Mango&quot;];</pre><p>ElementIndexApple0Banana1Mango2</p><p>To access an element:</p><pre>console.log(fruits[0]);</pre><p>Output:</p><pre>Apple</pre><p>And:</p><pre>console.log(fruits[2]);</pre><p>Output:</p><pre>Mango</pre><h3>Remember</h3><p>The last element is always:</p><pre>array.length - 1</pre><p>For example:</p><pre>console.log(fruits.length);</pre><p>Output:</p><pre>3</pre><p>So the last index is:</p><pre>3 - 1 = 2</pre><h3>Creating Arrays</h3><p>There are several ways to create an array.</p><h3>Using Array Literals</h3><p>This is the most common approach:</p><pre>let numbers = [10, 20, 30, 40];</pre><h3>Empty Array</h3><pre>let users = [];</pre><p>You can add elements later.</p><pre>users.push(&quot;Tuhin&quot;);<br>users.push(&quot;Rahul&quot;);</pre><h3>Using the Array Constructor</h3><pre>let numbers = new Array(10, 20, 30);</pre><p>However, for normal development, array literals are generally easier to read:</p><pre>let numbers = [10, 20, 30];</pre><h3>Can an Array Store Different Data Types?</h3><p>Yes.</p><p>JavaScript arrays can contain values of different data types.</p><p>For example:</p><pre>let data = [<br>    &quot;Tuhin&quot;,<br>    25,<br>    true,<br>    null,<br>    undefined<br>];</pre><p>An array can contain:</p><ul><li>String</li><li>Number</li><li>Boolean</li><li>null</li><li>undefined</li><li>Objects</li><li>Other arrays</li><li>Functions</li></ul><p>Example:</p><pre>let mixed = [<br>    &quot;JavaScript&quot;,<br>    100,<br>    true,<br>    { name: &quot;Tuhin&quot; },<br>    [1, 2, 3]<br>];</pre><p>This is possible because JavaScript is <strong>dynamically typed</strong>.</p><p>However, in real applications, keeping arrays logically consistent usually makes the code easier to understand.</p><p>For example:</p><pre>let prices = [100, 200, 300, 400];</pre><p>is easier to work with than:</p><pre>let data = [100, &quot;Hello&quot;, true, null];</pre><h3>Arrays Are Objects in JavaScript</h3><p>One interesting fact:</p><pre>typeof [];</pre><p>returns:</p><pre>&quot;object&quot;</pre><p>That’s because arrays are a special type of object in JavaScript.</p><p>But there is a better way to check whether a value is an array:</p><pre>Array.isArray([]);</pre><p>Output:</p><pre>true</pre><p>For example:</p><pre>let numbers = [1, 2, 3];</pre><pre>console.log(Array.isArray(numbers));</pre><p>Output:</p><pre>true</pre><h3>Updating Array Elements</h3><p>Arrays are mutable, meaning their elements can be changed.</p><pre>let fruits = [&quot;Apple&quot;, &quot;Banana&quot;, &quot;Mango&quot;];</pre><pre>fruits[1] = &quot;Orange&quot;;</pre><pre>console.log(fruits);</pre><p>Output:</p><pre>[&quot;Apple&quot;, &quot;Orange&quot;, &quot;Mango&quot;]</pre><p>We changed the value at index 1.</p><h3>Adding Elements to an Array</h3><h3>push()</h3><p>push() adds an element to the <strong>end</strong> of an array.</p><pre>let fruits = [&quot;Apple&quot;, &quot;Banana&quot;];</pre><pre>fruits.push(&quot;Mango&quot;);</pre><pre>console.log(fruits);</pre><p>Output:</p><pre>[&quot;Apple&quot;, &quot;Banana&quot;, &quot;Mango&quot;]</pre><h3>unshift()</h3><p>unshift() adds an element to the <strong>beginning</strong>.</p><pre>fruits.unshift(&quot;Orange&quot;);</pre><pre>console.log(fruits);</pre><p>Output:</p><pre>[&quot;Orange&quot;, &quot;Apple&quot;, &quot;Banana&quot;, &quot;Mango&quot;]</pre><h3>Removing Elements from an Array</h3><h3>pop()</h3><p>pop() removes the last element.</p><pre>let fruits = [&quot;Apple&quot;, &quot;Banana&quot;, &quot;Mango&quot;];</pre><pre>fruits.pop();</pre><pre>console.log(fruits);</pre><p>Output:</p><pre>[&quot;Apple&quot;, &quot;Banana&quot;]</pre><h3>shift()</h3><p>shift() removes the first element.</p><pre>fruits.shift();</pre><pre>console.log(fruits);</pre><p>Output:</p><pre>[&quot;Banana&quot;]</pre><h3>Array Length</h3><p>The length property tells us how many elements are present.</p><pre>let numbers = [10, 20, 30, 40];</pre><pre>console.log(numbers.length);</pre><p>Output:</p><pre>4</pre><p>It is especially useful when working with loops.</p><pre>for (let i = 0; i &lt; numbers.length; i++) {<br>    console.log(numbers[i]);<br>}</pre><p>Output:</p><pre>10<br>20<br>30<br>40</pre><h3>What is a Loop?</h3><p>A <strong>loop</strong> allows us to execute the same block of code repeatedly.</p><p>For example, suppose we have:</p><pre>let numbers = [10, 20, 30, 40, 50];</pre><p>Instead of writing:</p><pre>console.log(numbers[0]);<br>console.log(numbers[1]);<br>console.log(numbers[2]);<br>console.log(numbers[3]);<br>console.log(numbers[4]);</pre><p>we can use a loop:</p><pre>for (let i = 0; i &lt; numbers.length; i++) {<br>    console.log(numbers[i]);<br>}</pre><p>This is one of the most important patterns you will use when working with arrays.</p><h3>1. for Loop</h3><p>The traditional for loop has three main parts:</p><pre>for (initialization; condition; update) {<br>    // code<br>}</pre><p>Example:</p><pre>for (let i = 0; i &lt; 5; i++) {<br>    console.log(i);<br>}</pre><p>Output:</p><pre>0<br>1<br>2<br>3<br>4</pre><h3>Understanding the Three Parts</h3><pre>let i = 0;</pre><p>Initialization — where the loop starts.</p><pre>i &lt; 5;</pre><p>Condition — the loop continues while this is true.</p><pre>i++;</pre><p>Update — changes the value after every iteration.</p><h3>Looping Through an Array</h3><p>The for loop is very useful when you need the <strong>index</strong>.</p><pre>let fruits = [&quot;Apple&quot;, &quot;Banana&quot;, &quot;Mango&quot;];</pre><pre>for (let i = 0; i &lt; fruits.length; i++) {<br>    console.log(fruits[i]);<br>}</pre><p>Output:</p><pre>Apple<br>Banana<br>Mango</pre><p>You can also access the index:</p><pre>for (let i = 0; i &lt; fruits.length; i++) {<br>    console.log(i, fruits[i]);<br>}</pre><p>Output:</p><pre>0 &quot;Apple&quot;<br>1 &quot;Banana&quot;<br>2 &quot;Mango&quot;</pre><h3>2. while Loop</h3><p>A while loop runs as long as its condition is true.</p><p>Syntax:</p><pre>while (condition) {<br>    // code<br>}</pre><p>Example:</p><pre>let i = 0;</pre><pre>while (i &lt; 5) {<br>    console.log(i);<br>    i++;<br>}</pre><p>Output:</p><pre>0<br>1<br>2<br>3<br>4</pre><p>Be careful with the update:</p><pre>i++;</pre><p>Without it, the condition may remain true forever, creating an <strong>infinite loop</strong>.</p><h3>3. do...while Loop</h3><p>The do...while loop is similar to while, but there is one important difference.</p><p>The code executes <strong>at least once</strong>.</p><pre>let i = 0;</pre><pre>do {<br>    console.log(i);<br>    i++;<br>} while (i &lt; 5);</pre><p>Output:</p><pre>0<br>1<br>2<br>3<br>4</pre><p>Consider this example:</p><pre>let i = 10;</pre><pre>do {<br>    console.log(i);<br>    i++;<br>} while (i &lt; 5);</pre><p>Output:</p><pre>10</pre><p>Even though i &lt; 5 is false, the code runs once.</p><h3>4. for...of Loop</h3><p>for...of is a simple way to iterate over the <strong>values</strong> of an array.</p><pre>let fruits = [&quot;Apple&quot;, &quot;Banana&quot;, &quot;Mango&quot;];</pre><pre>for (let fruit of fruits) {<br>    console.log(fruit);<br>}</pre><p>Output:</p><pre>Apple<br>Banana<br>Mango</pre><p>You don’t need to manually manage an index.</p><p>Compare:</p><pre>for (let i = 0; i &lt; fruits.length; i++) {<br>    console.log(fruits[i]);<br>}</pre><p>with:</p><pre>for (let fruit of fruits) {<br>    console.log(fruit);<br>}</pre><p>For simply reading array values, for...of is often cleaner.</p><h3>5. for...in Loop</h3><p>for...in iterates over <strong>keys or indexes</strong>.</p><p>Example:</p><pre>let fruits = [&quot;Apple&quot;, &quot;Banana&quot;, &quot;Mango&quot;];</pre><pre>for (let index in fruits) {<br>    console.log(index);<br>}</pre><p>Output:</p><pre>0<br>1<br>2</pre><p>You can use the index to access the value:</p><pre>for (let index in fruits) {<br>    console.log(fruits[index]);<br>}</pre><p>Output:</p><pre>Apple<br>Banana<br>Mango</pre><h3>for...of vs for...in</h3><p>This is important to remember:</p><pre>for (let value of fruits) {<br>    console.log(value);<br>}</pre><p>gives:</p><pre>Apple<br>Banana<br>Mango</pre><p>While:</p><pre>for (let index in fruits) {<br>    console.log(index);<br>}</pre><p>gives:</p><pre>0<br>1<br>2</pre><p>So:</p><p><strong>for...of → values</strong></p><p><strong>for...in → keys/indexes</strong></p><p>For arrays, for...of is generally the more natural choice when you want the values.</p><h3>break in Loops</h3><p>break stops the loop immediately.</p><pre>for (let i = 0; i &lt; 10; i++) {<br><br>if (i === 5) {<br>        break;<br>    }<br>   console.log(i);<br>}</pre><p>Output:</p><pre>0<br>1<br>2<br>3<br>4</pre><p>When i becomes 5, the loop stops.</p><h3>continue in Loops</h3><p>continue skips the current iteration and moves to the next one.</p><pre>for (let i = 0; i &lt; 5; i++) {<br><br>if (i === 2) {<br>        continue;<br>    }<br>console.log(i);<br>}</pre><p>Output:</p><pre>0<br>1<br>3<br>4</pre><p>The value 2 was skipped.</p><h3>Arrays + Loops: A Common Pattern</h3><p>Arrays and loops are frequently used together.</p><p>For example, finding the sum of numbers:</p><pre>let numbers = [10, 20, 30, 40];</pre><pre>let sum = 0;</pre><pre>for (let i = 0; i &lt; numbers.length; i++) {<br>    sum += numbers[i];<br>}</pre><pre>console.log(sum);</pre><p>Output:</p><pre>100</pre><p>Here:</p><pre>let sum = 0;</pre><p>stores the result while the loop runs.</p><p>This pattern becomes extremely important when learning <strong>DSA</strong>.</p><h3>Which Loop Should You Use?</h3><p>LoopBest UseforWhen you need index/controlwhileWhen the number of iterations is uncertaindo...whileWhen code must run at least oncefor...ofWhen you need array valuesfor...inWhen you need keys/indexes</p><p>For arrays, a simple rule is:</p><pre>Need index?     → for<br>Need values?    → for...of<br>Need keys?      → for...in<br>Unknown count?  → while<br>Run at least once? → do...while</pre><h3>Quick Summary</h3><p>ConceptPurposeArrayStore multiple valuesIndexAccess an array elementlengthGet number of elementspush()Add to the endpop()Remove from the endunshift()Add to the beginningshift()Remove from the beginningforControlled iterationwhileRepeat while condition is truedo...whileExecute at least oncefor...ofIterate over valuesfor...inIterate over keys/indexesbreakStop the loopcontinueSkip current iteration</p><h3>Final Thoughts</h3><p>Arrays and loops are fundamental JavaScript concepts.</p><p>You will see them everywhere:</p><ul><li>Frontend development</li><li>API response handling</li><li>Data processing</li><li>React applications</li><li>Backend development</li><li>Algorithms</li><li>Data Structures and Algorithms (DSA)</li></ul><p>Before moving to advanced array methods such as map(), filter(), reduce(), find(), some(), and every(), make sure you are comfortable with <strong>array indexing and basic loops</strong>.</p><p>The goal is not just to memorize syntax.</p><p>Understand what happens during each iteration.</p><p>Once that becomes clear, more advanced JavaScript array methods and DSA problems become much easier to understand.</p><h3>What’s Next?</h3><p>In the next part of this JavaScript series, we will go deeper into <strong>JavaScript Array Methods</strong>, including:</p><p>map() → Transform data<br>filter() → Select data<br>reduce() → Build a single result<br>find() → Find an element<br>some() → Check if at least one matches<br>every() → Check if all match<br>flat() → Flatten nested arrays<br>flatMap() → Map and flatten</p><p>Keep practicing these fundamentals because arrays and iteration are building blocks for both <strong>JavaScript development and DSA</strong>.</p><h3>Follow Along</h3><p>If you are following this JavaScript series from the beginning, continue with the next part to gradually build a strong foundation in JavaScript.</p><p>If this article helped you understand arrays and loops, consider following me for more beginner-friendly JavaScript, DSA, full-stack development, and AI/ML content.</p><p>Thanks for reading.</p><h3>Links</h3><p>👉🏻 <a href="https://medium.com/@tuhinkairi/javascript-numbers-explained-math-precision-and-bigint-with-simple-examples-day-9-0dec4bf45419?sharedUserId=tuhinkairi"><em>learn about JS Math, Precision, and BigInt (Day</em></a><em> — </em><a href="https://medium.com/@tuhinkairi/javascript-numbers-explained-math-precision-and-bigint-with-simple-examples-day-9-0dec4bf45419?sharedUserId=tuhinkairi"><em>9)</em></a></p><p>👉🏻 <a href="https://medium.com/@tuhinkairi/javascript-strings-explained-string-methods-operations-day-8-9fbaa0cbb732?sharedUserId=tuhinkairi"><em>learn about String Methods &amp; Operations (Day — 8)</em></a></p><h3><strong>keywords:</strong></h3><p>JavaScript Arrays, JavaScript Array Tutorial, JavaScript Loops, JavaScript for loop, JavaScript while loop, JavaScript for of loop, JavaScript for in loop, JavaScript Array Methods, JavaScript Data Types, Learn JavaScript, JavaScript Tutorial for Beginners, JavaScript Array Iteration, JavaScript Programming</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=108b0fb32365" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Arrays in DSA Explained Simply | Basic Traversal & Two Sum | Part 1]]></title>
            <link>https://medium.com/@tuhinkairi/arrays-in-dsa-explained-simply-basic-traversal-two-sum-part-1-ec3aa3d40868?source=rss-486354359cd2------2</link>
            <guid isPermaLink="false">https://medium.com/p/ec3aa3d40868</guid>
            <category><![CDATA[data-structure-algorithm]]></category>
            <category><![CDATA[job-interview-preparation]]></category>
            <category><![CDATA[dsa-courses]]></category>
            <category><![CDATA[two-pointers]]></category>
            <category><![CDATA[interview]]></category>
            <dc:creator><![CDATA[Tuhin Kairi]]></dc:creator>
            <pubDate>Sun, 09 Aug 2026 11:27:00 GMT</pubDate>
            <atom:updated>2026-08-09T11:27:00.932Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wZ9uJKLuzpJ8dI5cos_WuA.png" /><figcaption>Arrays in DSA Explained Simply | Basic Traversal &amp; Two Sum | Part 1</figcaption></figure><p><em>Learn Arrays in DSA for coding interviews with this beginner-friendly Part 1 guide. Understand array traversal, Two Sum, hashing patterns, complexity, interview strategies, and essential LeetCode practice problems.</em></p><p>Arrays are usually one of the first data structures you encounter in DSA.</p><p>But in coding interviews, the challenge is rarely:</p><blockquote><em>“Do you know what an array is?”</em></blockquote><p>The real question is:</p><blockquote><strong><em>Can you look at an array problem and quickly recognize the approach needed to solve it?</em></strong></blockquote><p>In this article, we will start with the most fundamental array technique: <strong>traversal</strong>.</p><p>Then we will move to one of the most important beginner interview problems:</p><p><strong>Two Sum</strong></p><p>Along the way, we will learn how to recognize the <strong>Hashing pattern</strong> behind Two Sum and build a reusable way of thinking about similar problems.</p><h3>What You Will Learn</h3><p>By the end of this article, you will understand:</p><ul><li>What an array is</li><li>How array traversal works</li><li>Common types of array traversal questions</li><li>How to approach an array problem during an interview</li><li>The Two Sum problem</li><li>The brute-force thinking behind Two Sum</li><li>The Hashing pattern behind the optimized approach</li><li>How to recognize similar problems</li><li>Which LeetCode problems you should practice next</li></ul><h3>1. What Is an Array?</h3><p>An <strong>array</strong> is a data structure used to store multiple values in a sequence.</p><p>For example:</p><pre>[10, 20, 30, 40, 50]</pre><p>Each value has a position called an <strong>index</strong>.</p><pre>Value:    10   20   30   40   50<br>Index:     0    1    2    3    4</pre><p>In most programming languages, array indexing starts from 0.</p><p>So:</p><pre>arr[0] → 10<br>arr[1] → 20<br>arr[2] → 30<br>arr[3] → 40<br>arr[4] → 50</pre><h3>Real-World Analogy</h3><p>Think of an array as a row of numbered lockers.</p><pre>┌────┬────┬────┬────┬────┐<br>│ 10 │ 20 │ 30 │ 40 │ 50 │<br>└────┴────┴────┴────┴────┘<br>  0    1    2    3    4</pre><p>If you know the position, you can directly access the value.</p><p>That is one of the reasons arrays are so useful.</p><h3>2. The First Array Skill: Traversal</h3><p>Before learning complicated patterns, you need to become comfortable with one basic operation:</p><blockquote><strong><em>Visiting every element of an array.</em></strong></blockquote><p>This is called <strong>array traversal</strong>.</p><p>For example:</p><pre>[4, 7, 2, 9, 1]</pre><p>A traversal visits:</p><pre>4 → 7 → 2 → 9 → 1</pre><p>A simple loop can do this:</p><pre>for each element in the array:<br>    process the element</pre><p>In JavaScript:</p><pre>const arr = [4, 7, 2, 9, 1];</pre><pre>for (let i = 0; i &lt; arr.length; i++) {<br>    console.log(arr[i]);<br>}</pre><p>The important idea is not the syntax.</p><p>The important idea is:</p><blockquote><strong><em>Move through the array one element at a time and perform some operation on each element.</em></strong></blockquote><h3>3. Basic Traversal Pattern</h3><p>A large number of beginner array questions follow this structure:</p><pre>Start<br>  ↓<br>Visit element<br>  ↓<br>Perform operation<br>  ↓<br>Move to next element<br>  ↓<br>Repeat until the array ends</pre><p>Generic pseudocode:</p><pre>for i = 0 to n - 1:</pre><pre>    process arr[i]</pre><p>This simple pattern can solve many problems.</p><p>For example:</p><h3>Find the maximum</h3><pre>[4, 8, 2, 10, 6]</pre><pre>Start with max = 4</pre><pre>Compare:<br>8 &gt; 4  → max = 8<br>2 &gt; 8  → no<br>10 &gt; 8 → max = 10<br>6 &gt; 10 → no</pre><pre>Answer = 10</pre><h3>Find the sum</h3><pre>[2, 4, 6, 8]</pre><pre>sum = 0</pre><pre>sum = 0 + 2<br>sum = 2 + 4<br>sum = 6 + 6<br>sum = 12 + 8</pre><pre>Answer = 20</pre><h3>Count something</h3><p>Suppose we want to count even numbers:</p><pre>[1, 4, 7, 8, 10]</pre><pre>1 → ignore<br>4 → count<br>7 → ignore<br>8 → count<br>10 → count</pre><pre>Answer = 3</pre><p>The underlying pattern is still the same:</p><blockquote><strong><em>Traverse → inspect → update some state.</em></strong></blockquote><h3>4. Common Basic Traversal Question Types</h3><p>When you see a simple array problem, ask:</p><p><strong>“Can I solve this by visiting each element once?”</strong></p><p>Common examples include:</p><p>Question TypeWhat You Usually MaintainFind maximummaxFind minimumminCalculate sumsumCount elementscountFind an elementfound / indexCount occurrencesfrequency/countCheck a conditionbooleanModify elementsarray/index</p><p>These problems are important because they build your basic array intuition.</p><h3>5. Complexity of Basic Traversal</h3><p>Suppose an array contains n elements.</p><p>If you visit every element exactly once:</p><pre>[1] → [2] → [3] → ... → [n]</pre><p>You perform approximately n operations.</p><p>Therefore:</p><h3>Time Complexity</h3><pre>O(n)</pre><h3>Space Complexity</h3><p>Usually:</p><pre>O(1)</pre><p>if you only maintain variables such as:</p><pre>sum<br>max<br>min<br>count</pre><p>So the general pattern is:</p><p>ApproachTimeExtra SpaceSingle traversalO(n)O(1)</p><blockquote><em>💡 </em><strong><em>Interview Insight:</em></strong><em> If a problem only asks you to inspect every element once, your first instinct should usually be a single traversal.</em></blockquote><h3>6. But Array Problems Become More Interesting</h3><p>Now imagine the interviewer gives you:</p><pre>nums = [2, 7, 11, 15]<br>target = 9</pre><p>And asks:</p><blockquote><em>Find two numbers whose sum equals the target.</em></blockquote><p>Now simply traversing once isn’t enough.</p><p>You need to compare elements with other elements.</p><p>This brings us to one of the most famous array interview problems:</p><h3>Two Sum</h3><p><a href="https://leetcode.com/problems/two-sum/?utm_source=chatgpt.com">LeetCode — Two Sum</a></p><h3>7. Two Sum: Understand the Problem</h3><p>Suppose:</p><pre>nums = [2, 7, 11, 15]<br>target = 9</pre><p>We need to find two numbers whose sum is 9.</p><p>Look at:</p><pre>2 + 7 = 9</pre><p>So the answer is the indices of 2 and 7.</p><pre>[2, 7, 11, 15]<br> ↑  ↑<br> 0  1</pre><p>Answer:</p><pre>[0, 1]</pre><p>The important part is not memorizing the solution.</p><p>Instead, ask:</p><blockquote><strong><em>While looking at one number, what information do I need to find its partner?</em></strong></blockquote><h3>8. Start With Brute Force Thinking</h3><p>Suppose we are currently looking at:</p><pre>2</pre><p>The target is:</p><pre>9</pre><p>What number do we need?</p><pre>9 - 2 = 7</pre><p>So we need to find:</p><pre>7</pre><p>Now look at the next element.</p><pre>7</pre><p>Found it.</p><p>This gives us an important observation:</p><blockquote><em>For every number </em><em>x, the number we need is </em><em>target - x.</em></blockquote><p>This is called the <strong>complement</strong>.</p><pre>complement = target - currentNumber</pre><p>For:</p><pre>target = 9<br>current = 2</pre><p>we get:</p><pre>complement = 9 - 2<br>            = 7</pre><h3>9. Brute Force Approach</h3><p>The simplest approach is:</p><pre>Take one element<br>        ↓<br>Compare it with every element after it<br>        ↓<br>Check whether their sum equals target</pre><p>For:</p><pre>[2, 7, 11, 15]</pre><p>we might check:</p><pre>2 + 7<br>2 + 11<br>2 + 15</pre><pre>7 + 11<br>7 + 15</pre><pre>11 + 15</pre><p>This works.</p><p>But there is a problem.</p><p>For an array of n elements, we may need to compare many pairs.</p><p>That results in:</p><pre>O(n²)</pre><p>time complexity.</p><p>For small inputs, that may be acceptable.</p><p>For large inputs, we want something better.</p><h3>10. The Key Question</h3><p>Let’s return to our observation:</p><pre>current number → need target - current</pre><p>Suppose:</p><pre>target = 9</pre><p>We see:</p><pre>2</pre><p>We need:</p><pre>7</pre><p>Instead of searching the entire array again, what if we could quickly answer:</p><blockquote><em>“Have I already seen 7?”</em></blockquote><p>This is where <strong>Hashing</strong> becomes useful.</p><h3>11. The Hashing Pattern</h3><p>A hash-based data structure allows us to store information so that we can quickly check whether something already exists.</p><p>Think of it like a lookup table.</p><p>Instead of repeatedly searching:</p><pre>Have I seen 7?</pre><pre>Search...<br>Search...<br>Search...</pre><p>we maintain a collection of values we have already encountered.</p><p>Conceptually:</p><pre>Seen values</pre><pre>┌────┬────┬────┐<br>│ 2  │ 7  │ 11 │<br>└────┴────┴────┘</pre><p>Now when we need 7, we can ask:</p><pre>Have I seen 7?</pre><p>If yes, we have found our pair.</p><h3>12. The Two Sum Hashing Pattern</h3><p>The reusable thought process is:</p><pre>For every number:</pre><pre>1. Calculate the complement</pre><pre>complement = target - current</pre><pre>2. Check whether complement was seen before</pre><pre>3. If yes:<br>      We found the answer</pre><pre>4. If no:<br>      Store the current number</pre><pre>5. Continue</pre><p>The pattern looks like this:</p><pre>Current number<br>                    ↓<br>        Calculate complement<br>                    ↓<br>       target - current number<br>                    ↓<br>       Have we seen it before?<br>             ↙           ↘<br>           YES            NO<br>            ↓              ↓<br>       Found pair      Store current</pre><p>This is the core idea you should remember.</p><p>Not:</p><blockquote><em>“Two Sum uses a HashMap.”</em></blockquote><p>Instead remember:</p><blockquote><strong><em>“I need a complementary value, so I can store previously seen values for fast lookup.”</em></strong></blockquote><p>That thought process is much more reusable.</p><h3>13. Recognizing the Pattern</h3><p>During an interview, watch for these clues:</p><h3>Clue 1: You need two values</h3><p>For example:</p><pre>Find two numbers...</pre><h3>Clue 2: They must satisfy a relationship</h3><p>For example:</p><pre>sum = target<br>difference = target<br>product = target</pre><h3>Clue 3: You repeatedly ask whether a required value exists</h3><p>For example:</p><pre>Does the complement already exist?</pre><h3>Clue 4: Searching repeatedly would be expensive</h3><p>If your brute-force solution looks like:</p><pre>for every element:<br>    search the remaining array</pre><p>you should ask:</p><blockquote><strong><em>Can I store previously seen information for faster lookup?</em></strong></blockquote><p>This is the beginning of recognizing the <strong>Hashing pattern</strong>.</p><h3>14. The General Hashing Pattern</h3><p>The Two Sum idea can be generalized:</p><pre>Input<br>  ↓<br>Traverse the data<br>  ↓<br>Calculate what information/value is required<br>  ↓<br>Check previously stored information<br>  ↓<br>If found → use it<br>  ↓<br>If not found → store current information<br>  ↓<br>Continue</pre><p>This pattern appears in many interview problems.</p><p>The exact information stored may change.</p><p>You might store:</p><ul><li>A value</li><li>An index</li><li>A frequency</li><li>A prefix sum</li><li>A previously seen state</li></ul><p>But the core idea remains:</p><blockquote><strong><em>Store useful information so that future lookups become faster.</em></strong></blockquote><h3>15. Two Sum: Complexity Thinking</h3><p>There are two important approaches to understand.</p><p>ApproachTimeExtra SpaceMain IdeaBrute ForceO(n²)O(1)Check every pairHashingO(n) averageO(n)Store previously seen values</p><p>The optimized approach trades additional memory for faster lookup.</p><p>This is a very common interview trade-off:</p><blockquote><strong><em>Use more space to reduce time.</em></strong></blockquote><p>You will see this idea repeatedly throughout DSA.</p><h3>16. Basic Traversal vs Two Sum</h3><p>Notice how both problems start with an array traversal.</p><h3>Basic Traversal</h3><pre>Visit each element<br>        ↓<br>Perform an operation</pre><h3>Two Sum</h3><pre>Visit each element<br>        ↓<br>Calculate required value<br>        ↓<br>Check previously seen data<br>        ↓<br>Update stored data</pre><p>So Two Sum is not completely different from basic traversal.</p><p>It builds on it.</p><p>The traversal is still there.</p><p>We have simply added a data structure to make the traversal more powerful.</p><h3>17. Common Mistakes</h3><h3>Mistake 1: Immediately writing nested loops</h3><p>Nested loops are a valid starting point.</p><p>But in an interview, don’t stop there.</p><p>Ask:</p><blockquote><em>Can I reduce repeated searching?</em></blockquote><h3>Mistake 2: Forgetting the complement</h3><p>Instead of thinking:</p><pre>What pairs can I try?</pre><p>think:</p><pre>current = x</pre><pre>required = target - x</pre><p>This turns the problem into a lookup problem.</p><h3>Mistake 3: Storing only values when the problem needs indices</h3><p>Two Sum asks for indices.</p><p>So you need to think about what information must be preserved.</p><p>This is an important interview habit:</p><blockquote><strong><em>Before choosing a data structure, ask what information the final answer requires.</em></strong></blockquote><h3>Mistake 4: Ignoring duplicate values</h3><p>Consider:</p><pre>[3, 3]<br>target = 6</pre><p>Both values are the same.</p><p>Your approach must still allow two different positions to form the answer.</p><p>Always test:</p><ul><li>Duplicate values</li><li>Negative numbers</li><li>Zero</li><li>Very small arrays</li><li>No valid answer</li></ul><h3>18. Interview Thought Process</h3><p>When you see an array problem, don’t immediately code.</p><p>Use this sequence:</p><pre>1. Understand the input<br>        ↓<br>2. Understand the expected output<br>        ↓<br>3. Try the simplest solution<br>        ↓<br>4. Identify repeated work<br>        ↓<br>5. Ask whether a data structure can reduce it<br>        ↓<br>6. Analyze time and space<br>        ↓<br>7. Handle edge cases<br>        ↓<br>8. Then code</pre><p>This is more valuable than memorizing individual solutions.</p><h3>19. Practice: Basic Traversal</h3><p>Before moving deeper into patterns, practice implementing simple traversal problems yourself.</p><h3>Practice 1 — Find Maximum</h3><p>Given:</p><pre>[3, 7, 2, 9, 4]</pre><p>Find the largest element.</p><p><strong>Goal:</strong> Implement a single traversal.</p><h3>Practice 2 — Find Minimum</h3><p>Given:</p><pre>[8, 3, 6, 1, 9]</pre><p>Find the smallest element.</p><p><strong>Goal:</strong> Maintain a min value while traversing.</p><h3>Practice 3 — Calculate Sum</h3><p>Given:</p><pre>[5, 10, 15, 20]</pre><p>Calculate the total.</p><p><strong>Goal:</strong> Maintain a running sum.</p><h3>Practice 4 — Count Even Numbers</h3><p>Given:</p><pre>[1, 4, 7, 8, 10, 13]</pre><p>Count how many numbers are even.</p><p><strong>Goal:</strong> Combine traversal with a condition.</p><h3>Practice 5 — Linear Search</h3><p>Given:</p><pre>[10, 20, 30, 40, 50]</pre><p>Find whether 30 exists.</p><p><strong>Goal:</strong> Traverse and maintain a found condition or index.</p><h3>20. Practice: Two Sum</h3><p>Now implement the Two Sum idea.</p><h3>Level 1 — Understand the Brute Force</h3><p>Given:</p><pre>nums = [2, 7, 11, 15]<br>target = 9</pre><p>Find the two indices whose values add up to 9.</p><p>First implement it using nested loops.</p><p>Focus on understanding:</p><pre>i<br>j<br>nums[i] + nums[j]</pre><h3>Level 2 — Identify the Complement</h3><p>For every number:</p><pre>complement = target - current</pre><p>Try manually calculating the complement for:</p><pre>nums = [2, 7, 11, 15]<br>target = 9</pre><p>Create a table:</p><p>CurrentComplement2?7?11?15?</p><h3>Level 3 — Implement Hashing</h3><p>Now implement Two Sum using a hash-based lookup.</p><p>Your goal is to achieve:</p><pre>O(n)</pre><p>average time.</p><p>Do not copy a solution.</p><p>Try to derive it from:</p><pre>complement = target - current</pre><h3>21. LeetCode Practice Set</h3><p>The roadmap intentionally progresses from basic array operations toward more pattern-oriented problems.</p><h3>Easy — Start Here</h3><h3>1. Two Sum</h3><p><strong>Pattern:</strong> Hashing</p><p><strong>What it teaches:</strong> Complement lookup and storing previously seen information.</p><p><a href="https://leetcode.com/problems/two-sum/?utm_source=chatgpt.com">Solve Two Sum on LeetCode</a></p><h3>2. Remove Element</h3><p><strong>Pattern:</strong> Array Traversal / In-place Array Manipulation</p><p><strong>What it teaches:</strong> Traversing an array while modifying its effective contents.</p><p><a href="https://leetcode.com/problems/remove-element/?utm_source=chatgpt.com">Solve Remove Element on LeetCode</a></p><h3>3. Remove Duplicates from Sorted Array</h3><p><strong>Pattern:</strong> Array Traversal → Two Pointers</p><p><strong>What it teaches:</strong> Using traversal to process a sorted array and prepare for the Two Pointer pattern.</p><p><a href="https://leetcode.com/problems/remove-duplicates-from-sorted-array/?utm_source=chatgpt.com">Solve Remove Duplicates from Sorted Array on LeetCode</a></p><h3>4. Contains Duplicate</h3><p><strong>Pattern:</strong> Hashing</p><p><strong>What it teaches:</strong> Detecting whether previously seen information exists.</p><p><a href="https://leetcode.com/problems/contains-duplicate/?utm_source=chatgpt.com">Solve Contains Duplicate on LeetCode</a></p><h3>5. Majority Element</h3><p><strong>Pattern:</strong> Frequency Counting</p><p><strong>What it teaches:</strong> Tracking information about repeated values.</p><p><a href="https://leetcode.com/problems/majority-element/?utm_source=chatgpt.com">Solve Majority Element on LeetCode</a></p><h3>22. What You Should Implement Yourself</h3><p>Before reading any solution walkthrough, make sure you can implement these from scratch:</p><pre>✓ Array traversal<br>✓ Find maximum<br>✓ Find minimum<br>✓ Calculate sum<br>✓ Count elements satisfying a condition<br>✓ Linear search<br>✓ Two Sum — brute force<br>✓ Two Sum — hashing<br>✓ Remove Element<br>✓ Remove Duplicates from Sorted Array<br>✓ Contains Duplicate</pre><p>The goal is not to solve these once.</p><p>The goal is to reach the point where you can look at the problem and immediately think:</p><pre>&quot;What information do I need?&quot;<br>        ↓<br>&quot;What pattern is this?&quot;<br>        ↓<br>&quot;What data structure helps?&quot;<br>        ↓<br>&quot;What is the time complexity?&quot;</pre><h3>23. Pattern Connection</h3><p>Two Sum is especially important because it introduces a pattern that will appear again later.</p><p>The roadmap maps:</p><pre>Hashing<br>   ↓<br>Two Sum<br>Contains Duplicate<br>Happy Number<br>Longest Consecutive Sequence<br>...</pre><p>It also identifies <strong>Two Sum</strong> under the HashMap topic and later introduces dedicated Two Pointer problems such as <strong>Two Sum II</strong> and <strong>3Sum</strong>.</p><p>So don’t think of Two Sum as just one LeetCode question.</p><p>Think of it as your first introduction to a larger problem-solving pattern:</p><blockquote><strong><em>Can previously seen information help me avoid repeated searching?</em></strong></blockquote><h3>24. Summary</h3><p>Today we covered the foundation of array problem solving.</p><h3>Arrays</h3><ul><li>Store multiple values in a sequence.</li><li>Elements are accessed using indices.</li><li>Traversal means visiting elements one by one.</li></ul><h3>Basic Traversal</h3><p>The basic pattern is:</p><pre>Traverse<br>   ↓<br>Inspect<br>   ↓<br>Update</pre><p>Typical complexity:</p><pre>Time:  O(n)<br>Space: O(1)</pre><h3>Two Sum</h3><p>The important observation is:</p><pre>complement = target - current</pre><p>Instead of repeatedly searching for the complement, we can store previously seen values.</p><p>This introduces the <strong>Hashing pattern</strong>:</p><pre>Traverse<br>   ↓<br>Calculate required information<br>   ↓<br>Check previously seen data<br>   ↓<br>Store current information</pre><p>The key interview lesson is:</p><blockquote><strong><em>Don’t just ask whether your solution works. Ask whether you are repeating work that a data structure could eliminate.</em></strong></blockquote><h3>Homework</h3><p>Before reading Part 2, solve these without looking at solutions:</p><ol><li>Two Sum — brute force</li><li>Two Sum — hashing</li><li>Remove Element</li><li>Remove Duplicates from Sorted Array</li><li>Contains Duplicate</li><li>Majority Element</li></ol><p>For each problem, write down:</p><pre>1. Brute-force idea<br>2. Pattern<br>3. Optimal approach<br>4. Time complexity<br>5. Space complexity<br>6. Edge cases</pre><p>Don’t worry about solving everything perfectly.</p><p>The objective is to train <strong>problem recognition</strong>.</p><h3>What’s Next?</h3><p>In <strong>Part 2</strong>, we will take the problems introduced here and walk through their solutions step by step.</p><p>For each problem, we will cover:</p><pre>Problem<br>   ↓<br>Initial Thought Process<br>   ↓<br>Brute Force<br>   ↓<br>Better Approach<br>   ↓<br>Optimal Approach<br>   ↓<br>Code<br>   ↓<br>Dry Run<br>   ↓<br>Complexity<br>   ↓<br>Interview Tips</pre><p>The goal is not simply to know the answer.</p><p>It is to understand <strong>how to arrive at the answer during an interview</strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec3aa3d40868" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript Numbers Explained: Math, Precision, and BigInt with Simple Examples (Day — 9)]]></title>
            <link>https://medium.com/@tuhinkairi/javascript-numbers-explained-math-precision-and-bigint-with-simple-examples-day-9-0dec4bf45419?source=rss-486354359cd2------2</link>
            <guid isPermaLink="false">https://medium.com/p/0dec4bf45419</guid>
            <category><![CDATA[learn-javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Tuhin Kairi]]></dc:creator>
            <pubDate>Sun, 09 Aug 2026 08:35:38 GMT</pubDate>
            <atom:updated>2026-08-09T08:35:38.542Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1JG5pZNBxQ8TLuZrG4-41g.png" /></figure><p><em>Learn JavaScript Numbers, the Math object, floating-point precision, safe integers, and BigInt with simple examples. A beginner-friendly guide to understanding numbers in JavaScript.</em></p><p><strong>Welcome to Day 9 of my JavaScript for Beginners series!</strong></p><p>In the previous session, we explored <strong>Strings</strong> and their operations. Today, we’re shifting gears to another fundamental data type in JavaScript — <strong>Numbers</strong>.</p><p>Numbers are everywhere in programming — from calculating prices and scores to handling percentages, measurements, IDs, and large values.</p><p>But JavaScript numbers have a few important concepts that every developer should understand:</p><ul><li>Numbers</li><li>The Math object</li><li>Number precision</li><li>BigInt</li></ul><p>Let’s understand each one with simple examples.</p><h3>1. Numbers in JavaScript</h3><p>In JavaScript, the Number type is used to represent both <strong>integers and floating-point numbers</strong>.</p><pre>let age = 25;<br>let price = 499.99;<br>let temperature = -10;</pre><pre>console.log(age);<br>console.log(price);<br>console.log(temperature);</pre><p>JavaScript does not have separate int and float types like some other programming languages.</p><p>All of these are Number values:</p><pre>let a = 10;       // Integer<br>let b = 10.5;     // Decimal<br>let c = -20;      // Negative number<br>let d = 0;        // Zero</pre><p>You can check the type using typeof:</p><pre>console.log(typeof 100);<br>// &quot;number&quot;</pre><pre>console.log(typeof 10.5);<br>// &quot;number&quot;</pre><h3>Special Number Values</h3><p>JavaScript also has some special numeric values.</p><pre>console.log(Infinity);<br>console.log(-Infinity);<br>console.log(NaN);</pre><h3>Infinity</h3><p>Infinity represents a value greater than the largest finite number.</p><pre>console.log(10 / 0);<br>// Infinity</pre><h3>NaN</h3><p>NaN means <strong>Not a Number</strong>.</p><p>It usually appears when a mathematical operation cannot produce a meaningful numeric result.</p><pre>console.log(&quot;hello&quot; * 5);<br>// NaN</pre><p>You can check whether a value is NaN:</p><pre>console.log(Number.isNaN(NaN));<br>// true</pre><h3>2. The Math Object</h3><p>JavaScript provides the built-in <strong>Math object</strong> for performing common mathematical operations.</p><p>You don’t need to create a Math object.</p><p>You can directly use its methods and properties.</p><h3>Math.round()</h3><p>Rounds a number to the nearest integer.</p><pre>console.log(Math.round(4.4));<br>// 4</pre><pre>console.log(Math.round(4.6));<br>// 5</pre><h3>Math.floor()</h3><p>Rounds a number <strong>down</strong>.</p><pre>console.log(Math.floor(4.9));<br>// 4</pre><p>For negative numbers, remember that “down” means toward negative infinity:</p><pre>console.log(Math.floor(-4.2));<br>// -5</pre><h3>Math.ceil()</h3><p>Rounds a number <strong>up</strong>.</p><pre>console.log(Math.ceil(4.1));<br>// 5</pre><h3>Math.trunc()</h3><p>Removes the decimal part without rounding.</p><pre>console.log(Math.trunc(4.9));<br>// 4</pre><pre>console.log(Math.trunc(-4.9));<br>// -4</pre><h3>Quick Difference</h3><pre>Math.round(4.6) → 5<br>Math.floor(4.6) → 4<br>Math.ceil(4.1)  → 5<br>Math.trunc(4.9) → 4</pre><h3>Math.max() and Math.min()</h3><p>Find the largest or smallest value.</p><pre>console.log(Math.max(10, 20, 5));<br>// 20</pre><pre>console.log(Math.min(10, 20, 5));<br>// 5</pre><h3>Math.abs()</h3><p>Returns the absolute value.</p><pre>console.log(Math.abs(-25));<br>// 25</pre><pre>console.log(Math.abs(25));<br>// 25</pre><h3>Math.pow()</h3><p>Calculates a number raised to a power.</p><pre>console.log(Math.pow(2, 3));<br>// 8</pre><p>You can also use the exponentiation operator:</p><pre>console.log(2 ** 3);<br>// 8</pre><h3>Math.sqrt()</h3><p>Returns the square root.</p><pre>console.log(Math.sqrt(25));<br>// 5</pre><h3>Math.random()</h3><p>Generates a random number between 0 and 1.</p><pre>console.log(Math.random());</pre><p>The result can be:</p><pre>0.1234<br>0.7856<br>0.4567</pre><p>But it will always be:</p><pre>0 &lt;= value &lt; 1</pre><h3>Generate a Random Integer</h3><p>For example, to generate a number from 1 to 10:</p><pre>let randomNumber = Math.floor(Math.random() * 10) + 1;</pre><pre>console.log(randomNumber);</pre><h3>3. Number Precision in JavaScript</h3><p>This is one of the most important things to understand about JavaScript numbers.</p><p>JavaScript uses the <strong>IEEE 754 double-precision floating-point format</strong> to represent Number values.</p><p>Because of this, some decimal calculations can produce unexpected results.</p><p>For example:</p><pre>console.log(0.1 + 0.2);<br>// 0.30000000000000004</pre><p>You might expect:</p><pre>0.3</pre><p>But JavaScript returns:</p><pre>0.30000000000000004</pre><p>Why?</p><p>Because numbers such as 0.1 and 0.2 cannot always be represented exactly in binary floating-point format.</p><p>This is not a JavaScript-only problem. It is a limitation of floating-point representation.</p><h3>Solving Decimal Precision Issues</h3><p>For simple calculations, you can control the number of decimal places using toFixed().</p><pre>let result = 0.1 + 0.2;</pre><pre>console.log(result.toFixed(2));<br>// &quot;0.30&quot;</pre><pre>let x = 3.14159;</pre><pre>console.log(x.toFixed(2)); // &quot;3.14&quot;<br>console.log(x.toFixed(0)); // &quot;3&quot;<br>console.log(x.toFixed(4)); // &quot;3.1416&quot;</pre><p>Notice something important:</p><p>toFixed() returns a <strong>string</strong>, not a number.</p><pre>console.log(typeof result.toFixed(2));<br>// &quot;string&quot;</pre><p>If you need a number:</p><pre>let fixedResult = Number(result.toFixed(2));</pre><pre>console.log(fixedResult);<br>// 0.3</pre><p>For financial or highly precise calculations, relying on floating-point Number arithmetic without proper handling can be risky.</p><h3>4. Safe Integers</h3><p>JavaScript can safely represent integers only within a specific range.</p><p>The maximum safe integer is:</p><pre>console.log(Number.MAX_SAFE_INTEGER);<br>// 9007199254740991</pre><p>The minimum safe integer is:</p><pre>console.log(Number.MIN_SAFE_INTEGER);<br>// -9007199254740991</pre><p>Numbers beyond this range can lose integer precision.</p><p>For example:</p><pre>console.log(9007199254740991 + 1);<br>// 9007199254740992</pre><p>But:</p><pre>console.log(9007199254740991 + 2);<br>// 9007199254740992</pre><p>The result is surprising because the Number type cannot represent every integer beyond its safe range exactly.</p><p>You can check whether an integer is safe:</p><pre>console.log(Number.isSafeInteger(100));<br>// true</pre><pre>console.log(Number.isSafeInteger(9007199254740992));<br>// false</pre><p>This is where <strong>BigInt</strong> becomes useful.</p><h3>5. BigInt in JavaScript</h3><p>BigInt is a JavaScript primitive type designed to represent <strong>integers larger than the safe </strong><strong>Number range</strong>.</p><p>You create a BigInt by adding n at the end of an integer.</p><pre>let bigNumber = 9007199254740993n;</pre><pre>console.log(bigNumber);</pre><p>The n tells JavaScript:</p><blockquote><em>This is a BigInt.</em></blockquote><p>You can also use the BigInt() function:</p><pre>let number = BigInt(&quot;9007199254740993&quot;);<br><br>console.log(number);</pre><h3>BigInt Arithmetic</h3><p>BigInt supports common arithmetic operations:</p><pre>let a = 10000000000000000n;<br>let b = 20000000000000000n;</pre><pre>console.log(a + b);<br>console.log(a - b);<br>console.log(a * b);<br>console.log(a / b);</pre><p>However, there is one important rule.</p><h3>You Cannot Mix Number and BigInt</h3><p>This will cause an error:</p><pre>let a = 10;<br>let b = 20n;</pre><pre>console.log(a + b);</pre><p>You need to explicitly convert them.</p><pre>let a = 10;<br>let b = 20n;</pre><pre>console.log(BigInt(a) + b);<br>// 30n</pre><p>Or convert the BigInt to a Number when it is safe to do so:</p><pre>console.log(Number(b));<br>// 20</pre><p>Be careful when converting very large BigInts to Number, because precision can be lost.</p><h3>Number vs BigInt</h3><p>A simple way to remember the difference:</p><pre>Number<br>→ Regular integers and decimals<br>→ Supports floating-point values<br>→ Safe integer range is limited</pre><pre>BigInt<br>→ Very large integers<br>→ No decimal values<br>→ Can represent integers beyond Number&#39;s safe range</pre><p>Example:</p><pre>let normalNumber = 100;<br>let largeInteger = 100000000000000000000n;</pre><h3>When Should You Use BigInt?</h3><p>You usually don’t need BigInt for normal calculations.</p><p>Use it when your application needs <strong>very large integer values</strong>, such as:</p><ul><li>Large counters</li><li>Cryptographic calculations</li><li>Very large IDs</li><li>Financial or scientific integer calculations</li><li>Applications dealing with values beyond Number.MAX_SAFE_INTEGER</li></ul><p>For ordinary values like:</p><pre>let age = 25;<br>let price = 499.99;<br>let score = 95;</pre><p>Number is the right choice.</p><h3>Quick Summary</h3><pre>Number<br>→ JavaScript&#39;s standard numeric type<br><br>Math<br>→ Provides useful mathematical methods<br><br>Math.round()<br>→ Round to nearest integer<br><br>Math.floor()<br>→ Round down<br><br>Math.ceil()<br>→ Round up<br><br>Math.trunc()<br>→ Remove decimal part<br><br>Math.random()<br>→ Generate random numbers<br><br>Precision<br>→ Floating-point calculations can have small inaccuracies<br><br>Number.MAX_SAFE_INTEGER<br>→ 9007199254740991<br><br>BigInt<br>→ Used for very large integers<br><br>BigInt ends with:<br>→ n</pre><h3>Final Thoughts</h3><p>Understanding JavaScript numbers is more than knowing how to perform addition and subtraction.</p><p>As you build real-world applications, you’ll eventually encounter <strong>rounding, floating-point precision, safe integers, and very large numbers</strong>.</p><p>The key things to remember are:</p><p><strong>Use </strong><strong>Number for normal numeric operations.</strong></p><p><strong>Use </strong><strong>Math for common mathematical operations.</strong></p><p><strong>Be careful with floating-point precision.</strong></p><p><strong>Use </strong><strong>BigInt when working with integers larger than the safe </strong><strong>Number range.</strong></p><p>In the next part of this JavaScript series, we’ll continue building the fundamentals step by step.</p><p>If you’re learning JavaScript from scratch, follow the series and build your fundamentals one concept at a time.</p><ol><li><strong><em>Follow the series 👉🏻</em></strong><em> — </em><a href="https://medium.com/@tuhinkairi/list/js-tutorial-beginner-to-advanced-b66cdf33a203">https://medium.com/@tuhinkairi/list/js-tutorial-beginner-to-advanced-b66cdf33a203</a></li><li><strong><em>Learn about JavaScript Stings and Its Operations (previous)</em> </strong>— <a href="https://medium.com/@tuhinkairi/javascript-strings-explained-string-methods-operations-day-8-9fbaa0cbb732?sharedUserId=tuhinkairi">https://medium.com/@tuhinkairi/javascript-strings-explained-string-methods-operations-day-8-9fbaa0cbb732?sharedUserId=tuhinkairi</a></li></ol><p>if you really like my efforts kindly give a <strong>Clap </strong>and do <strong>follow </strong>me. <strong>Happy coding ❤️🫰🏻</strong></p><h3>SEO Keywords</h3><p><em>JavaScript Numbers, JavaScript Math, JavaScript BigInt, JavaScript Number Precision, JavaScript Number Methods, JavaScript Math Methods, Number.MAX_SAFE_INTEGER, JavaScript BigInt vs Number, JavaScript for Beginners, Learn JavaScript, JavaScript Tutorial</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0dec4bf45419" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>