<?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 Rahul Kumar on Medium]]></title>
        <description><![CDATA[Stories by Rahul Kumar on Medium]]></description>
        <link>https://medium.com/@rahul319sinha?source=rss-500522a24a92------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*zGKQzj4ya8QfZdrOmAYzsg.jpeg</url>
            <title>Stories by Rahul Kumar on Medium</title>
            <link>https://medium.com/@rahul319sinha?source=rss-500522a24a92------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 12:49:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rahul319sinha/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[Closures Explained with Tricky Interview Questions For frontend Interview]]></title>
            <link>https://rahul319sinha.medium.com/closures-explained-with-tricky-interview-questions-825a11ff61d6?source=rss-500522a24a92------2</link>
            <guid isPermaLink="false">https://medium.com/p/825a11ff61d6</guid>
            <category><![CDATA[javascript-development]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Rahul Kumar]]></dc:creator>
            <pubDate>Mon, 02 Nov 2026 11:05:15 GMT</pubDate>
            <atom:updated>2026-11-02T11:05:54.964Z</atom:updated>
            <content:encoded><![CDATA[<p>#5: Javascript Interview Series</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/749/1*z-av-2QiMNPqevNQRgU8fA.png" /></figure><h4>What is Closure?</h4><p>→ A closure is a function that remembers variables from its outer scope even after outer function has finished execution.</p><p>or</p><p>Closure ek function hota hai jo apne outer scope ke variables ko yaad rakhta hai, chahe outer function execute hokar complete hi kyu na ho gaya ho.</p><p><strong>Example:</strong></p><pre>function outer(){<br>    let a = 10;<br>    function inner(){<br>      console.log(a);<br>     }<br>  return inner;<br>}<br><br>const fn = outer();<br><br>fn();</pre><p><strong>Output:</strong></p><p>outer() has been executed, still inner function remembers the ‘a’ variable.</p><pre>10</pre><h4>Why Closures are created?</h4><p>→ Javascript automatically creates closure when:</p><ul><li>A function is defined inside another function</li><li>The inner function references variables from its <strong>lexical (outer) scope.</strong></li><li>The inner function is executed outside <strong>its parent function.</strong></li></ul><p>To preserve variables after outer function execution.</p><h4>How closures work internally?</h4><p>Let’s understand by example:</p><pre>function outer() {<br>    let count = 0;<br><br>    return function() {<br>        count++;<br>        console.log(count);<br>    };<br>}<br><br>const counter = outer();<br>counter(); // 1<br>counter(); // 2</pre><p>Internally javascript will preserve:</p><p><strong>Function + Lexical Environment</strong></p><p>Means here in example: <strong>function() + Outer Scope (count = 0)</strong>. Basically it <strong>will take reference of count</strong> variable not value.<br>so, If you will call again that counter function then it will give output as updated one.</p><h3>Closures with setTimeout</h3><p>Example:</p><pre>function demo() {<br>    let name = &quot;Rahul&quot;;<br><br>    setTimeout(() =&gt; {<br>        console.log(name);<br>    }, 1000);<br>}<br><br>demo();</pre><p>Here is the exact step-by-step breakdown of what happens under the hood:</p><ol><li><strong>Call Stack Execution</strong>: When demo() is invoked, it is pushed onto the <strong>Call Stack</strong>. The variable name is allocated in the local memory space of demo().</li><li><strong>Web API Hand-off</strong>: The engine encounters setTimeout. Because setTimeout is a Web API feature provided by the browser environment (not native to the JS engine core), JavaScript hands the callback function and the 1000ms timer over to the browser environment and immediately moves to the next line.</li><li><strong>Function Completion</strong>: demo() finishes executing and is popped off the Call Stack. At this point, the local execution context of demo() is technically gone.</li><li><strong>The Task Queue</strong>: After 1000ms, the browser moves the callback function () =&gt; { console.log(name); } into the <strong>Callback Queue</strong> (or Task Queue).</li><li><strong>The Event Loop</strong>: The Event Loop constantly checks if the Call Stack is empty. Since demo() is finished and the stack is clear, the Event Loop pushes the callback onto the Call Stack for execution.</li><li><strong>The Closure Magic</strong>: When the callback finally runs, it needs the name variable. Even though demo() finished long ago, the callback preserves a <strong>closure </strong>a reference to its outer lexical scope. This prevents the name variable from being garbage collected, allowing &#39;Rahul&#39; to be successfully printed.</li></ol><h4>Closures in Loops:</h4><p>Example 1:</p><pre>for(var i = 1; i &lt;= 3; i++) {<br>    setTimeout(() =&gt; {<br>        console.log(i);<br>    }, 1000);<br>}</pre><p>Output:</p><pre>4<br>4<br>4</pre><p>Why?</p><p>Var is function scope so i will be shared for all, once loops will finished executing, then each iteration setTimeout will be called, that time setTimeOut is having reference of ‘i’, then that time i becomes 4 for all. so it will print 4 4 4.</p><p><strong>Example 2.</strong></p><p>We can solve above issue by using closure:</p><pre>for(var i = 1; i &lt;= 3; i++) {<br>    function demo(x){<br>    setTimeout(() =&gt; {<br>        console.log(x);<br>    }, 1000);<br>  }<br>  demo(i);<br>}</pre><p>Now, for each iteration in demo function we are passing variable that variable will preserve, so it will print 1 2 3.</p><p><strong>Example 3:</strong></p><pre>for(let i = 1; i &lt;= 3; i++) {<br>    setTimeout(() =&gt; {<br>        console.log(i);<br>    }, 1000);<br>}</pre><p><strong>Output:</strong></p><pre>1<br>2<br>3</pre><p><strong>Why?</strong></p><p>let is block scope, let keyword creates a <strong>new, distinct instance</strong> of the variable i for every single iteration of the loop. so it will give output as 1 2 3.</p><h4>Real-world usecase of closures:</h4><ol><li>Data Hiding / Private variables</li><li>Counter</li><li>Memoization</li><li>Debouncing</li></ol><p>Let’s understand one by one, by some example:</p><h4>Data Hiding/ Private Variables:</h4><p>Imagine a bank account, you dont anyone can see and change your bank balance:</p><pre>const account = {<br>    balance: 1000<br>};<br><br>account.balance = 1000000;<br><br>console.log(account.balance);</pre><p>Output:</p><pre>1000000</pre><p>its totally unsafe.</p><p>By using closure:</p><pre>function createAccount() {<br><br>    let balance = 1000;<br><br>    return {<br>        deposit(amount) {<br>            balance += amount;<br>        },<br><br>        withdraw(amount) {<br>            balance -= amount;<br>        },<br><br>        getBalance() {<br>            return balance;<br>        }<br>    };<br>}<br><br>const account = createAccount();<br><br>console.log(account.getBalance());<br><br>account.deposit(500);<br><br>console.log(account.getBalance());<br><br>account.withdraw(200);<br><br>console.log(account.getBalance());<br><br>console.log(account.balance);</pre><p>Output:</p><pre>1000<br>1500<br>1300<br>undefined</pre><p>Now, here balance variable won’t get expose directly, You can access through closure only,</p><pre>desposit()<br>withdraw()<br>getBalance()</pre><h4>Counter:</h4><pre><br>function counter(){<br>  let count = 0;<br>    return function(){<br>      count++;<br>      return count;<br>    }<br>}<br><br>const c = counter();<br>console.log(c()); // 1<br>console.log(c()); // 2<br>console.log(c()); // 3</pre><p>Output:</p><pre>1<br>2<br>3</pre><p>Here, Closure preserve the state of count variable.</p><h4>3. Memoization</h4><pre>function memoize(){<br>  const cache = {};<br><br>  return function(num){<br>     if(cache[num]){<br>        console.log(&quot;From cache&quot;);<br>        return cache[num];<br>      }<br><br>    console.log(&quot;calculating...&quot;);<br>    cache[num] = num*num;<br>    return cache[num];<br>  }<br>}<br><br><br>const square = memoize();<br><br>console.log(square(5));<br>console.log(square(5));<br>console.log(square(5));</pre><p>Output:</p><pre>Calculating<br>25<br><br>From Cache<br>25<br><br>From Cache<br>25</pre><p>Why?</p><p>Closure perserve cache variable here.</p><h4>4. Debouncing:</h4><p>there is usecase whenever user is typing in seach box that time on each keypress api is getting called so we can reduce api call using debouncing:</p><pre><br>r             <br>ra<br>rah<br>rahu<br>rahul </pre><p>For each one api is getting called.</p><p>Let’s see how to resolve this issue:</p><pre>function debounce(fn, delay){<br>  let timer;<br>  return function(){<br>    clearTimeout(timer);<br>    timer = setTimeout(() =&gt; { <br>        fn();<br>     }, delay);<br>  };<br>}<br><br><br>const search = debounce(()=&gt;{<br>  console.log(&quot;API Call&quot;);<br>},1000);<br><br>search(); // this is like keypress<br>search(); // this is like keypress<br>search();  // this is like keypress<br>search();  // this is like keypress</pre><p>Output:<br>after 1 second:</p><pre>API call</pre><p>timer will reset in each call.</p><h3>Thanks…</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=825a11ff61d6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Temporal Dead Zone(TDZ), How it behaves in different scope, From Basics to Advanced Interview…]]></title>
            <link>https://rahul319sinha.medium.com/temporal-dead-zone-tdz-how-it-behaves-in-different-scope-from-basics-to-advanced-interview-8c55c733dddb?source=rss-500522a24a92------2</link>
            <guid isPermaLink="false">https://medium.com/p/8c55c733dddb</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[javascript-development]]></category>
            <category><![CDATA[reactjs]]></category>
            <dc:creator><![CDATA[Rahul Kumar]]></dc:creator>
            <pubDate>Mon, 26 Oct 2026 07:39:19 GMT</pubDate>
            <atom:updated>2026-10-26T07:40:19.166Z</atom:updated>
            <content:encoded><![CDATA[<h3>Temporal Dead Zone(TDZ), How it behaves in different scope, From Basics to Advanced Interview Questions</h3><p>#4</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/819/0*S4v1vz9QAHY-4IUJ.png" /></figure><h4>What is TDZ?</h4><p>→ <strong>Time Period </strong>between when a<strong> variable is hoisted</strong> and <strong>when it is initalized</strong>. If you try to access during this period, it will give you <strong>ReferenceError.</strong></p><p>or</p><p>TDZ woh time period hai jab variable memory mein to create ho chuka hota hai, lekin initialize nahi hua hota. Is duration mein variable access karne par ReferenceError aata hai.</p><p><strong>Example:</strong></p><pre>console.log(age);<br><br>let age = 25;</pre><p>Output:</p><pre>ReferenceError</pre><h4>Why Does TDZ Exist?</h4><p>→ TDZ exists to <strong>prevental accidental access </strong>to variables before they are intialized, making code safer and less error-prone. specially for let and const.</p><h4>Difference between TDZ vs Hoisting?</h4><p>Let’s understand by example:</p><pre>console.log(a);<br>let a = 10;</pre><p>Here, it is happening like this:</p><p><strong>let </strong>is <strong>getting hoisted</strong> but it remains in <strong>TDZ</strong>.</p><p>In Memory Phase:</p><pre>a : &lt;uninitialized&gt;</pre><p>that’s why it will give <strong>ReferenceError.</strong></p><h4>How TDZ will behave in difference scope:</h4><h4>1. Block Scope:</h4><pre><br>{<br>    console.log(city);<br><br>    let city = &quot;Pune&quot;;<br>}</pre><p>Output:</p><pre>ReferenceError</pre><h4>2. Functions:</h4><pre>function test() {<br>    console.log(a);<br><br>    let a = 10;<br>}<br><br>test();</pre><p>Output:</p><pre>ReferenceError</pre><p>test will create own function execution context, there a will be uninitialized.</p><h4>3. In Function with Default Parameters:</h4><pre><br>function test(a = b, b = 10) {<br>    console.log(a, b);<br>}<br><br>test();</pre><p>Here, Parameter evaluation happens from left to right.<br>In a = b, here, b is not initialized so it will be give reference error.</p><p><strong>Valid example of above:</strong></p><pre>function test( b = 10, a = b) {<br>    console.log(a, b);<br>}<br><br>test();</pre><p>Output:</p><pre>10 10</pre><p>Practice Example:</p><p>Example 1:</p><pre>let a = 10;<br><br>{<br>    console.log(a);<br><br>    let a = 20;<br>}</pre><p><strong>Output:</strong></p><p>ReferenceError</p><p><strong>Reason:</strong></p><p>Because, In block scope there is already a but it is not initialize at time of accessing it.</p><p><strong>Example 2:</strong></p><pre>let a = 5;<br><br>function test() {<br>    console.log(a);<br><br>    {<br>        let a = 10;<br>    }<br>}<br><br>test();</pre><p><strong>Output:</strong></p><pre>5</pre><p><strong>Reason:<br>In that scope, it wont find a so it will go global scope.</strong></p><p><strong>Example 3:</strong></p><pre>let x = 1;<br><br>function test(x = x) {<br>    console.log(x);<br>}<br><br>test();</pre><p>Output:</p><pre>ReferenceError</pre><p>Parameter tries to read itself while still in TDZ.</p><p>Thanks…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c55c733dddb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript Hoisting, TDZ & Variable Shadowing: The Most Asked Frontend Interview Topic]]></title>
            <link>https://rahul319sinha.medium.com/javascript-hoisting-tdz-variable-shadowing-the-most-asked-frontend-interview-topic-1d13a7c20b92?source=rss-500522a24a92------2</link>
            <guid isPermaLink="false">https://medium.com/p/1d13a7c20b92</guid>
            <category><![CDATA[javascript-development]]></category>
            <category><![CDATA[frontend-development]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[javascript-interview]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Rahul Kumar]]></dc:creator>
            <pubDate>Fri, 23 Oct 2026 11:34:09 GMT</pubDate>
            <atom:updated>2026-10-23T11:34:09.169Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>JavaScript Interview Series #3</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/819/0*fv15otePH7atcruZ.png" /></figure><h4>What is Hoisting?</h4><p>→ Hoisting is nothing but In memory creation phase, Javascript allocates memory to variables and functions, Thats why it is getting moved to top of their scope.</p><p>or <br><strong>Hoisting is JavaScript’s behavior of moving variable and function declarations to the top of their scope during the memory creation phase.</strong></p><p>or</p><p>Hoisting ka matlab hai JavaScript execution se pehle variables aur functions ke liye memory allocate karta hai. Is wajah se lagta hai ki declarations upar move ho gayi hain.</p><h4>How <strong>hoisting</strong> actually works under the hood?</h4><p>When your JavaScript code runs, the engine creates an Execution Context in two distinct phases:</p><p><strong>Memory Creation Phase (Compile Phase):</strong></p><ul><li>The engine scans your code line by line.</li><li>It finds all variable and function declarations.</li><li><strong>Functions:</strong> The engine stores the entire function definition directly in memory.</li><li><strong>var variables:</strong> The engine reserves space for the variable and initializes it with the value undefined.</li><li><strong>let and </strong><strong>const variables:</strong> The engine reserves space for them too, but leaves them <strong>uninitialized</strong> (placing them in the Temporal Dead Zone until their actual line of code runs).</li></ul><p><strong>Execution Phase:</strong></p><ul><li>The engine executes the code line by line, assigning actual values to variables and executing functions.</li></ul><p>Because the memory is already allocated <em>before</em> a single line of code executes, you can reference a function or a var variable earlier in the script without the engine crashing making it <em>appear</em> as though they were dragged to the top of the file.</p><p>Example:</p><pre>console.log(a);<br>getName();<br>var a = 10;<br><br>function getName(){<br>  console.log(&quot;Raju&quot;);<br>}</pre><p><strong>Output:</strong></p><pre>undefined<br>Raju</pre><p><strong>What exactly happened under the hood:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/643/1*ckE3wqHquoJ6ZctyVCKEPA.png" /></figure><p>Before javascript will start code execution line by line,</p><ul><li>In <strong>memory Creation phase,</strong> all the variables and functions got the memory.</li><li>After that execution started that’s on line 1. it will give <strong>undefined </strong>after that function will be called, then value will <strong>assigned </strong>to variable.</li></ul><p>One Question would be arose in your mind:</p><h4>Are let and const Hoisted?</h4><p>→ <strong>Yes</strong>, Both are getting <strong>Hoisted </strong>but We <strong>can’t access </strong>it <strong>before Initialization</strong>.</p><p>Example:</p><pre>console.log(a);<br><br>let a = 10;</pre><p>Output:</p><pre>ReferenceError: Cannot access &#39;a&#39; before initialization</pre><p>It’s same with const.</p><p>Now you were thinking like,</p><h4>Why in case of var we are getting undefined??</h4><p>→ In case of var, <strong>During Memory creation phase</strong>, variables declared using <strong>var </strong>are initialized with <strong>undefined</strong>.</p><h4>Let’s Understand, How functions are getting Hoisted ?</h4><p>In Function, <strong>Whole body of function </strong>is getting stored in memory during memory creation phase.</p><p><strong>If function:</strong></p><ul><li><strong>Normal function→ Whole body of function </strong>is getting stored in memory during memory creation phase.</li><li><strong>Functional expressions → </strong>It is getting hoisted like <strong>variables </strong>(<strong>var, </strong><strong>let, or </strong><strong>const) they are assigned to.</strong></li><li><strong>Arrow function → </strong>It is getting hoisted like <strong>variables </strong>(<strong>var, </strong><strong>let, or </strong><strong>const) they are assigned to.</strong></li></ul><p><strong><em>Let’s understand by Example:</em></strong></p><h4><strong>Normal Function:</strong></h4><p><strong>Example1:</strong></p><pre>greet(); // Output: &quot;Hello!&quot;<br><br>function greet() {<br>    console.log(&quot;Hello!&quot;);<br>}</pre><h4><strong>Functional expressions:</strong></h4><p><strong>Example 1: Using var</strong></p><pre>funcVar(); // TypeError: funcVar is not a function<br><br>var funcVar = function() {<br>    console.log(&quot;Using var&quot;);<br>};</pre><p><strong>Example 2: Using let/const</strong></p><pre>funcLet(); // ReferenceError: Cannot access &#39;funcLet&#39; before initialization<br><br>let funcLet = function() {<br>    console.log(&quot;Using let&quot;);<br>};</pre><p>The variable is hoisted but remains uninitialized in the <strong>Temporal Dead Zone (TDZ)</strong>. Accessing it before its definition throws a ReferenceError.</p><h4><strong>Arrow Functions:</strong></h4><p><strong>Example 1: Using var</strong></p><pre>arrowVar(); // TypeError: arrowVar is not a function<br><br>var arrowVar = () =&gt; {<br>    console.log(&quot;Arrow with var&quot;);<br>};</pre><p><strong>Example 2: Using let/const</strong></p><pre>arrowLet(); // ReferenceError: Cannot access &#39;arrowLet&#39; before initialization<br><br>let arrowLet = () =&gt; {<br>    console.log(&quot;Arrow with let&quot;);<br>};</pre><p>The variable is hoisted but remains uninitialized in the <strong>Temporal Dead Zone (TDZ)</strong>. Accessing it before its definition throws a ReferenceError.</p><p>I think you have heard so many times this term <strong>“Temporal Dead Zone”<br>Let’s Understand:</strong></p><h4>What is Temporal Dead Zone (TDZ)?</h4><p>→ The period between memory creation and initialization is called temporal dead Zone.</p><p><strong>Example:</strong></p><pre>console.log(age); // ReferenceError<br><br>let age = 25;</pre><p><strong>Memory Creation<br> ↓<br>TDZ<br> ↓<br>let age = 25</strong></p><h4>Some Tricky Questions:</h4><p><strong>Example 1:</strong></p><pre><br>console.log(a);<br><br>var a = 10;<br><br>function hello() {<br>    console.log(&quot;Hello&quot;);<br>}<br><br>console.log(a);</pre><p><strong>Output &amp; Reason:</strong></p><pre>undefined​‌<br>10</pre><p><strong>because in memory creation phase, a will be initilaized with undefined then in execution phase code will be executed line by line then value will be assigned then it will give output as 10.</strong></p><p><strong>Question 2.</strong></p><pre>console.log(a);<br><br>var a = 10;<br><br>function a() {<br>    console.log(&quot;Hello&quot;);<br>}<br><br>console.log(a);</pre><p><strong>Output</strong>:</p><pre>function a() { console.log(&quot;Hello&quot;); }<br>10</pre><p>Why answer like this, Because <strong>Function Declarations have higher priority than variable declaration in memory allocation phase.</strong></p><p><strong>Question 3:</strong></p><pre>var a = 1;<br><br>function test() {<br>    console.log(a);<br><br>    var a = 2;<br><br>    function a() {}<br><br>    console.log(a);<br>}<br><br>test();</pre><p>Output:</p><pre>function a() {}<br>2</pre><p>Why answer like this, Because <strong>Function Declarations have higher priority than variable declaration in memory allocation pha</strong></p><p><strong>Question 4.</strong></p><pre>console.log(a);<br><br>let a = 10;<br><br>console.log(a);</pre><p><strong>Output:</strong></p><pre>ReferenceError a cant be accessible before intialization</pre><p><strong>Memory Creation Phase<br> ↓<br>a is created<br> ↓<br>TDZ (Temporal Dead Zone)<br> ↓</strong></p><p><strong>let a = 10</strong></p><p><strong>Question 5.</strong></p><pre>console.log(hello);<br><br>var hello= function() {<br>    return &quot;Hello&quot;;<br>};<br><br>console.log(hello());</pre><p><strong>Output:</strong></p><pre>undefined<br>Hello</pre><p><strong>Reason:</strong></p><p>It will be hoisted as <strong>var </strong>variable first so for first console.log, it will give <strong>undefined</strong>, then value of variable will be assigned then function value will be printed.</p><p><strong>Question 6.</strong></p><pre>foo();<br><br>var foo = function() {<br>    console.log(&quot;Function Expression&quot;);<br>};<br><br>function foo() {<br>    console.log(&quot;Function Declaration&quot;);<br>}</pre><p><strong>Output:</strong></p><pre>Function Declaration</pre><p><strong>Reason:</strong></p><p>functional expression will be hoisted as <strong>var variable. then function will be hoisted then function declaration will prioritize so it will be give output as </strong>Function Declaration.</p><p><strong>Question 7.</strong></p><pre>var a = 10;<br><br>(function() {<br>    console.log(a);<br><br>    var a = 20;<br><br>    console.log(a);<br>})();<br><br>console.log(a);</pre><p>Output:</p><pre>undefined<br>20<br>10</pre><p>Question 8.</p><pre>function test() {<br>    console.log(a);<br><br>    var a = b = 10;<br>}<br><br>test();<br><br>console.log(typeof a);<br>console.log(typeof b);</pre><p>Output:</p><pre>undefined<br>undefined<br>number</pre><p>Reason:</p><pre>var a = b = 10;</pre><p>It means:</p><pre><br>b = 10;<br>var a = b;</pre><p>so js will behave <strong>b as global variable.</strong> because it is not declared as ler, var, or const.</p><p>*** Hoisting works with declarations only:</p><pre>var a;<br>let a;<br>const a;<br>function a(){}</pre><p><strong>Example 9.</strong></p><pre>function test() {<br>    console.log(a);<br><br>    a = 20;<br>}</pre><p><strong>Output:</strong></p><pre>ReferenceError: a is not defined</pre><p>Reason:</p><p><strong>variable is not exists.</strong></p><p><strong>Example 10.</strong></p><pre>var a = 10;<br>function test() {<br>    console.log(a);<br><br>    a = 20;<br>}<br><br>console.log(a);</pre><p><strong>Output:</strong></p><pre>10<br>20</pre><p><strong>Reason:</strong></p><p>Bacause of scope chain.</p><p>Like, First it will look in same scope in same scope it is not there then it will go to parent scope, it will found there, so it will give output 10 then 20.</p><h3>Thanks…</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1d13a7c20b92" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Scope, Scope Chain & Lexical Environment For Frontend Interview]]></title>
            <link>https://rahul319sinha.medium.com/mastering-scope-scope-chain-lexical-environment-for-frontend-interview-a19e3bcdee8d?source=rss-500522a24a92------2</link>
            <guid isPermaLink="false">https://medium.com/p/a19e3bcdee8d</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[javascript-development]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[frontend-development]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <dc:creator><![CDATA[Rahul Kumar]]></dc:creator>
            <pubDate>Thu, 22 Oct 2026 10:36:35 GMT</pubDate>
            <atom:updated>2026-10-23T11:41:58.298Z</atom:updated>
            <content:encoded><![CDATA[<p>#2</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RUf6z-koHyR-3c7o.png" /></figure><p>Let’s get started:</p><h4>What is Scope?</h4><p>→ <strong>Scope determines where a variable can be accessed in a program.</strong></p><p>or</p><p>Scope batata hai ki koi variable code ke kis area se access kiya ja sakta hai</p><p>Let’s understand by example:</p><pre>let city = &quot;Bangalore&quot;<br><br>function showCity(){<br>  console.log(city);<br>}</pre><p>city will be accessible inside function because it is in outer scope.</p><h4>Types of Scope in Javascript:</h4><ol><li>Global Scope</li><li>Function Scope</li><li>Block Scope</li></ol><p>Let’s understand one by one:</p><h4>Global Scope:</h4><p>A variable which is declared outside all the functions and blocks belongs to the global scope. It can be accessible everywhere.</p><p>or</p><p>Variable jo function and block ke bahar declare hota hai and generally har jagah access kr sakte hai.</p><p>Example:</p><pre>let name = &quot;Rahul&quot;<br><br>function getName(){<br>  console.log(name);<br>}<br><br>{<br>  console.log(name);<br>}</pre><h4>Function Scope:</h4><p>Variables declared with <strong>var inside a function</strong> are accessible only within that function.</p><p>or</p><p>Function ke andar declared variable bas function ke andar hi accessible hoga.</p><p>example:</p><pre>function test(){<br>  var age = 25;<br>  console.log(age);<br>}</pre><p><strong>Then one question would be coming in your mind:</strong></p><p>why not <strong>let </strong>and <strong>const</strong>?</p><p>Because in case of let and const, whenever we are declaring the variable with let/const then it is block scope.</p><h4>Block Scope:</h4><p>A <strong>block </strong>is a set of statements enclosed within {}.</p><p>Variables declared with <strong>let and </strong><strong>const </strong>are limited to the block in which they are defined.</p><p>example 1:</p><pre>{<br>   let name = &quot;Rahul&quot;;<br>}<br><br><br>if(true){<br>  let city = &quot;Pune&quot;;<br>}<br><br>console.log(city); // reference error</pre><p>example 2:</p><pre>function getName(){<br>  let name = &quot;Rahul&quot;;<br>  console.log(name);<br>}<br><br>console.log(name); // reference error</pre><p>Example 3:</p><pre>if (true) {<br>  let blockScoped = &quot;I am trapped inside this block&quot;;<br>  var functionScoped = &quot;I can escape the block&quot;;<br>}<br><br>console.log(functionScoped); // Logs: &quot;I can escape the block&quot;<br>console.log(blockScoped);    // ReferenceError: blockScoped is not defined</pre><p>Example 4:</p><pre>for (var i = 0; i &lt; 3; i++) {<br>    // executing...<br>}<br>console.log(i); // Logs: 3 (var leaked outside the loop!)<br><br>for (let j = 0; j &lt; 3; j++) {<br>    // executing...<br>}<br>console.log(j); // ReferenceError: j is not defined (let stayed inside the loop)</pre><h4>4. Module Scope:</h4><p>Module Scope is a scope created by <strong>JavaScript ES Module</strong>s (import / export) where variables are accessible only within that module unless <strong>explicitly exported</strong></p><p>or</p><p>Module Scope ka matlab hai ki kisi .js file ke andar jo variables/functions declare kiye gaye hain, woh sirf us file (module) ke andar accessible hote hain jab tak unhe export na kiya jaye.</p><p><strong>Why Module scope came in picture?</strong></p><p>→ Because previously, everything was getting attached to global scope.<br>like:</p><p>Example:</p><p>file1.js</p><pre>var user = &quot;Rahul&quot;</pre><p>file2.js</p><pre>console.log(user);  // give output as Rahul</pre><p><strong>Example With Module Scope:</strong></p><p>file1.js</p><pre>const user = &quot;Rahul&quot;;</pre><p>file2.js</p><pre>console.log(user); // give you refernce error</pre><h4>Example: with All the scope:</h4><p>Let’s see one example where all the scope would be there:</p><pre>// ==========================================<br>// 1. MODULE SCOPE<br>// If this file is treated as an ES module (e.g., script type=&quot;module&quot;),<br>// this variable is only accessible inside this file unless exported.<br>// ==========================================<br>const moduleVar = &quot;I am inside Module Scope&quot;;<br><br>// ==========================================<br>// 2. GLOBAL SCOPE<br>// Declared at the top level outside any module restriction or explicitly on the global object.<br>// Accessible from anywhere in your entire script.<br>// ==========================================<br>const globalVar = &quot;I am inside Global Scope&quot;;<br><br>function outerFunction() {<br>    // ==========================================<br>    // 3. FUNCTION (LOCAL) SCOPE<br>    // Accessible anywhere inside this function, but invisible outside of it.<br>    // ==========================================<br>    const functionVar = &quot;I am inside Function Scope&quot;;<br><br>    if (true) {<br>        // ==========================================<br>        // 4. BLOCK SCOPE<br>        // Declared with let/const inside curly braces {}.<br>        // Only accessible inside this specific &#39;if&#39; block.<br>        // ==========================================<br>        const blockVar = &quot;I am inside Block Scope&quot;;<br>         // --- Testing Access Inside the Block ---<br>        console.log(blockVar);    // ✅ Works: local to this block<br>        console.log(functionVar); // ✅ Works: parent function scope (Lexical Scope)<br>        console.log(globalVar);   // ✅ Works: parent global scope<br>        console.log(moduleVar);   // ✅ Works: parent module scope<br>    }<br> // --- Testing Access Outside the Block ---<br>    console.log(functionVar);     // ✅ Works<br>    // console.log(blockVar);     // ❌ ReferenceError: blockVar is not defined<br>}<br><br>outerFunction();<br>// --- Testing Access Outside the Function ---<br>console.log(globalVar);           // ✅ Works<br>// console.log(functionVar);      // ❌ ReferenceError: functionVar is not defined</pre><h4>What is Lexical Scope?</h4><p><strong>Lexical </strong>means <strong>“Where the code is physically present”</strong></p><p><strong>Lexical scope </strong>means <strong>variable accessibility </strong>is determined by where functions and variables are written in the source code.<br>or</p><p>“<strong>Lexical</strong>” ka matlab: <em>Code physically kahan likha gaya hai.</em></p><p>JavaScript variable access ko code ke location ke basis par decide karta hai.</p><p><strong>Example:</strong></p><pre>let name = &quot;Rohan&quot;;<br><br>function outer(){<br>  function inner(){<br>      console.log(name);<br>  }<br>  inner();<br>}<br><br>outer();</pre><p>Output:</p><pre>Rohan</pre><p>Why?</p><p>Because Inner() is written physically inside outer().<br><strong>Global → outer → inner</strong> (This is relationship that is called lexical scope).</p><h4>Scope Chain:</h4><p>A scope chain is the hierarchy of scopes JavaScript follows while looking for a variable.</p><p>Let’s understand by example:</p><pre><br>let city= &quot;Mumbai&quot;;<br><br>function outer() {<br><br>    let team = &quot;Frontend&quot;;<br><br>    function inner() {<br><br>        let name = &quot;Rahul&quot;;<br><br>        console.log(city);<br>    }<br><br>    inner();<br>}<br><br>outer();</pre><p><strong>How inner() will lookup for city:</strong></p><p>First it will check in current scope that is inner(). then It will look into outer() then it will look for global scope.</p><p><strong>inner<br> ↓<br>outer<br> ↓<br>global</strong></p><p><strong>so output:</strong></p><pre>Mumbai</pre><h4>How does javascript resolve variable lookup?</h4><p>JavaScript searches for a variable in the <strong>current scope first</strong>. If not found, it moves to the <strong>parent scope until it reaches the global scope.</strong></p><h4>What is Variable Shadowing?</h4><p>→ <br>Variable shadowing occurs when a variable in an inner scope has the same name as a variable in an outer scope.</p><p>Example:</p><pre>let city = &quot;Mumbai&quot;<br><br>function show(){<br>    let city = &quot;Pune&quot;;<br>    console.log(city);<br>}<br><br>show();<br>console.log(city);</pre><p>Why it is valid shadowing, because let is block scope whatever is declare it wont affect outside block let variable so answer is <strong>Pune</strong>. outer console log will print <strong>Mumbai</strong>.</p><p>Example 2:</p><pre>let city = &quot;Mumbai&quot;<br><br>function show(){<br>    var city = &quot;Pune&quot;;<br>    console.log(city);<br>}<br><br>show();<br>console.log(city);</pre><p>In this case, var is function scope and let is block scope then inner variable wont affect outer variable.</p><p>Example 3:</p><pre>var city = &quot;Mumbai&quot;<br><br>function show(){<br>    let city = &quot;Pune&quot;;<br>    console.log(city);<br>}<br><br>show();<br>console.log(city);</pre><p>It is also valid.</p><h4><strong>What is Illegal Shadowing?</strong></h4><p><strong>→ Illegal shadowing happens when JavaScript does not allow a variable declaration because it violates scope rules.</strong></p><p>Example:</p><pre>let  city = &quot;Mumbai&quot;<br><br>{<br>    var city = &quot;Pune&quot;;<br>    console.log(city);<br>}<br><br>console.log(city);</pre><p>This is illegal shadowing because var is function scope and in that scope city is already declared with let so let wont allow re-declaration of variable.</p><p>Example 2:</p><pre>var city = &quot;Mumbai&quot;<br><br>{<br>    let city = &quot;Pune&quot;;<br>    console.log(city);<br>}<br><br>console.log(city);</pre><p>This is valid because let is block level, it wont affect outer variable.</p><p>Example 3:</p><pre>let city = &quot;Mumbai&quot;<br><br>{<br>    let city = &quot;Pune&quot;;<br>    console.log(city);<br>}<br><br>console.log(city);</pre><p>This is also valid.</p><blockquote>Summary:</blockquote><blockquote><strong>Scope:</strong> Area where a variable is accessible.</blockquote><blockquote><strong>Lexical Scope: </strong>Scope determined by code location.</blockquote><blockquote><strong>Scope Chain: </strong>Path used for variable lookup.</blockquote><blockquote><strong>Variable Shadowing: </strong>Inner variable hides outer variable.</blockquote><blockquote><strong>Illegal Shadowing: </strong>A redeclaration that violates JavaScript scope rules.</blockquote><blockquote><strong>Global Scope: </strong>Accessible from anywhere.</blockquote><blockquote><strong>Module Scope: </strong>Accessible only within the module.</blockquote><p>Thanks…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a19e3bcdee8d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering JavaScript Execution Context and Call Stack for Frontend Interviews]]></title>
            <link>https://rahul319sinha.medium.com/mastering-javascript-execution-context-and-call-stack-for-frontend-interviews-ac212a1cb5e4?source=rss-500522a24a92------2</link>
            <guid isPermaLink="false">https://medium.com/p/ac212a1cb5e4</guid>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Rahul Kumar]]></dc:creator>
            <pubDate>Wed, 21 Oct 2026 12:02:25 GMT</pubDate>
            <atom:updated>2026-10-21T12:02:25.788Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/819/1*Ms2nIWEpjNr7Fnua_ZK21g.png" /></figure><h4><strong>What is execution Context?</strong></h4><p>→ <strong>Environment jahan JavaScript code execute hota hai.</strong></p><p>or</p><p><strong>→ Environment where JavaScript code is executed.</strong></p><p>Let’s understand by example:</p><p>Let’s say you are working in office, before begining your works company provides you:</p><ul><li>Table</li><li>Chair</li><li>Laptop</li><li>Access Card.</li></ul><p>As same, javascript creates Execution context before executing the code.</p><p><strong>Execution Context contains:</strong></p><ol><li>Memory Section</li><li>Code execution section</li></ol><p>Let’s understand by example:</p><pre>var a = 10;<br><br>function greet() {<br>    console.log(&quot;Hello&quot;);<br>}</pre><p>Firstly, JavaScript will allocate memory then will execute the code.(JS pehle memory allocate karega, fir code execute karega.)</p><p>Sabse pahle, Javascript kaise run hota hai?</p><p><strong>jab tum code likhte ho:</strong></p><pre>var a = 10;<br><br>function greet() {<br>    console.log(&quot;Hello&quot;);<br>}<br><br>console.log(a);</pre><h4>Phases of Execution context:</h4><p><strong>Phase 1: Memory Creation Phase</strong><br>In this phase, Javascript will reserve the memory.</p><p>let/const is getting created but it is kept in TDZ, It is not accessible before intialization.</p><p>Variables -&gt; undefined<br>Functions -&gt; complete function body</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/843/1*o4niXomYlciFQFeH8wpnqQ.png" /></figure><p><strong>Phase 2: Execution phase<br></strong>Here, Javascript will execute code line by line.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/909/1*uHH1yshLXLL7DKyRb6dJWg.png" /></figure><p>whenever code will executed line by line the values of (var) will be assigned into memory. function will be executed on function call only.</p><h4>What is Call stack?</h4><p>Call Stack = <strong>Function calls track karne ka mechanism.<br>Stack follows: LIFO(Last In First Out).</strong></p><p>A stack data structure used by JavaScript to manage execution contexts and function calls.</p><p>Let’s understand by example:</p><pre>function one() {<br>    two();<br>}<br><br>function two() {<br>    three();<br>}<br><br>function three() {<br>    console.log(&quot;Hi&quot;);<br>}<br><br>one();</pre><p>Call Stack of above code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*tiG8IjazAiyLOeFqT8gSNA.png" /></figure><h4>How Does JavaScript Manage Function Calls?</h4><p><strong>whenever function is getting called/invoked:</strong></p><p><strong>Step1: </strong>Javascript create new execution context</p><p><strong>Step2: </strong>pushes it into call Stack</p><p><strong>Step3: </strong>Executes function</p><p><strong>Step4: </strong>Removes it from stack after completion</p><h4>Is Execution Context Created For Every Function Call?</h4><p><strong>→ YES, </strong>Every function call gets its own execution context.</p><p>Example:</p><pre>function greet(name) {<br>    console.log(name);<br>}<br><br>greet(&quot;Rahul&quot;);<br>greet(&quot;Amit&quot;);</pre><p><strong>First call:</strong></p><pre>Execution Context #1<br><br>name -&gt; Rahul</pre><p>Destroyed after execution.</p><p><strong>Second call: </strong>completely new, function is same but execution context is different.</p><pre>Execution Context #2<br><br>name -&gt; Amit</pre><p><strong>What is stack overflow?</strong></p><blockquote><em>→</em><strong><em> Occurs when too many execution contexts are pushed onto the call stack, usually due to infinite recursion.</em></strong></blockquote><p>example:</p><pre>function test() {<br>    test();<br>}<br><br>test();</pre><p>Thanks…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ac212a1cb5e4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Interview questions on React Router dom]]></title>
            <link>https://rahul319sinha.medium.com/interview-questions-on-react-router-dom-219962788803?source=rss-500522a24a92------2</link>
            <guid isPermaLink="false">https://medium.com/p/219962788803</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[reactive-programming]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Rahul Kumar]]></dc:creator>
            <pubDate>Thu, 01 Jan 2026 20:04:28 GMT</pubDate>
            <atom:updated>2026-07-29T18:14:14.418Z</atom:updated>
            <content:encoded><![CDATA[<ul><li>Routing is a technique used in modern web applications <strong>to configure USER</strong> and <strong>SEO friendly URL’s.</strong></li><li>User friendly URL allows the user to query any content directly from url.</li><li>SEO friendly url allows search engines to identify the exact location in page. It is mostly required for Anaytics.</li><li>Routing implicitly uses AJAX.<br>- It can load new details into page without reloading the page.<br>- User can stay one page and can get access to everything onto the page(SPA)</li><li>React 18 is using Routing versions V6 before React 18, It was using Routing versions V5.</li><li>Library for Routing is <strong>“react-router-dom”</strong>.</li></ul><p>For more updates: <a href="https://htechdigital.com/">Visit</a></p><h4>Basic Routing Components:</h4><ol><li><strong>BrowserRouter:</strong> It transcompiles the virtual route into actual browser route.</li></ol><pre>import { BrowserRouter as Router } from &#39;react-router-dom&#39;;<br><br>&lt;Router&gt;<br>  ... your routes...<br>&lt;/Router&gt;<br><br><br><br>or <br><br>import { BrowserRouter} from &#39;react-router-dom&#39;;<br><br>&lt;BrowserRouter&gt;<br>  ... your routes...<br>&lt;/BrowserRouter&gt;</pre><p><strong>Q1. which browser object of javascript can handle navigation?</strong></p><p>→ <strong>location object </strong>[location.href]</p><p><strong>Q2. How to we can add a new page into current browsing history?</strong></p><p>→ <strong>“history” </strong>object</p><p><strong>2. Routes: </strong><br>- It is collection of routes defined for application.<br>- It creates a Routing table.</p><p><strong>Syntax:</strong></p><pre>&lt;BrowserRouter&gt;<br>    &lt;Routes&gt;<br>        ...your routes...<br>    &lt;/Routes&gt;<br>&lt;/BrowserRouter&gt;<br></pre><p><strong>3. Route:</strong><br>- It is used to configure a route.<br>- Every route is an object with set of properties.<br> → index<br> → exact<br> → path<br> → element</p><p><strong>Syntax:</strong></p><pre>&lt;Route path=&#39;&#39; element={} index exact&gt;&lt;/Route&gt;<br> </pre><p>example:</p><pre>&lt;BrowserRouter&gt;<br>    &lt;Routes&gt;<br>        &lt;Route path=&#39;&#39; element=&#39;&#39; /&gt;<br>        &lt;Route path=&#39;&#39; element=&#39;&#39; /&gt;<br>        ..<br>        ..<br>    &lt;/Routes&gt;<br>&lt;/BrowserRouter&gt;</pre><ul><li>Route can have collection of child routes.</li></ul><pre>&lt;Routes&gt;<br>        &lt;Route path=&#39;&#39; element=&#39;&#39;&gt;<br>            &lt;Route path=&#39;&#39; element=&#39;&#39; /&gt;<br>            &lt;Route path=&#39;&#39; element=&#39;&#39; /&gt;<br>         &lt;/Route&gt;<br>       <br>    &lt;/Routes&gt;</pre><ul><li>Route can also have route parameters.</li></ul><pre>&lt;Routes&gt;<br>    &lt;Route path=&#39;:params&#39; element=&#39;&#39; /&gt;<br>&lt;/Routes&gt;</pre><ul><li>Route can also have search parameters.</li></ul><pre>&lt;Routes&gt;<br>        &lt;Route path=&#39;:params?key=data&#39; element=&#39;&#39; /&gt;<br>&lt;/Routes&gt;</pre><p>4. Link: <br>- It generates a routes link<br>- It navigates to specific path configured in route table.</p><p>Syntax:</p><pre>&lt;Link to=&#39;routePath&#39;&gt; Text | Image &lt;/Link&gt;</pre><p><strong>5. Outlet</strong><br>- It configures the target location where the resulting markup must be redered.</p><p><strong>Route can use markup directly from element.[It can render markup directly as result ]</strong></p><p>Example or Syntax:</p><pre>&lt;Routes&gt;<br>        &lt;Route path=&#39;routePath&#39; element={&lt;div&gt;Your Content&lt;/div&gt;} /&gt;<br>&lt;/Routes&gt;</pre><ul><li>If user is not requesting any specific path then you can define defult content to render.</li></ul><pre>&lt;Routes&gt;<br>        &lt;Route path=&#39;/&#39; element={default content to render} /&gt;<br>&lt;/Routes&gt;</pre><ul><li>If user is requesting a path and it is not available in application then we can render <strong>wild card route.</strong></li></ul><pre>&lt;Routes&gt;<br>        &lt;Route path=&#39;*&#39; element={content to render if requested path isn&#39;t available} /&gt;<br>&lt;/Routes&gt;</pre><p><strong>Q. How to navigate dynamically?</strong><br>- by using<strong> useNavigate()</strong> hook provided bu <strong>‘react-router-dom’,</strong> previously it is done by <strong>useHistory().</strong></p><p>Syntax:</p><pre>import {} from &#39;react-router-dom&#39;;<br><br>let navigate = useNavigate();<br><br>navigate(&#39;/login&#39;);</pre><h4>Route Parameters:</h4><ul><li>Parameter allow to query any content directly from URL.</li><li>Parameter is also used to transport data from one component to another.</li></ul><p>Step 1. Configure route path that can accept parameters</p><pre>&lt;Route path=&#39;name/:param1/:param2&#39; element={} /&gt;</pre><p>Step 2. Route parameters are passed with actual values from URL</p><pre>http:localhost:3000/name/value1/value2</pre><p>Step 3. Access Route paramaters using useParams() router hook.</p><pre>let params = useParams(); // Object with key and value<br>params.param1       // param1: value1<br>params.param2       // param2: value2</pre><h4>Query/Search Parameters:</h4><p><strong>In javascript :</strong></p><p>location.search is used to access the search parameters of URL.</p><pre>&lt;script&gt; <br>  var params = location.search;<br>  alert(params);<br>&lt;/script&gt;</pre><p>In React:</p><p>useSearchParams() hook is used to access the search params.</p><p>The useSearchParams hook is a powerful tool available in React Router v6 that allows you to work with <strong>query string parameters</strong> in your React components.</p><p>example:</p><h4><strong>Route Cycle:</strong></h4><p>There are many phases of route cycle:</p><ol><li><strong>BrowserRouter: </strong><br>- Map the virtual route to the actual DOM.</li><li><strong>Configure Route table(&lt;Routes&gt;&lt;/Routes&gt;)</strong><br>- creating Routes collection</li><li><strong>Configure Route using &lt;Route /&gt;</strong></li><li><strong>Configure request nad response</strong><br>- <strong>path</strong>: defines request<br>- element: defines response</li><li><strong>Configure Outlet</strong></li></ol><p><strong>How do we authenticate Routes?</strong><br>- React won’t provide any pre-defined service for route authentication.<br>- We have to explicitly implement by using techniques like: <strong>state</strong>, <strong>cookies</strong>, <strong>redux </strong>etc.</p><h4>Summary:</h4><p><strong>React Hooks used in Routing:</strong></p><ul><li><strong>useParams(): </strong>Access route parameters</li><li><strong>useSearchParams():</strong> Access route parameters</li><li><strong>useNavigate(): </strong>Dynamically navigating to any specified URL.</li><li><strong>useLocation():</strong> Provides access to location object of DOM and can return, href, pathname etc.</li><li><strong>useHistory():</strong> It can access the browser history and push any content into history<strong>(depricated).</strong></li></ul><p>For more updates: <a href="https://htechdigital.com/">Visit</a></p><h3>Thanks…</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=219962788803" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hoisting, Shadowing, and TDZ in JavaScript: Understanding var, let, and const]]></title>
            <link>https://rahul319sinha.medium.com/hoisting-shadowing-and-tdz-in-javascript-understanding-var-let-and-const-f95472130a2c?source=rss-500522a24a92------2</link>
            <guid isPermaLink="false">https://medium.com/p/f95472130a2c</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[javascript-hoisting]]></category>
            <category><![CDATA[javascript-development]]></category>
            <category><![CDATA[interview]]></category>
            <dc:creator><![CDATA[Rahul Kumar]]></dc:creator>
            <pubDate>Thu, 18 Sep 2025 16:46:32 GMT</pubDate>
            <atom:updated>2025-09-18T16:47:19.831Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tYV6ewElCjt7XzHH.png" /></figure><h4>What is Scope?</h4><p>→ A certain region of program whose defined variable exists &amp; can be recognized. Beyond that, it won’t be recognized.</p><p>or</p><p>Scope is the region of a program where a variable is accessible or can be referenced. Outside of that region, the variable cannot be accessed.</p><p><strong>Types of scope:</strong></p><ul><li>Global scope</li><li>Function scope</li><li>Block scope</li></ul><p><strong>Example:</strong></p><pre>// Global scope<br>var a = 20;<br><br>function name() {<br>   // function scope<br>}<br>{<br>   // block scope<br>}</pre><h4>var, let &amp; const:</h4><ul><li><strong>var</strong> → Function scoped (accessible throughout the entire function in which it is declared).</li><li><strong>let and </strong><strong>const</strong> → Block scoped (accessible only within the nearest { } block where they are declared).</li></ul><p><strong>Example:</strong><br><strong>var:</strong></p><pre>var a = 5;<br>console.log(a);   // 5</pre><p><strong>var in block level:</strong></p><pre>{<br>   var a = 5;<br>}<br>console.log(a);   // o/p -&gt; 5</pre><p><strong>let/const :</strong></p><pre>{<br>   let a = 5;<br>}<br>console.log(a);   // ReferenceError: a is not defined</pre><p><strong>let/const in block level:</strong></p><pre>{<br>   let a = 5;<br>   console.log(a);   // 5<br>}</pre><h4>Shadowing:</h4><p>Shadowing happens when a variable declared inside a certain scope (like a block { }) has the <strong>same name</strong> as a variable declared in an outer scope. The inner variable <strong>overrides (shadows)</strong> the outer one within its scope.</p><p><strong>Example:</strong></p><pre>function test() {<br>   let a = &quot;Hello&quot;;   // outer &#39;a&#39;<br>   if (true) {<br>      let a = &quot;Hi&quot;;   // inner &#39;a&#39; shadows outer &#39;a&#39;<br>      console.log(a);   // Output -&gt; Hi<br>   }<br>   console.log(a);      // Output -&gt; Hello<br>}<br>test();</pre><h4>Illegal Shadowing:</h4><ul><li><strong>var</strong> can be shadowed by <strong>let</strong>.</li><li>But <strong>let</strong> cannot be shadowed by <strong>var</strong> → This causes <strong>illegal shadowing</strong> and throws an error.</li></ul><p><strong>Example:</strong></p><pre>function test() {<br>   var a = &quot;Hello&quot;;<br>   let b = &quot;bye&quot;;<br>   if (true) {<br>      let a = &quot;Hi&quot;;       // valid shadowing<br>      var b = &quot;Goodbye&quot;;  // illegal shadowing:  SyntaxError: Identifier &#39;b&#39; has already been declared<br>      console.log(a);<br>      console.log(b);<br>   }<br>}<br>test();</pre><h4>2. Declaration Rules in JavaScript:</h4><ol><li><strong>var:</strong></li></ol><ul><li>Variables declared with var <strong>can be redeclared</strong> multiple times in the same scope.</li></ul><p>Example:</p><pre>var a;<br>var a;   // No error</pre><p><strong>2. let and const:</strong></p><ul><li>Variables declared with let or const <strong>cannot be redeclared</strong> in the same scope.</li></ul><p><strong>Example:</strong></p><pre>let a;<br>let a;   // Error: Identifier &#39;a&#39; has already been declared</pre><h4>3. Declaration Without Initialization:</h4><ul><li>var → Allowed</li><li>let → Allowed</li><li>const → ❌ Not allowed (must be initialized at the time of declaration)</li></ul><p>Example:</p><pre>var a;     // works<br>let b;     // works<br>const c;   // Error: Missing initializer<br>const d = 5; // works</pre><p><strong>Some examples:</strong></p><pre>var a = 3;<br>let a = 5;   // ❌ Error: Identifier &#39;a&#39; has already been declared</pre><pre>let a = 5;<br>var a = 3;   // ❌ Error: Identifier &#39;a&#39; has already been declared</pre><pre>var a = 3;<br>var a = 5;   // ✅ Works fine<br>console.log(a); // Output -&gt; 5</pre><h4>Re-initialization:</h4><ul><li><strong>var:</strong></li></ul><pre>var a = 3;<br>a = 6;    // ✅ works</pre><ul><li><strong>let:</strong></li></ul><pre>let a = 5;<br>a = 8;    // ✅ works</pre><ul><li><strong>const:</strong></li></ul><pre>const a = 7;<br>a = 8;    // ❌ not possible (re-initialization not allowed)</pre><h4>Hoisting</h4><p>Hoisting means that <strong>variable declarations are moved (hoisted) to the top of their scope during the compile phase</strong>, but <strong>initializations are not hoisted</strong>.</p><ul><li><strong>var</strong> → Hoisted and initialized with undefined.</li><li><strong>let &amp; </strong><strong>const</strong> → Hoisted but stay in the <strong>Temporal Dead Zone (TDZ)</strong> until initialized.</li></ul><p>Example with var:</p><pre>console.log(count); // Output -&gt; undefined<br>var count = 1;</pre><p>Here, the declaration of count is hoisted, but the assignment (= 1) happens later.</p><p>Example with let:</p><pre>console.log(c); // ReferenceError<br>let c = 1;</pre><p>Here, c is hoisted but cannot be accessed before initialization (it is in the TDZ).</p><h4>Temporal Dead Zone (TDZ):</h4><p>The <strong>TDZ</strong> is the time between when a variable is hoisted and when it is initialized.<br> During this period, accessing the variable throws a <strong>ReferenceError</strong>.</p><p>Example 1:</p><pre>function abc() {<br>   console.log(a);  // Output -&gt; undefined<br>   var a = 10;<br>}<br>abc();</pre><p>Here, var a is hoisted and initialized to undefined, so no error occurs.</p><p><strong>Example 2 (</strong><strong>let and </strong><strong>const in TDZ):</strong></p><pre>function abc() {<br>   console.log(a, b, c);<br>   const c = 10;<br>   let b = 2;<br>   var a = 4;<br>}<br>abc();</pre><p>Here, a is hoisted (initialized as undefined),<br> but b (let) and c (const) are still in the TDZ →</p><p><strong>Error:</strong></p><pre>ReferenceError: Cannot access &#39;b&#39; before initialization</pre><h3>Thanks…</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f95472130a2c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Node.js : Day 14]]></title>
            <link>https://rahul319sinha.medium.com/node-js-day-14-0c7baf7ebbb5?source=rss-500522a24a92------2</link>
            <guid isPermaLink="false">https://medium.com/p/0c7baf7ebbb5</guid>
            <category><![CDATA[mern-stack]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[node-js-tutorial]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Rahul Kumar]]></dc:creator>
            <pubDate>Tue, 02 Sep 2025 09:23:17 GMT</pubDate>
            <atom:updated>2026-10-16T14:54:31.628Z</atom:updated>
            <content:encoded><![CDATA[<h3>Master MongoDB with Node.js: Step-by-Step CRUD Operations Tutorial</h3><h4>Node.js : Day 14</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IFhzz9ZyIzkBPtZz.png" /></figure><p><strong>Prerequisites of this blog:</strong><br> - Basic understanding of Node.js.<br> - MongoDB installed locally or access to MongoDB Atlas.<br> - Node.js installed on the system.<br> - Basic JavaScript knowledge.</p><h4>Setting Up the Environment:</h4><p><strong>Step 1: Initialize a Node.js project:</strong></p><pre>$ mkdir mongodb-crud-tutorial<br><br>$ cd mongodb-crud-tutorial<br><br>$ npm init -y<br> </pre><p><strong>Step 2: Install dependencies:</strong></p><pre>$ npm install express mongoose </pre><p><strong>Step 3: Create the folder structure:</strong></p><pre><br>  mongodb-crud-tutorial/<br>  ├── models/<br>  ├── routes/<br>  ├── .env<br>  ├── server.js<br>  </pre><h4><strong>Step 4. Connect to MongoDB</strong></h4><p>Explain how to set up a `.env` file to store the MongoDB URI:</p><pre>MONGO_URI=mongodb+srv://&lt;username&gt;:&lt;password&gt;@cluster.mongodb.net/mydatabase?retryWrites=true&amp;w=majority</pre><p>Provide the code to connect to MongoDB using Mongoose in `server.js`:</p><pre><br>  const mongoose = require(&#39;mongoose&#39;);<br>  const express = require(&#39;express&#39;);<br>  const app = express();<br>  const dotenv = require(&#39;dotenv&#39;);<br><br>  dotenv.config();<br><br>  mongoose.connect(process.env.MONGO_URI)<br>  .then(() =&gt; console.log(&#39;MongoDB Connected&#39;))<br>  .catch(err =&gt; console.error(&#39;MongoDB Connection Failed:&#39;, err));<br><br>  app.use(express.json());<br><br>  const PORT = 5000;<br>  app.listen(PORT, () =&gt; console.log(`Server running on port ${PORT}`));</pre><h4><strong>Step 5. Define the Schema and Model</strong></h4><pre> <br>  const mongoose = require(&#39;mongoose&#39;);<br><br>  const UserSchema = new mongoose.Schema({<br>    name: { type: String, required: true },<br>    email: { type: String, required: true, unique: true },<br>    age: { type: Number, required: true },<br>  });<br><br>module.exports = mongoose.model(&#39;User&#39;, UserSchema);</pre><h4><strong>Step 6. Create Routes for CRUD Operations:</strong></h4><p><strong>Step 1: </strong>Set up routes in `<strong>routes/userRoutes.js</strong>`:</p><pre>  const express = require(&#39;express&#39;);<br>  const router = express.Router();<br>  const User = require(&#39;../models/User&#39;);// Create User (POST)<br>  router.post(&#39;/users&#39;, async (req, res) =&gt; {<br>    try {<br>      const user = new User(req.body);<br>      const savedUser = await user.save();<br>      res.status(201).json(savedUser);<br>    } catch (error) {<br>      res.status(400).json({ message: error.message });<br>    }<br>  });// Read All Users (GET)<br>  router.get(&#39;/users&#39;, async (req, res) =&gt; {<br>    try {<br>      const users = await User.find();<br>      res.status(200).json(users);<br>    } catch (error) {<br>      res.status(500).json({ message: error.message });<br>    }<br>  });<br>// Update User (PUT)<br>  router.put(&#39;/users/:id&#39;, async (req, res) =&gt; {<br>    try {<br>      const updatedUser = await User.findByIdAndUpdate(req.params.id, req.body, { new: true });<br>      res.status(200).json(updatedUser);<br>    } catch (error) {<br>      res.status(400).json({ message: error.message });<br>    }<br>  });<br>// Delete User (DELETE)<br>  router.delete(&#39;/users/:id&#39;, async (req, res) =&gt; {<br>    try {<br>      await User.findByIdAndDelete(req.params.id);<br>      res.status(200).json({ message: &#39;User deleted&#39; });<br>    } catch (error) {<br>      res.status(500).json({ message: error.message });<br>    }<br>  });<br><br>module.exports = router;<br></pre><p><strong>Step 2: </strong>Use the routes in `server.js`:</p><pre>  const userRoutes = require(&#39;./routes/userRoutes&#39;);<br>    <br>  app.use(&#39;/api&#39;, userRoutes);</pre><h4>7. Test the API</h4><p>Use Postman or a similar tool to test each endpoint:<br> <strong>POST:</strong> `/api/users` to create a user.<br> <strong>GET:</strong> `/api/users` to get all users.<br> <strong>PUT:</strong> `/api/users/:id` to update a user.<br><strong>DELETE: </strong>`/api/users/:id` to delete a user.</p><p>You can use Error Handling and Validation according to your preference.</p><h3>Thanks…</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0c7baf7ebbb5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Writing any: Learn Real TypeScript by Building]]></title>
            <link>https://rahul319sinha.medium.com/typescript-learn-by-doing-fe1e291946a6?source=rss-500522a24a92------2</link>
            <guid isPermaLink="false">https://medium.com/p/fe1e291946a6</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[typescript-tips]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Rahul Kumar]]></dc:creator>
            <pubDate>Mon, 18 Aug 2025 18:44:28 GMT</pubDate>
            <atom:updated>2026-10-16T14:49:30.533Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>Basic Types:</strong></h4><p>In TypeScript, you can define <strong>basic types</strong> for variables using the syntax:</p><pre>let variableName: variableType </pre><p><strong>variableTypes</strong> could be <strong>number, string, boolean &amp; null.</strong></p><p>Here are some common <strong>basic types</strong>:</p><p><strong>1. Number</strong></p><pre>let age: number = 25;<br>let price: number = 99.99;</pre><p><strong>2. String</strong></p><pre>let name: string = &quot;Rahul&quot;;<br>let greeting: string = `Hello, ${name}`;</pre><p><strong>3. Boolean</strong></p><pre>let isLoggedIn: boolean = true;<br>let hasAccess: boolean = false;</pre><p><strong>4. Null</strong></p><pre>let emptyValue: null = null;</pre><p><strong>Example:</strong></p><pre>let id: number = 101;<br>let username: string = &quot;Kumar&quot;;<br>let isActive: boolean = true;<br>let data: null = null;</pre><p><strong>Question 1: declare a variable named myNumber and assign it a value of 42. What data type should you use for this variable?</strong></p><p><strong>Solution:</strong></p><pre>let myNumber: number = 42 </pre><p><strong>Question 2:</strong> C<strong>reate a variable called myName and assign it a string value, such as your name. What data type should this variable have?</strong></p><p><strong>Solution:</strong></p><pre>let myName: string = &#39;John&#39; </pre><p><strong>Question 3:</strong> <strong>Declare a boolean variable named isStudent and set it to true or false. What data type is appropriate for this variable?</strong></p><p><strong>Solution:</strong></p><pre> let isStudent: boolean = true </pre><p><strong>Question 4: Define a variable called myData and assign it a value of null. What type should you assign to this variable?</strong></p><p><strong>solution:</strong></p><pre> let myData: null = null</pre><h4><strong>Array types in Typescript:</strong></h4><p>In TypeScript, you can define <strong>arrays with specific types</strong> to ensure all elements follow the same type.</p><p><strong>Syntax:</strong></p><pre>let arrayName: arrayType[] </pre><p><strong>arrayType </strong>could be anything from <strong>variableType.</strong></p><p><strong>Example:</strong></p><pre>// Array of numbers<br>let numbers: number[] = [1, 2, 3, 4, 5];<br><br>// Array of strings<br>let fruits: string[] = [&quot;Apple&quot;, &quot;Banana&quot;, &quot;Mango&quot;];<br><br>// Array of booleans<br>let flags: boolean[] = [true, false, true];<br><br>// Array of null values<br>let emptyValues: null[] = [null, null];<br><br>// Array of objects<br>type Person = {<br>  name: string;<br>  age: number;<br>};<br><br>let people: Person[] = [<br>  { name: &quot;Rahul&quot;, age: 25 },<br>  { name: &quot;Kumar&quot;, age: 28 },<br>];</pre><p><strong>Question 5</strong>: <strong>Create an array named numbers containing a list of numbers like [1, 2, 3, 4, 5].</strong></p><p><strong>Solution:</strong></p><pre> let numbersArray: number[] = [1, 2, 3, 4, 5] </pre><p><strong>Question 6. Declare an array called fruits containing a list of strings representing different fruit names.</strong></p><p><strong>Solution:</strong></p><pre> let fruits: string[] = [’apple’, &#39;banana’, &#39;orange’] </pre><h4><strong>Object types in TypeScript:</strong></h4><p>You can define the <strong>shape of an object inline</strong> using curly braces {} and specify types for each property.</p><pre> let objectName: { <br>  propertyName1: propertyType1; <br>  propertyName2: propertyType2; <br>} = {<br>  propertyName1: propertyValue,<br>  propertyName2: propertyValue<br>}; <br><br> // propertyType could be anything from variableType </pre><p><strong>Example:</strong></p><pre>let person: { <br>  name: string; <br>  age: number; <br>  isActive: boolean; <br>} = {<br>  name: &quot;Rahul&quot;,<br>  age: 25,<br>  isActive: true<br>};<br><br>console.log(person.name); // Rahul<br>console.log(person.age);  // 25<br>console.log(person.isActive); // true</pre><p><strong>Question 7.</strong> <strong>Create an object named person with properties name (string) and age (number).</strong></p><p><strong>Solution:</strong></p><pre> let person: { name: string; age: number } = { name: &#39;Alice’, age: 30 } </pre><p><strong>Question 8. Define an object car with properties make (string) and year (number).</strong></p><p><strong>Solution:</strong></p><pre>let car: { make: string; year: number } = { make: &#39;Toyota’, year: 2022 } <br></pre><p><strong>Question 8.</strong> Create an object student with properties name (string), age (number), and isEnrolled (boolean).</p><p><strong>Solution:</strong></p><pre> let student: { name: string; age: number; isEnrolled: boolean } = <br>                {  name: &#39;Bob&#39;,  age: 20,  isEnrolled: true, };</pre><p><strong>Question 9.</strong> <strong>Define an object named personDetails with properties name (string) age (number) hobbies (array of strings) address (object) with properties: street (string) city (string) isStudent (boolean) scores (array of numbers) extraInfo (null).</strong></p><p><strong>Solution:</strong></p><pre>let personDetails: {<br>  name: string;<br>  age: number;<br>  hobbies: string[];<br>  address: {<br>    street: string;<br>    city: string;<br>  };<br>  isStudent: boolean;<br>  scores: number[];<br>  extraInfo: null;<br>} = {<br>  name: &quot;Jane&quot;,<br>  age: 25,<br>  hobbies: [&quot;reading&quot;, &quot;hiking&quot;],<br>  address: {<br>    street: &quot;123 Main St&quot;,<br>    city: &quot;Cityville&quot;,<br>  },<br>  isStudent: false,<br>  scores: [90, 85, 78],<br>  extraInfo: null,<br>};</pre><h4><strong>Unions and Intersections in Typescript:</strong></h4><h4>1. Union Types</h4><ul><li>A <strong>union type</strong> allows a variable to hold <strong>one of multiple types</strong>.</li><li>You use the | (pipe) symbol to define a union.</li></ul><p><strong>Syntax:</strong></p><pre>let variable: type1 | type2;</pre><p><strong>Example:</strong></p><pre>let id: number | string;<br><br>id = 123;      <br>id = &quot;ABC123&quot;; <br>// id = true;  // Error: boolean not allowed</pre><h4>Variable unions:</h4><pre>let variableName: type1 | type2 // type could be anything from variableType</pre><p><strong>Question 10. Define a variable id with the type that allows it to store either a string or a number.</strong></p><p><strong>Solution:</strong></p><pre>let id: string | number;</pre><h4>union for arrays:</h4><pre>let arrayName: (type1 | type2 | type3 | ...etc )[];</pre><p><strong>Question 11.</strong> Declare a variable numberOrStringArray as an array that can store either number or string elements.</p><p><strong>Solution:</strong></p><pre>let numberOrStringArray: (number | string)[] = [1, &#39;two’, 3, &#39;four’]</pre><p><strong>Question 12.</strong> Create an array named mixedArray with elements of different data types such as numbers, strings, and booleans.</p><p><strong>Solution:</strong></p><pre>let mixedArray: (number | string | boolean)[] = [1, &#39;hello’, true, 42, false]</pre><h4>2. Intersection Types</h4><p>An <strong>intersection type</strong> combines multiple types into <strong>one</strong>, so the variable/object must satisfy <strong>all types at the same time</strong>.<br> You use the &amp; symbol to define intersections.</p><p><strong>Syntax:</strong></p><pre>type Combined = Type1 &amp; Type2;</pre><p><strong>example 1:</strong></p><pre>type TypeA = { propA: number } <br>type TypeB = { propB: string } <br><br>type CombinedType = TypeA &amp; TypeB </pre><p><strong>example 2:</strong></p><pre>// example 2 <br>type TypeA = { propA: number; propB: string } <br>type TypeB = TypeA &amp; {  propC: string } <br>type TypeC = TypeA &amp; {  propD: string }</pre><p><strong>real example:</strong></p><pre>type Person = {<br>  name: string;<br>  age: number;<br>};<br><br>type Employee = {<br>  employeeId: number;<br>  department: string;<br>};<br><br>type Staff = Person &amp; Employee;<br><br>const staffMember: Staff = {<br>  name: &quot;Rahul&quot;,<br>  age: 28,<br>  employeeId: 101,<br>  department: &quot;IT&quot;,<br>};</pre><p><strong>Question 13. define a type Person which has properties name (string) and age (number). define a type Student which extends Person and adds a property studentId (string). define a type Teacher which extends Person and adds a property subject (string).</strong></p><p><strong>Solution:</strong></p><pre>type Person = {  name: string  age: number } <br>type Student = Person &amp; {  studentId: string } <br>type Teacher = Person &amp; {  subject: string }</pre><h4><strong>Type inference:</strong></h4><p>Type inference is when typescript automatically figures out the type of a variable based on its initial value.</p><p><strong>Question 14:</strong> <strong>Declare a variable named myInferredNumber and assign it the value 10. What type is typescript inferring for this variable?</strong></p><p><strong>solution:</strong></p><pre> let myInferredNumber = 10 // TypeScript infers the type as number</pre><h3>Functions:</h3><pre>function functionName(parameter: parameterType): functionReturnType {<br>  // function logic here<br>}<br></pre><ul><li><strong>parameter: parameterType</strong> → TypeScript knows what type the input should be.</li><li><strong>functionReturnType</strong> → TypeScript knows what type the function will return.</li></ul><p><strong>Question 14.</strong> Define a function named greet that takes a parameter name (string) and consoles a greeting message like “Hello, [Name]!”.</p><p><strong>Solution:</strong></p><pre>function greet(name: string) : void {<br>  console.log(`Hello, ${name}!`);<br>}</pre><p><strong>Question 15.</strong> Create a function named addNumbers that takes two parameters a (number) and b (number), adds them together, and consoles the result.</p><p><strong>Solution:</strong></p><pre>const addNumbers = (a : number, b : number) =&gt;{<br>  const sum = a + b;<br>  console.log(`Sum: ${sum}`);<br>}</pre><p><strong>Question 16. </strong>Define a function calculateVolume that takes three parameters: length (number), width (number), and height (number). The function should calculate and return the volume of a box using the formula length * width * height.</p><p><strong>Solution:</strong></p><pre>const calculateVolume = (length: number, width: number, height: number) : number =&gt; {<br>  return length * width * height;<br>  <br>}</pre><h4>function with union types:</h4><p><strong>Example:</strong></p><pre> function functionName(<br>     parameter: parameterType1 | parameterType2,<br> ): functionReturnType {}</pre><p><strong>Question 17. </strong>Create a function named printInfo that takes a parameter info which can be either a string or a number. The function should console log the provided info.</p><p><strong>Solution:</strong></p><pre>const printInfo = (info : string | number) : void =&gt; {<br>    console.log(info);<br>}</pre><h4>function with discriminated unions:</h4><p>Example:</p><pre>type Type1 = {<br>  shape: &quot;circle&quot;<br> ...<br> };<br> type Type2 = {<br>  shape: &quot;rectangle&quot;<br> ...<br> };<br> type Type3 = Type1 | Type2;<br> function functionName(parameter: Type3): functionReturnType {}</pre><p><strong>Question 17. </strong>Define a function getArea that takes a parameter shape with a discriminated union type. The shape can be either a circle or a rectangle. If it’s a circle, the function should calculate and return the area of the circle using the formula π * radius². If it’s a rectangle, it should calculate and return the area using the formula length * width.</p><p><strong>Solution:</strong></p><pre>type Circle = {<br>  kind: &#39;circle&#39;;<br>  radius: number;<br>}<br><br>type Rectangle = {<br>  kind: &#39;rectangle&#39;;<br>  length: number;<br>  width: number;<br>}<br><br>type Shape = Circle | Rectangle;<br><br>function getArea(shape: Shape): number {<br>  if(shape.kind === &#39;circle&#39;){<br>      return Math.PI*shape.radius**2;<br>  }else {<br>      return shape.length * shape.width;<br>  }<br>}</pre><h4>function that converts object types:</h4><p>Example:</p><pre> type Type1 = {<br> ...<br> ...<br> };<br> type Type2 = Type1 &amp; {<br> ...<br> ...<br> };<br> function functionName(parameter: Type1): Type2 {}</pre><p><strong>Question 18. </strong>Define a function convertPersonToStudent that takes an object of type Person and returns an object of type Student. The Person object has properties name (string) and age (number), while the Student object should have properties name (string), age (number), and studentId (string).</p><p><strong>Solution:</strong></p><pre>type Person = {<br>  name: string;<br>  age: number;  <br>}<br><br>type Student = Person &amp; { studentId: string };<br><br>const convertPersonToStudent = (person: Person) : Student =&gt; {<br>     return { ...person, studentId: &#39;S123&#39; };<br>}</pre><p><strong>Question 19. </strong>Define a function doubleNumbers that takes an array of numbers and returns a new array where each number is doubled.</p><p>Solution:</p><pre>function doubleNumbers(numbers: number[]): number[] {<br>   return numbers.map((num) =&gt; num * 2)<br>}</pre><h3>Interfaces in Typescript:</h3><p>In <strong>TypeScript</strong>, an <strong>interface</strong> is a way to <strong>define the structure (shape) of an object</strong>. It tells TypeScript what properties (and methods) an object should have, along with their types.</p><p><strong>Syntax:</strong></p><pre> InterfaceName {  propertyName: propertyType  anotherProperty: anotherPropertyType } </pre><p><strong>Example:</strong></p><pre>interface User {<br>  id: number;<br>  name: string;<br>}<br><br>const user1: User = {<br>  id: 1,<br>  name: &quot;Rahul&quot;<br>}; <br></pre><p><strong>Question 20. </strong>Define an interface named Person with properties name (string) and age (number). Then, declare a variable person that adheres to this interface.</p><p><strong>solution:</strong></p><pre>interface Person {<br>  name: string;<br>  age: number;<br>}<br><br>let person : Person = {name: &quot;Rahul&quot;; age: 25};<br>console.log(person);</pre><p><strong>Question 21.</strong> complex interface practice chalenge Create an interface Car with the following properties: make (string) model (string) year (number) isElectric (boolean) features (array of strings).</p><p><strong>Solution:</strong></p><pre>interface Car {<br>  make : string;<br>  model: string;<br>  year: number;<br>  isElectric: boolean;<br>  features: string[];<br>}</pre><h4><strong>U</strong>sing interface in a function call:</h4><p><strong>Syntax:</strong></p><pre>InterfaceName { <br>    propertyName: propertyType;<br>    anotherProperty: anotherPropertyType;<br>} <br><br>function functionName(parameter: InterfaceName): functionReturnType {} </pre><p><strong>Example:</strong></p><pre>// Define an interface (blueprint of object)<br>interface User {<br>  id: number;<br>  name: string;<br>}<br><br>// Function that accepts a User object<br>function printUser(user: User): void {<br>  console.log(`ID: ${user.id}, Name: ${user.name}`);<br>}<br><br>// Call function with correct object<br>printUser({ id: 1, name: &quot;Rahul&quot; }); </pre><p><strong>Question 22. </strong>Define a function displayPerson that takes a parameter of type Person and consoles a message like &quot;Name: [Name], Age: [Age]&quot;.</p><p><strong>Solution:</strong></p><pre>interface Person {<br>  name :  string;<br>  age: number;<br>}<br><br>function displayPerson(person: Person) : void {<br>  console.log(`Name: ${person.name}, Age: ${person.age}`)<br>}<br><br>displayPerson({name: &quot;Rahul&quot;, age: 25})</pre><h4><strong>Function signature as an interface:</strong></h4><p><strong>Syntax:</strong></p><pre> InterfaceName { <br>(parameter1: parameterType1, <br>parameter2: parameterType2): <br>returnType } <br><br>const functionName: InterfaceName = () =&gt; {};</pre><p><strong>Question 22. </strong>Declare an interface MathFunction that defines a function signature for a function that takes two parameters of type number and returns a number. Then, define a function named add using this interface.</p><ul><li>A function to double the number</li><li>A function to return the square.</li></ul><p><strong>Solution:</strong></p><pre>const add: MathFunction = (a, b) =&gt; {<br>  return a + b;<br>}<br>console.log(add(3,5));<br><br>interface DoubleFunction { (a: number): number } <br><br>const double: DoubleFunction = (a) =&gt; 2 * a;<br>console.log(double(7));<br><br>const square: DoubleFunction = (a) =&gt; a * a;<br>console.log(square(10));</pre><h4>Simple function with generics:</h4><p>A <strong>generic function</strong> in TypeScript allows you to write a function that can work with <strong>any type</strong> while still preserving type safety.</p><p>Example:</p><pre>function functionName&lt;T&gt;(arg: T): T { // function logic here } </pre><pre>function identity&lt;T&gt;(arg: T): T {<br>  return arg;<br>}<br><br>let output1 = identity&lt;string&gt;(&quot;Hello&quot;);  // type is string<br>let output2 = identity&lt;number&gt;(100);      // type is number<br>let output3 = identity(true);             // type is boolean (TS infers T = boolean)</pre><p><strong>Question 22. </strong>Create a function named identity that takes a parameter value of any type and returns the same value.</p><p><strong>solution:</strong></p><pre>function identity&lt;T&gt;(value: T): T { return value };<br><br> identity&lt;number&gt;(&#39;22&#39;) // throw error<br> <br> identity&lt;number&gt;(22); // it will work</pre><p><strong>Question 23.</strong> Define a function named findItem that takes two parameters: an array items of type T[] and an item of type T. The function should return the index of the first occurrence of the item in the array, or -1 if the item is not found.</p><pre>function findItem&lt;T&gt;(items: T[], itemToBeFound: T): number {<br>    return items.findIndex(item =&gt; item === itemToBeFound);<br>}<br><br>const items = [1, 2, 3, 4, 5] // number[] <br>const itemToBeFound = &quot;3&quot;// string <br><br>findItem([1, 2, 3, 4, 5], 3); // 2<br>findItem([1, 2, 3, 4, 5], &#39;3&#39;); // ❌ TypeScript error (string is not number)<br>findItem([&#39;mango&#39;, &#39;banana&#39;, &#39;apple&#39;], 2); // ❌ TypeScript error (number is not string)<br>findItem([&#39;mango&#39;, &#39;banana&#39;, &#39;apple&#39;], &#39;guava&#39;); // -1 (valid, but not found)<br><br>const items = [1, 2, 3, 4, 5] // number[] <br>const itemToBeFound = 3// number<br>console.log(findItem(items, itemToBeFound)); // 2<br><br>const items = [1, 2, 3, 4, 5] // number[] <br>const itemToBeFound = 6// number<br>console.log(findItem(items, itemToBeFound)); // -1</pre><h4>Interfaces with optional properties:</h4><p>In <strong>TypeScript</strong>, when you define an interface, you can mark certain properties as <strong>optional</strong> by adding a ? after the property name.</p><p><strong>Example:</strong></p><pre> interface InterfaceName {<br>      propertyName: propertyType;<br>      **anotherProperty?**: anotherPropertyType;<br> }</pre><p><strong>Question 23. </strong>Create an interface Book with the following properties: title (string) author (string) year (number) genre (string, optional) todo Define two books one with genre and another without it. See if the one without that key gives an error. Now try this without the optional property and see the errors.</p><p><strong>Solution:</strong></p><pre> interface Book {  <br>    title: string;<br>    author: string;<br>    year: number;<br>    genre?: string <br>}<br><br>const bookWithGenre: Book = {<br>    title: &quot;The Hobbit&quot;,<br>    author: &quot;J.R.R. Tolkien&quot;,<br>    year: 1937,<br>    genre: &quot;Fantasy&quot;<br>};<br><br>const bookWithoutGenre: Book = {<br>    title: &quot;1984&quot;,<br>    author: &quot;George Orwell&quot;,<br>    year: 1949<br>};</pre><p>both is valid.</p><h3>Work with Objects in Typescript:</h3><h4>Define type for array of objects:</h4><p><strong>Syntax:</strong></p><pre> type Type1 = {}<br> const arrayObj: Type1[] = []</pre><p><strong>Example:</strong></p><pre>// Define type <br>type Person = {<br>  name: string;<br>  age: number;<br>};<br><br>// Define array of Person objects<br>const people: Person[] = [<br>  { name: &quot;Rahul&quot;, age: 25 },<br>  { name: &quot;Kumar&quot;, age: 28 },<br>  { name: &quot;Amit&quot;, age: 30 }<br>];</pre><p><strong>Question 23. </strong>Define a type named QuizQuestion that represents an object with properties: question (string) options (array of strings) correctOption (number).</p><p><strong>Solution:</strong></p><pre>type QuizQuestion = {<br>  question: string;<br>  options: string[];<br>  correctOption: number;<br>}<br><br> const quizQuestions: QuizQuestion[] = [<br>     {<br>        question: &#39;What is the capital of France?&#39;,<br>        options: [&#39;Paris&#39;, &#39;Berlin&#39;, &#39;Madrid&#39;, &#39;Rome&#39;],<br>        correctOption: 0,<br>     }<br> ]</pre><p><strong>Question 24. </strong>Define a type quizChecker for a function that takes a QuizQuestion (of type quizQuestion) and a userAnswer (number), and returns a boolean indicating whether the user’s answer is correct</p><p>Solution:</p><pre> type QuizQuestion = {<br>  question: string;<br>  options: string[];<br>  correctOption: number; // index of the correct option<br>};<br><br>// Define a type alias for a function signature<br>type QuizChecker = (quizQuestion: QuizQuestion, userAnswer: number) =&gt; boolean;<br><br>// Implement the function<br>const checkQuizAnswer: QuizChecker = (quizQuestion, userAnswer) =&gt; {<br>  return userAnswer === quizQuestion.correctOption;<br>};<br><br>// Example usage<br>const sampleQuestion: QuizQuestion = {<br>  question: &quot;What is 2 + 2?&quot;,<br>  options: [&quot;3&quot;, &quot;4&quot;, &quot;5&quot;],<br>  correctOption: 1, // index of &quot;4&quot;<br>};</pre><p><strong>Question 25. </strong>Define a type filterFunction for a function that takes an array of values (of any type) and a predicate function. The predicate function should take a single parameter and return a boolean. The main function should return an array containing only the values that satisfy the predicate.</p><pre> // Write an implementation of filterArray function with types<br> const isEven = (num: number) =&gt; num % 2 === 0<br> const numbers = [1, 2, 3, 4, 5, 6];<br><br> console.log(filterArray(numbers, isEven)) // Output: [2, 4, 6]<br><br> filterArray([&#39;a&#39;, &#39;bcd&#39;, &#39;efgh&#39;], (str) =&gt; str.length &gt; 3) // [&quot;efgh&quot;]<br> solution<br> </pre><p>Solution:</p><pre>type filterFunction&lt;T&gt; = (array: T[], predicate: (value: T) =&gt; boolean) =&gt; T[];<br><br>const filterArray: filterFunction&lt;number&gt; = (array, predicate) =&gt; {<br>    return array.filter(predicate)<br>}</pre><p><strong>Question 26. </strong>Define a type mapFunction for a function that takes an array of values (of any type) and a mapper function. The mapper function should take a single parameter and return a new value. The main function should return an array containing the mapped values.</p><pre> const doubleToString = (num: number) =&gt; (num * 2).toString();<br> const numbers = [1, 2, 3, 4, 5]; // number[] == T<br> console.log(mapArray(numbers, doubleToString));<br> // Output: [&quot;2&quot;, &quot;4&quot;, &quot;6&quot;, &quot;8&quot;, &quot;10&quot;] // string[] == R</pre><p>Solution:</p><pre> type mapFunction&lt;T, R&gt; = (array: T[], mapper: (value: T) =&gt; R) =&gt; R[]<br> const mapArray: mapFunction&lt;number, string&gt; = (array, mapper) =&gt; {<br> return array.map(mapper)<br> }<br> const doubleToString = (num: number) =&gt; (num * 2).toString()<br> const numbers = [1, 2, 3, 4, 5]<br> COPY<br> console.log(mapArray(numbers, doubleToString)) // Output: [&quot;2&quot;, &quot;4&quot;, &quot;6&quot;, &quot;8&quot;, &quot;10&quot;]</pre><h3>Thanks…</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fe1e291946a6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Inputs Practice Questions]]></title>
            <link>https://rahul319sinha.medium.com/react-inputs-practice-questions-87e6b8fbcd33?source=rss-500522a24a92------2</link>
            <guid isPermaLink="false">https://medium.com/p/87e6b8fbcd33</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[reactinput]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[reactjs]]></category>
            <dc:creator><![CDATA[Rahul Kumar]]></dc:creator>
            <pubDate>Wed, 09 Jul 2025 12:53:33 GMT</pubDate>
            <atom:updated>2025-07-09T12:53:33.333Z</atom:updated>
            <content:encoded><![CDATA[<h4>Working with Text Inputs and useState:</h4><p><strong>Question 1. </strong>Create an input field and whatever you type in the input field, show that text simultaneously below in a paragraph tag.</p><p><strong>Solution:</strong></p><pre>import { useState } from &quot;react&quot;;<br><br>const Question1 = () =&gt; {<br>const [inputValue, setInputValue] = useState&lt;any&gt;(&quot;&quot;);<br>const handleInputChange = (e: React.ChangeEvent&lt;HTMLInputElement&gt;) =&gt; {<br>    setInputValue(e.target.value);<br>};<br>return(<br>    &lt;div style={{ border: &quot;1px solid #ccc&quot;, padding: &#39;20px&#39; }}&gt;<br>        &lt;p&gt;{inputValue}&lt;/p&gt;<br>        &lt;input type=&quot;text&quot; name=&quot;text&quot; id=&quot;text&quot; onChange={handleInputChange}/&gt;<br>    &lt;/div&gt;<br>)<br>}<br>export default Question1;</pre><p><strong>Question 2. </strong>Create 2 text input fields ‘First Name’ and ‘Last Name’. On entering your name in the text fields, you should populate that input below in a paragraph tag.</p><p><strong>Soultion:</strong></p><pre>import { useState, type ChangeEvent } from &quot;react&quot;;<br><br>const Question2 = () =&gt; {<br>    const [firstName, setFirstName] = useState&lt;string&gt;(&quot;&quot;);<br>    const [lastName, setLastName] = useState&lt;string&gt;(&quot;&quot;);<br>    const handleFirstNameChange = (e : ChangeEvent&lt;HTMLInputElement&gt;) =&gt; {<br>        setFirstName(e.target.value);<br>    }<br>    const handleLastNameChange = (e: ChangeEvent&lt;HTMLInputElement&gt;) =&gt; {<br>        setLastName(e.target.value);<br>    }<br>    return(<br>        &lt;div style={{ border: &quot;1px solid #ccc&quot;, padding: &#39;20px&#39;, marginTop: &#39;20px&#39; }}&gt;<br>                &lt;h2&gt;Let&#39;s check you in&lt;/h2&gt;<br>                &lt;label className=&quot;inputfield&quot; style={{display: &quot;block&quot;, margin: &quot;5px&quot;}}&gt;<br>                    First name: &lt;input name=&quot;firstname&quot; onChange={handleFirstNameChange}/&gt;<br>                &lt;/label&gt;<br>                &lt;label className=&quot;inputfield&quot; style={{display: &quot;block&quot;, margin: &quot;5px&quot;}}&gt;<br>                    Last name: &lt;input name=&quot;lastname&quot; onChange={handleLastNameChange}/&gt;<br>                &lt;/label&gt;<br>                &lt;p&gt;<br>                    You will be checked in with the name: &lt;b&gt;<br>                        {firstName} {lastName}<br>                    &lt;/b&gt;<br>                &lt;/p&gt;<br>        &lt;/div&gt;<br>    )<br>}<br>export default Question2;</pre><p><strong>Question 3.</strong> Given an array of objects, fruits, which have properties name, color and quantity. Create a React component that takes a fruit name as input from the user, then searches the fruits array for a matching fruit name. If a matching fruit is found, display its color and quantity. If no matching fruit is found, display a message saying that the fruit was not found.</p><p><strong>Solution:</strong></p><pre>import { useState } from &quot;react&quot;;<br><br>type Fruit = {name: string; color: string; quantity: number}<br>const fruits: Fruit[] = [<br>    { name: &quot;Apple&quot;, color: &quot;Red&quot;, quantity: 10 },<br>    { name: &quot;Banana&quot;, color: &quot;Yellow&quot;, quantity: 5 },<br>    { name: &quot;Grapes&quot;, color: &quot;Purple&quot;, quantity: 20 },<br>];<br><br>const Question3  = () =&gt; {<br>    const [inputValue, setInputValue] = useState&lt;string&gt;(&#39;&#39;);<br>    const [result, setResult] = useState&lt;Fruit | null&gt;(null);<br> <br>    const handleInputChange = (e: React.ChangeEvent&lt;HTMLInputElement&gt;) =&gt; {<br>        setInputValue(e.target.value);<br>    };<br>    const handleSearch = () =&gt; {<br>        const fruit = fruits.find(fruit =&gt; fruit.name.toLowerCase() === inputValue.toLowerCase());<br>        if (fruit) {<br>            setResult(fruit);<br>        } else {<br>            setResult(null);<br>        }<br>    };<br>    return (<br>        &lt;div style={{ border: &quot;1px solid #ccc&quot;, padding: &#39;20px&#39;, marginTop: &#39;20px&#39; }}&gt;<br>            &lt;h2&gt;Fruit Search&lt;/h2&gt;<br>            &lt;label className=&quot;inputfield&quot; style={{ display: &quot;block&quot;, margin: &quot;5px&quot; }}&gt;<br>                Fruit Name: &lt;input type=&quot;text&quot; value={inputValue} onChange={handleInputChange} /&gt;<br>            &lt;/label&gt;<br>            &lt;button onClick={handleSearch}&gt;Search&lt;/button&gt;<br>            {result ? (<br>                &lt;div&gt;<br>                    &lt;p&gt;Fruit: {result.name}&lt;/p&gt;<br>                    &lt;p&gt;Color: {result.color}&lt;/p&gt;<br>                    &lt;p&gt;Quantity: {result.quantity}&lt;/p&gt;<br>                &lt;/div&gt;<br>            ) : (<br>                inputValue &amp;&amp; &lt;p&gt;Fruit not found.&lt;/p&gt;<br>            )}<br>        &lt;/div&gt;<br>    );<br>}<br>export default Question3;</pre><h4>Working with Dropdown and useState:</h4><p><strong>Question 4.</strong> Create a React component that allows the user to select a color from a dropdown menu.Change the color of heading text to the selected color. The component should have an initial state value of “black” for the selected color. The dropdown menu should include at least four color options: black, red, blue, and green. Use the useState hook to manage the state of the selected color.</p><p><strong>Solution:</strong></p><pre>import { useState } from &quot;react&quot;;<br><br>const Question4 = () =&gt; {<br>  const [selectedColor, setSelectedColor] = useState&lt;string | &quot;&quot;&gt;( &quot;&quot;);<br>  const handleSelectChange = (e: React.ChangeEvent&lt;HTMLSelectElement&gt;) =&gt; {<br>    const value = e.target.value;<br>    setSelectedColor(value === &quot;&quot; ? &quot;&quot; : value);<br>  };<br>  return (<br>    &lt;div&gt;<br>      &lt;h1 style={{ color: selectedColor || &quot;black&quot; }}&gt;<br>        Text to Be Colored on Selection.<br>      &lt;/h1&gt;<br>      &lt;select onChange={handleSelectChange} value={selectedColor}&gt;<br>        &lt;option value=&quot;&quot;&gt;--Choose Color--&lt;/option&gt;<br>        &lt;option value=&quot;black&quot;&gt;Black&lt;/option&gt;<br>        &lt;option value=&quot;blue&quot;&gt;Blue&lt;/option&gt;<br>        &lt;option value=&quot;green&quot;&gt;Green&lt;/option&gt;<br>        &lt;option value=&quot;red&quot;&gt;Red&lt;/option&gt;<br>      &lt;/select&gt;<br>    &lt;/div&gt;<br>  );<br>};<br>export default Question4;</pre><p><strong>Question 5.</strong>Create a React component, to display all the items in the fruits array on DOM. Create a dropdown select to filter fruits by category and display on the DOM.</p><pre>import { useState } from &quot;react&quot;;<br><br>const fruits = [<br>  { id: 1, category: &quot;Apple&quot;, name: &quot;Apple Shimla&quot; },<br>  { id: 2, category: &quot;Apple&quot;, name: &quot;Kashmiri Apple&quot; },<br>  { id: 3, category: &quot;Apple&quot;, name: &quot;Ambri Apple&quot; },<br>  { id: 4, category: &quot;Banana&quot;, name: &quot;Banana Robusta&quot; },<br>  { id: 5, category: &quot;Banana&quot;, name: &quot;Raw Banana Green&quot; },<br>  { id: 6, category: &quot;Orange&quot;, name: &quot;Orange Indian&quot; },<br>  { id: 7, category: &quot;Orange&quot;, name: &quot;Orange USA&quot; },<br>  { id: 8, category: &quot;Grapes&quot;, name: &quot;Grapes Black&quot; },<br>  { id: 9, category: &quot;Grapes&quot;, name: &quot;Grapes Seedless&quot; },<br>  { id: 10, category: &quot;Mango&quot;, name: &quot;Badami&quot; },<br>  { id: 11, category: &quot;Mango&quot;, name: &quot;Alphonso&quot; },<br>  { id: 12, category: &quot;Mango&quot;, name: &quot;Ratnagiri&quot; }<br>];<br>export default function Question5() {<br>  return (<br>    &lt;div&gt;<br>      &lt;select&gt;<br>        &lt;option value=&quot;All&quot;&gt;All&lt;/option&gt;<br>        &lt;option value=&quot;Apple&quot;&gt;Apple&lt;/option&gt;<br>        &lt;option value=&quot;Banana&quot;&gt;Banana&lt;/option&gt;<br>        &lt;option value=&quot;Orange&quot;&gt;Orange&lt;/option&gt;<br>        &lt;option value=&quot;Grapes&quot;&gt;Grapes&lt;/option&gt;<br>        &lt;option value=&quot;Mango&quot;&gt;Mango&lt;/option&gt;<br>      &lt;/select&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p><strong>Solution:</strong></p><pre>import { useState } from &quot;react&quot;;<br><br>type Fruit = {<br>    id: number;<br>    category: string;<br>    name: string;<br>}<br>const fruits: Fruit[] = [<br>    { id: 1, category: &quot;Apple&quot;, name: &quot;Apple Shimla&quot; },<br>    { id: 2, category: &quot;Apple&quot;, name: &quot;Kashmiri Apple&quot; },<br>    { id: 3, category: &quot;Apple&quot;, name: &quot;Ambri Apple&quot; },<br>    { id: 4, category: &quot;Banana&quot;, name: &quot;Banana Robusta&quot; },<br>    { id: 5, category: &quot;Banana&quot;, name: &quot;Raw Banana Green&quot; },<br>    { id: 6, category: &quot;Orange&quot;, name: &quot;Orange Indian&quot; },<br>    { id: 7, category: &quot;Orange&quot;, name: &quot;Orange USA&quot; },<br>    { id: 8, category: &quot;Grapes&quot;, name: &quot;Grapes Black&quot; },<br>    { id: 9, category: &quot;Grapes&quot;, name: &quot;Grapes Seedless&quot; },<br>    { id: 10, category: &quot;Mango&quot;, name: &quot;Badami&quot; },<br>    { id: 11, category: &quot;Mango&quot;, name: &quot;Alphonso&quot; },<br>    { id: 12, category: &quot;Mango&quot;, name: &quot;Ratnagiri&quot; }<br>  ];<br>const Question5 = () =&gt; {<br>    const [selectedFruit, setSelectedFruit] = useState&lt;string&gt;(&quot;All&quot;);<br>    const [filteredFruits, setFilteredFruits] = useState&lt;Fruit[]&gt;(fruits);<br>    const handleSelectionFruit = (e: React.ChangeEvent&lt;HTMLSelectElement&gt;) =&gt; {<br>        const value = e.target.value;<br>        setSelectedFruit(value);<br>        if (value !== &quot;All&quot;) {<br>            const filteredFruits = fruits.filter(fruit =&gt; fruit.category === value);<br>            setFilteredFruits(filteredFruits);<br>            console.log(&quot;Filtered Fruits: &quot;, filteredFruits);<br>        } else {<br>            setFilteredFruits(fruits);<br>            console.log(&quot;All Fruits: &quot;, fruits);<br>        }<br>    }<br>    return(<br>       &lt;div style={{ border: &quot;1px solid #ccc&quot;, padding: &#39;20px&#39;, marginTop: &#39;20px&#39; }}&gt;<br>        &lt;h2&gt;Fruit Selection&lt;/h2&gt;<br>         &lt;select onChange={handleSelectionFruit} value={selectedFruit}&gt;<br>        &lt;option value=&quot;All&quot;&gt;All&lt;/option&gt;<br>        &lt;option value=&quot;Apple&quot;&gt;Apple&lt;/option&gt;<br>        &lt;option value=&quot;Banana&quot;&gt;Banana&lt;/option&gt;<br>        &lt;option value=&quot;Orange&quot;&gt;Orange&lt;/option&gt;<br>        &lt;option value=&quot;Grapes&quot;&gt;Grapes&lt;/option&gt;<br>        &lt;option value=&quot;Mango&quot;&gt;Mango&lt;/option&gt;<br>      &lt;/select&gt;<br>      &lt;ul&gt;<br>        {filteredFruits.map((fruit) =&gt; (<br>          &lt;li key={fruit.id}&gt;{fruit.name}&lt;/li&gt;<br>        ))}<br>      &lt;/ul&gt;<br>       &lt;/div&gt;<br>    )<br>}<br>export default Question5;</pre><h4>Working with Checkboxes and useState</h4><p><strong>Question 6.</strong>Create a React component that displays a list of tasks, each with a checkbox next to it. When a checkbox is checked, display the task as strikethrough text.</p><pre>import { useState } from &quot;react&quot;;<br><br>export default function App() {<br>  const [tasks, setTasks] = useState([<br>    { id: 1, text: &quot;Clean the house&quot;, completed: false },<br>    { id: 2, text: &quot;Do laundry&quot;, completed: false },<br>    { id: 3, text: &quot;Buy groceries&quot;, completed: false }<br>  ]);<br>  return (<br>    &lt;div&gt;<br>      {tasks.map((task) =&gt; (<br>        &lt;div key={task.id}&gt;<br>          &lt;input type=&quot;checkbox&quot; checked={task.completed} /&gt;<br>          &lt;span&gt;{task.text}&lt;/span&gt;<br>        &lt;/div&gt;<br>      ))}<br>    &lt;/div&gt;<br>  );<br>}</pre><p><strong>Solution:</strong></p><pre>import { useState } from &quot;react&quot;;<br><br>type Task = {<br>  id: number;<br>  text: string;<br>  completed: boolean;<br>};<br>const Question6 = () =&gt; {<br>  const [tasks, setTasks] = useState&lt;Task[]&gt;([<br>    { id: 1, text: &quot;Clean the house&quot;, completed: false },<br>    { id: 2, text: &quot;Do laundry&quot;, completed: false },<br>    { id: 3, text: &quot;Buy groceries&quot;, completed: false },<br>  ]);<br>  const handleCheckboxChange = (taskId: number) =&gt; {<br>    const updatedTasks = tasks.map((task) =&gt;<br>      task.id === taskId ? { ...task, completed: !task.completed } : task<br>    );<br>    setTasks(updatedTasks);<br>  };<br>  return (<br>    &lt;div style={{ border: &quot;1px solid #ccc&quot;, padding: &quot;20px&quot;, marginTop: &quot;20px&quot; }}&gt;<br>      &lt;h2&gt;Task List&lt;/h2&gt;<br>      {tasks.map((task) =&gt; (<br>        &lt;div key={task.id}&gt;<br>          &lt;input<br>            type=&quot;checkbox&quot;<br>            checked={task.completed}<br>            onChange={() =&gt; handleCheckboxChange(task.id)}<br>          /&gt;<br>          &lt;span style={{ textDecoration: task.completed ? &quot;line-through&quot; : &quot;none&quot; }}&gt;<br>            {task.text}<br>          &lt;/span&gt;<br>        &lt;/div&gt;<br>      ))}<br>    &lt;/div&gt;<br>  );<br>};<br>export default Question6;</pre><h3>Thanks...</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=87e6b8fbcd33" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>