<?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 Jun Ukemori on Medium]]></title>
        <description><![CDATA[Stories by Jun Ukemori on Medium]]></description>
        <link>https://medium.com/@jukemori?source=rss-89c83af3c6c0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*8cHKQwNrmT8dEdEyfvo-8A.jpeg</url>
            <title>Stories by Jun Ukemori on Medium</title>
            <link>https://medium.com/@jukemori?source=rss-89c83af3c6c0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 10:12:12 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jukemori/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Understanding How to Flatten Arrays in JavaScript (Step-by-Step for Beginners)]]></title>
            <link>https://javascript.plainenglish.io/understanding-how-to-flatten-arrays-in-javascript-step-by-step-for-beginners-4cda0dc7370c?source=rss-89c83af3c6c0------2</link>
            <guid isPermaLink="false">https://medium.com/p/4cda0dc7370c</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[flatten]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[javascript-array-methods]]></category>
            <category><![CDATA[frontend-interviews]]></category>
            <dc:creator><![CDATA[Jun Ukemori]]></dc:creator>
            <pubDate>Sat, 08 Nov 2025 00:46:55 GMT</pubDate>
            <atom:updated>2025-11-08T07:50:57.372Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OprpWma71CcJTRnhJ7qAfQ.png" /></figure><p>When learning JavaScript, you’ll often run into interview questions like this:</p><blockquote><em>“Implement a function </em><em>flatten that returns a new array with all sub-array elements combined into a single level.”</em></blockquote><p>This might sound confusing at first — but once you understand it, it’s a fun problem that teaches loops, recursion, and JavaScript’s built-in array methods.</p><p>Let’s go through this slowly, in a way that’s clear even if you’re new to JavaScript.</p><h3>What Does “Flatten” Mean?</h3><p>If you have an array like this:</p><pre>[1, [2, [3, [4]]]]</pre><p>The goal is to <strong>flatten</strong> it into:</p><pre>[1, 2, 3, 4]</pre><p>In other words, we’re removing all the inner “boxes” (nested arrays) until everything is on one single level.</p><h3>Before You Code: Clarify the Problem</h3><p>In interviews, you should always ask these questions before you start coding:</p><ol><li><strong>What type of data does the array contain?</strong><br> Are the elements numbers, strings, or arrays inside arrays?<br> Some quick tricks only work with numbers.</li><li><strong>How deeply nested can it be?</strong><br> If there are thousands of levels, recursion might fail (JavaScript has limits).</li><li><strong>Should we change the original array or return a new one?</strong><br> Changing the input (mutating it) is risky — most of the time, it’s better to return a new array.</li><li><strong>Can we assume the input is valid?</strong><br> Usually yes, unless told otherwise.</li><li><strong>Does the environment support modern JavaScript (ES6+)?</strong><br> If yes, we can use newer features like the spread operator ... and flat().</li></ol><h3>Approach 1: Iterative with while, slice, shift, and unshift</h3><p>This version uses a <strong>loop</strong> (not recursion) to flatten arrays.</p><pre>function flatten(value) {<br>  const res = [];<br>  const copy = value.slice(); // make a copy so we don’t change the original array<br><br>  while (copy.length) {<br>    const item = copy.shift(); // take the first element<br>    if (Array.isArray(item)) {<br>      // if it’s an array, unpack it into the beginning<br>      copy.unshift(...item);<br>    } else {<br>      res.push(item); // if it’s not an array, add to result<br>    }<br>  }<br><br>  return res;<br>}</pre><h4>Built-in methods explained:</h4><ul><li>slice() → makes a shallow copy of the array.</li><li>shift() → removes and returns the first element.</li><li>unshift() → adds elements to the beginning of the array.</li><li>Array.isArray() → checks if something is an array.</li></ul><p>This approach avoids recursion and works for deeply nested arrays.</p><h3>Approach 2: Using some() and concat()</h3><p>This version uses a <strong>while loop</strong> with .some() to check if any nested arrays still exist.</p><pre>function flatten(value) {<br>  while (value.some(Array.isArray)) {<br>    value = [].concat(...value);<br>  }<br>  return value;<br>}</pre><h4>Built-in methods explained:</h4><ul><li>.some(Array.isArray) → returns true if <em>any</em> element is an array.</li><li>.concat(...value) → merges all items into one array.</li><li>... (spread operator) → spreads out elements of nested arrays.</li></ul><p>This keeps flattening layer by layer until no more arrays are left.</p><h3>Approach 3: Recursive with reduce() and concat()</h3><p>Recursion fits this problem naturally since arrays can contain arrays inside themselves.</p><pre>function flatten(value) {<br>  return value.reduce(<br>    (acc, curr) =&gt; acc.concat(Array.isArray(curr) ? flatten(curr) : curr),<br>    []<br>  );<br>}</pre><h4>Built-in methods explained:</h4><ul><li>.reduce() → loops through the array and builds up a single result (acc = accumulator).</li><li>.concat() → joins two arrays together.</li></ul><h4>Beginner note:</h4><p>If your array is <strong>very deeply nested</strong> (thousands of levels), recursion can cause a <strong>stack overflow</strong> — the browser can only handle a certain number of recursive calls.<br> In that case, the iterative version (Approach 1 or 2) is safer.</p><h3>Approach 4: Flatten In-Place Using splice()</h3><p>This version <strong>changes</strong> the original array instead of creating a new one.</p><pre>function flatten(value) {<br>  for (let i = 0; i &lt; value.length; ) {<br>    if (Array.isArray(value[i])) {<br>      value.splice(i, 1, ...value[i]);<br>    } else {<br>      i++;<br>    }<br>  }<br>  return value;<br>}</pre><h4>Built-in methods explained:</h4><ul><li>.splice(i, 1, ...value[i]) → removes the element at index i and inserts its inner items instead.</li><li>This <strong>mutates</strong> the array (changes it directly).</li></ul><p>If the interviewer wants a solution with constant space (no extra arrays), this is a great choice.</p><h3>Approach 5: Recursive with flatMap()</h3><p>flatMap() both maps and flattens by one level. Calling it recursively makes it fully flat.</p><pre>function flatten(value) {<br>  return Array.isArray(value)<br>    ? value.flatMap((item) =&gt; flatten(item))<br>    : value;<br>}</pre><h4>Built-in methods explained:</h4><ul><li>.flatMap() → runs a function on each element and flattens one level.</li><li>Recursion handles deeper levels.</li></ul><h3>Key Takeaways</h3><ul><li>Use Array.isArray() to check if something is an array.</li><li>Decide whether you want to <strong>mutate</strong> or <strong>return a new</strong> array.</li><li>Recursion is elegant but can fail for very deep arrays.</li><li>Iterative methods are safer for large inputs.</li><li>Bonus tricks are fun, but not practical in real projects.</li></ul><p>If you understand all these approaches, you’re not just learning how to flatten arrays — you’re also learning how JavaScript handles arrays, loops, recursion, and built-in methods.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4cda0dc7370c" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/understanding-how-to-flatten-arrays-in-javascript-step-by-step-for-beginners-4cda0dc7370c">Understanding How to Flatten Arrays in JavaScript (Step-by-Step for Beginners)</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding <script>, <script aync>, and <script defer> in JavaScript (Beginner-Friendly Guide)]]></title>
            <link>https://javascript.plainenglish.io/understanding-script-script-aync-and-script-defer-in-javascript-beginner-friendly-guide-d7639b010416?source=rss-89c83af3c6c0------2</link>
            <guid isPermaLink="false">https://medium.com/p/d7639b010416</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[script]]></category>
            <category><![CDATA[script-tag]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[html5]]></category>
            <dc:creator><![CDATA[Jun Ukemori]]></dc:creator>
            <pubDate>Tue, 28 Oct 2025 12:20:56 GMT</pubDate>
            <atom:updated>2025-10-28T14:58:42.478Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cEO8dBB3IpuSUYhtb4G2Rw.png" /></figure><p>When you include JavaScript files in your web pages, the browser must decide <strong>when</strong> to download and <strong>when</strong> to execute them.<br> That choice directly affects how fast your page appears and how your code runs.</p><p>The async and defer attributes give you control over this behavior.<br> Let’s go step-by-step and see exactly how they differ, with code examples you can test yourself.</p><h3>Normal Script — Blocks the Page</h3><p>Let’s start with a regular script:</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>  &lt;head&gt;<br>    &lt;script src=&quot;script.js&quot;&gt;&lt;/script&gt;<br>  &lt;/head&gt;<br>  &lt;body&gt;<br>    &lt;h1&gt;Hello World&lt;/h1&gt;<br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><p>And in <strong>script.js</strong>:</p><pre>console.log(&#39;Script running...&#39;);</pre><p><strong>What happens:</strong></p><ul><li>The browser starts reading your HTML.</li><li>When it reaches &lt;script src=&quot;script.js&quot;&gt;, it <strong>pauses</strong> HTML parsing.</li><li>It downloads and executes the script.</li><li>Only then it continues building the rest of the page.</li></ul><p>So if the script is large or slow to download, your users will see a blank screen longer.</p><h3>Async — Run As Soon As It’s Ready</h3><p>Now let’s use the async attribute:</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>  &lt;head&gt;<br>    &lt;script src=&quot;first.js&quot; async&gt;&lt;/script&gt;<br>    &lt;script src=&quot;second.js&quot; async&gt;&lt;/script&gt;<br>  &lt;/head&gt;<br>  &lt;body&gt;<br>    &lt;h1&gt;Async Example&lt;/h1&gt;<br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><p><strong>first.js:</strong></p><pre>console.log(&#39;First script loaded&#39;);</pre><p><strong>second.js:</strong></p><pre>console.log(&#39;Second script loaded&#39;);</pre><p><strong>How async works:</strong></p><ol><li>The browser continues parsing HTML <strong>while downloading</strong> both scripts.</li><li>When a script finishes downloading, it <strong>pauses HTML parsing</strong>, executes it, then continues.</li><li>Because they run <strong>as soon as they’re ready</strong>, the order is not guaranteed.</li></ol><p>For example, even though first.js is listed first, you might see this in the console:</p><pre>Second script loaded<br>First script loaded</pre><p>Async scripts are great for things like:</p><ul><li>Analytics</li><li>Ads</li><li>Any script that doesn’t depend on the DOM or other scripts</li></ul><h3>Defer — Wait Until HTML is Done</h3><p>Now try defer:</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>  &lt;head&gt;<br>    &lt;script src=&quot;first.js&quot; defer&gt;&lt;/script&gt;<br>    &lt;script src=&quot;second.js&quot; defer&gt;&lt;/script&gt;<br>  &lt;/head&gt;<br>  &lt;body&gt;<br>    &lt;h1&gt;Defer Example&lt;/h1&gt;<br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><p><strong>first.js:</strong></p><pre>console.log(&#39;First defer script&#39;);</pre><p><strong>second.js:</strong></p><pre>console.log(&#39;Second defer script&#39;);</pre><p><strong>How defer works:</strong></p><ol><li>The browser downloads scripts <strong>while parsing</strong> the HTML.</li><li>It does <strong>not block</strong> HTML parsing.</li><li>All deferred scripts execute <strong>after</strong> the HTML is fully parsed.</li><li>Importantly, they run <strong>in order</strong>.</li></ol><p>So your console will always show:</p><pre>First defer script<br>Second defer script</pre><p>That’s why defer is ideal for most modern JavaScript — it guarantees your DOM is ready and keeps your page loading fast.</p><h3>Comparing Load Behavior</h3><p>Here’s a summary using plain words instead of tables:</p><ul><li><strong>Normal script:</strong> Stops the page from rendering until it runs.</li><li><strong>Async script:</strong> Loads in the background and runs immediately after download (order not guaranteed).</li><li><strong>Defer script:</strong> Loads in the background and runs only after the HTML is done (order preserved).</li></ul><h3>Real-World Example</h3><p>Here’s a practical example that shows how each type behaves in the console:</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br>  &lt;head&gt;<br>    &lt;script&gt;<br>      console.log(&#39;1. Inline head script&#39;);<br>    &lt;/script&gt;<br><br>    &lt;script src=&quot;async.js&quot; async&gt;&lt;/script&gt;<br>    &lt;script src=&quot;defer.js&quot; defer&gt;&lt;/script&gt;<br>  &lt;/head&gt;<br>  &lt;body&gt;<br>    &lt;h1&gt;Script Loading Demo&lt;/h1&gt;<br>    &lt;script&gt;<br>      console.log(&#39;2. Inline body script&#39;);<br>    &lt;/script&gt;<br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><p><strong>async.js:</strong></p><pre>console.log(&#39;3. Async script&#39;);</pre><p><strong>defer.js:</strong></p><pre>console.log(&#39;4. Defer script&#39;);</pre><p><strong>Possible console output:</strong></p><pre>1. Inline head script<br>3. Async script<br>2. Inline body script<br>4. Defer script</pre><p>Notice:</p><ul><li>The async script (3) may appear before the body script because it runs as soon as it’s ready.</li><li>The defer script (4) always runs last — after the HTML is parsed.</li></ul><h3>When Should You Use Each?</h3><ul><li><strong>Use normal scripts</strong> only when you need to block rendering (very rare).</li><li><strong>Use async</strong> for scripts that run independently, like analytics or ads.</li><li><strong>Use defer</strong> for your main JavaScript files that rely on the DOM being ready.</li></ul><h3>Best Practice</h3><p>In modern web development, a good default pattern is:</p><pre>&lt;script src=&quot;main.js&quot; defer&gt;&lt;/script&gt;</pre><p>That ensures your main logic runs after the DOM is ready, without delaying page rendering.</p><h3>Final Thoughts</h3><p>Understanding the difference between async and defer is one of those “small things” that makes your website faster and smoother.<br> It’s not about writing more code — it’s about <strong>telling the browser when to run it</strong>.</p><h3>A message from our Founder</h3><p><strong>Hey, </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>Sunil</strong></a><strong> here.</strong> I wanted to take a moment to thank you for reading until the end and for being a part of this community.</p><p>Did you know that our team run these publications as a volunteer effort to over 3.5m monthly readers? <strong>We don’t receive any funding, we do this to support the community. ❤️</strong></p><p>If you want to show some love, please take a moment to <strong>follow me on </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>LinkedIn</strong></a><strong>, </strong><a href="https://tiktok.com/@messyfounder"><strong>TikTok</strong></a>, <a href="https://instagram.com/sunilsandhu"><strong>Instagram</strong></a>. You can also subscribe to our <a href="https://newsletter.plainenglish.io/"><strong>weekly newsletter</strong></a>.</p><p>And before you go, don’t forget to <strong>clap</strong> and <strong>follow</strong> the writer️!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d7639b010416" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/understanding-script-script-aync-and-script-defer-in-javascript-beginner-friendly-guide-d7639b010416">Understanding &lt;script&gt;, &lt;script aync&gt;, and &lt;script defer&gt; in JavaScript (Beginner-Friendly Guide)</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Throttle in JavaScript (Beginner-Friendly Explanation)]]></title>
            <link>https://javascript.plainenglish.io/understanding-throttle-in-javascript-beginner-friendly-explanation-03297051fb50?source=rss-89c83af3c6c0------2</link>
            <guid isPermaLink="false">https://medium.com/p/03297051fb50</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[throttle]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[javascript-interview]]></category>
            <category><![CDATA[debounce]]></category>
            <dc:creator><![CDATA[Jun Ukemori]]></dc:creator>
            <pubDate>Sun, 26 Oct 2025 02:46:36 GMT</pubDate>
            <atom:updated>2025-10-27T16:55:15.303Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i6GfAptypLVn1LbOR9i8_w.png" /></figure><p>When you start working with JavaScript and user interactions, you may come across a term called <strong>“throttling.”</strong> It’s a common question in front-end interviews, and understanding it deeply will help you write more efficient code and perform better in interviews.</p><p>Let’s break it down step-by-step.</p><h3>What Does “Throttle” Even Mean?</h3><p>In plain English, <strong>to throttle</strong> means <strong>to limit or control the flow</strong> of something.<br> Think of it like pressing the gas pedal in a car — throttling determines <strong>how much and how often</strong> fuel goes to the engine.</p><p>In JavaScript, throttling is about <strong>controlling how often a function runs</strong> over time.</p><p>For example, imagine you have a function that runs every time you scroll or resize the browser window. These events can fire hundreds of times per second, and constantly executing a heavy function can slow down your app. Throttling prevents this by allowing the function to run <strong>at most once every X milliseconds</strong>.</p><h3>The Basic Idea</h3><p>If a function is throttled with a wait time of 100ms, it means:</p><ul><li>The function will run immediately when first called.</li><li>Then it will ignore any further calls for the next 100ms.</li><li>After 100ms, it can run again.</li></ul><p>So, it’s like a <strong>temporary lock</strong> that prevents the function from firing too frequently.</p><h3>Example of a Throttled Function</h3><pre>let i = 0;<br>function increment() {<br>  i++;<br>}<br><br>const throttledIncrement = throttle(increment, 100);<br><br>// t = 0ms: Run immediately<br>throttledIncrement(); // i = 1<br><br>// t = 50ms: Ignored because 100ms hasn’t passed<br>throttledIncrement(); // i = 1<br><br>// t = 101ms: Run again<br>throttledIncrement(); // i = 2</pre><h3>Step-by-Step Implementation</h3><p>Here’s the most common version of a throttle function:</p><pre>export default function throttle(func, wait = 0) {<br>  let shouldThrottle = false;<br><br>  return function (...args) {<br>    if (shouldThrottle) {<br>      return;<br>    }<br><br>    shouldThrottle = true;<br>    setTimeout(function () {<br>      shouldThrottle = false;<br>    }, wait);<br><br>    func.apply(this, args);<br>  };<br>}</pre><p>Let’s break it down carefully.</p><h3>Understanding the Logic</h3><h4>1. The States: Idle and Active</h4><p>The throttled function can be in one of two states:</p><p><strong>Idle:</strong><br> The function hasn’t been called recently. When you call it, it executes immediately and changes state to “Active.”</p><p><strong>Active:</strong><br> The function has already been called recently (within the wait period). Any further calls are ignored until the timer finishes.</p><p>We use a boolean variable shouldThrottle to track this state.</p><h4>2. Setting Up the Throttle Logic</h4><p>When we call the throttled function:</p><ul><li>First, we check if shouldThrottle is true.</li><li>If it is, that means the function is in the “Active” state — so we <strong>return early</strong> and do nothing.</li><li>If it’s not throttled:</li><li>We set shouldThrottle = true to lock it.</li><li>Run the original function (func.apply(this, args)).</li><li>Start a timer with setTimeout to release the lock after the wait time.</li></ul><h4>3. Why Use apply() Instead of Just Calling the Function?</h4><p>If you just call func(...args), the value of this inside the original function may be lost — especially if you’re using it in a method like object.method.</p><p>Using func.apply(this, args) ensures that the function runs in the correct context, preserving this.</p><h4>4. Why Not Use an Arrow Function?</h4><p>Inside the returned throttled function, we need access to the dynamic value of this, which depends on how the function is called.</p><p>Arrow functions don’t have their own this — they capture it from the surrounding lexical scope, which could lead to incorrect behavior.</p><p>Therefore, we use a regular function expression instead of an arrow function, ensuring that this correctly refers to the caller when func.apply(this, args) runs.</p><h3>Understanding the Order of Operations</h3><p>You might wonder:<br> Can we change the order like this?</p><pre>setTimeout(() =&gt; { shouldThrottle = false; }, wait);<br>shouldThrottle = true;<br>func.apply(this, args);</pre><p>Yes, this order is fine because:</p><ol><li>shouldThrottle is set to true <strong>before</strong> calling the function, so the next immediate calls are blocked.</li><li>The setTimeout schedules the unlock for later, but does not block the main thread.</li><li>Then the function executes right away.</li></ol><p>If you swapped the order incorrectly (like calling func before setting shouldThrottle), you’d risk overlapping calls before the lock is active.</p><p>So the correct order is:</p><ol><li>Set shouldThrottle = true</li><li>Schedule setTimeout to release it later</li><li>Run the function</li></ol><h3>How It Works in the Event Loop</h3><p>Let’s visualize this in the JavaScript event loop:</p><pre>Time (ms):   0          50         100         150<br>Action:     call()     call()     call()     call()<br><br>State:<br>- At 0ms → shouldThrottle = false → run func() → set lock true → start 100ms timer<br>- At 50ms → shouldThrottle = true → ignore call<br>- At 100ms → timer finishes → shouldThrottle = false<br>- At 101ms → call runs again</pre><p>The setTimeout callback goes to the <strong>task queue</strong> and is picked up by the <strong>event loop</strong> once the timer expires.<br> That’s how the lock automatically resets.</p><h3>Real-World Example</h3><p>Imagine you’re building an app that tracks the user’s scroll position:</p><pre>function onScroll() {<br>  console.log(window.scrollY);<br>}<br><br>const throttledScroll = throttle(onScroll, 200);<br>window.addEventListener(&#39;scroll&#39;, throttledScroll);</pre><p>Without throttling, this event could fire <strong>hundreds of times per second</strong>, flooding your console and slowing down performance.</p><p>With throttling, the function runs at most once every 200ms, keeping your app fast and smooth.</p><h3>Throttle vs Debounce (Quick Note)</h3><ul><li><strong>Throttle:</strong> Ensures the function runs <strong>at regular intervals</strong>, no matter how often the event happens.</li><li><strong>Debounce:</strong> Ensures the function runs <strong>only after a pause</strong> in activity.</li></ul><p>For example:</p><ul><li>Use <strong>throttle</strong> for scroll or resize events.</li><li>Use <strong>debounce</strong> for search input fields or text changes.</li></ul><h3>Common Variations</h3><p>This version of throttle is the simplest form.<br> Libraries like Lodash have more advanced versions that support:</p><ul><li><strong>Leading:</strong> Call immediately when first triggered.</li><li><strong>Trailing:</strong> Also call one more time after the final event.</li><li><strong>Cancel:</strong> Stop all scheduled executions.</li></ul><p>These give you finer control, depending on your use case.</p><h3>Summary</h3><p>Throttling helps you control how often a function executes over time.<br> The main concepts are:</p><ul><li>It runs <strong>immediately once</strong>, then locks for the specified wait duration.</li><li>Calls during the lock are <strong>ignored</strong>.</li><li>After the timer finishes, the function can run again.</li><li>We use setTimeout, a boolean flag, and apply() to make it work correctly.</li></ul><h3>Final Code Recap</h3><pre>export default function throttle(func, wait = 0) {<br>  let shouldThrottle = false;<br><br>  return function (...args) {<br>    if (shouldThrottle) return;<br><br>    shouldThrottle = true;<br>    setTimeout(() =&gt; { shouldThrottle = false; }, wait);<br><br>    func.apply(this, args);<br>  };<br>}</pre><p>Understanding throttle and debounce is one of the most important JavaScript interview topics. Once you can explain how this works, you’re not just memorizing answers — you’re mastering the JavaScript event loop, asynchronous timing, and performance optimization fundamentals.</p><h3>A message from our Founder</h3><p><strong>Hey, </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>Sunil</strong></a><strong> here.</strong> I wanted to take a moment to thank you for reading until the end and for being a part of this community.</p><p>Did you know that our team run these publications as a volunteer effort to over 3.5m monthly readers? <strong>We don’t receive any funding, we do this to support the community. ❤️</strong></p><p>If you want to show some love, please take a moment to <strong>follow me on </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>LinkedIn</strong></a><strong>, </strong><a href="https://tiktok.com/@messyfounder"><strong>TikTok</strong></a>, <a href="https://instagram.com/sunilsandhu"><strong>Instagram</strong></a>. You can also subscribe to our <a href="https://newsletter.plainenglish.io/"><strong>weekly newsletter</strong></a>.</p><p>And before you go, don’t forget to <strong>clap</strong> and <strong>follow</strong> the writer️!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=03297051fb50" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/understanding-throttle-in-javascript-beginner-friendly-explanation-03297051fb50">Understanding Throttle in JavaScript (Beginner-Friendly Explanation)</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cookies vs. localStorage vs. sessionStorage — A Beginner-Friendly Explanation]]></title>
            <link>https://javascript.plainenglish.io/cookies-vs-localstorage-vs-sessionstorage-a-beginner-friendly-explanation-e7d421bd3f6d?source=rss-89c83af3c6c0------2</link>
            <guid isPermaLink="false">https://medium.com/p/e7d421bd3f6d</guid>
            <category><![CDATA[sessionstorage]]></category>
            <category><![CDATA[cookies]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[webapi]]></category>
            <category><![CDATA[localstorage]]></category>
            <dc:creator><![CDATA[Jun Ukemori]]></dc:creator>
            <pubDate>Sat, 25 Oct 2025 11:56:34 GMT</pubDate>
            <atom:updated>2025-10-25T17:13:22.834Z</atom:updated>
            <content:encoded><![CDATA[<h3>Cookies vs. localStorage vs. sessionStorage — A Beginner-Friendly Explanation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WH5CRBiedKbGmbxoPv85wA.png" /></figure><p>When you build web apps, you often need to <strong>store data in the browser</strong> — maybe to remember a user’s theme, keep them logged in, or save a form draft.<br> The browser provides three main options for storing such data:</p><ul><li><strong>Cookies</strong></li><li><strong>localStorage</strong></li><li><strong>sessionStorage</strong></li></ul><p>They might sound similar, but they behave quite differently.<br> Let’s go through what each one does, how they differ, and when to use them — all in simple terms.</p><h3>Cookies</h3><p>Cookies are the oldest and most widely used method for saving small pieces of data in the browser.<br> They were designed to let the <strong>server and browser share information</strong>, such as login sessions or user preferences.</p><h4>Key points</h4><ul><li>Each cookie can store <strong>about 4KB</strong> of data.</li><li>Cookies can have an <strong>expiration date</strong> (Expires) or a time-to-live (Max-Age). If none is set, they are deleted when the browser closes.</li><li>They are <strong>sent automatically</strong> to the server with every HTTP request to the same domain.</li><li>Cookies are available to <strong>both the server and client-side JavaScript</strong> (unless protected).</li><li>You can make cookies safer with flags like:</li><li>HttpOnly (prevents JavaScript access)</li><li>Secure (only sent over HTTPS)</li><li>SameSite (controls cross-site behavior)</li></ul><h4>Example</h4><pre>// Set a cookie that expires in one week<br>document.cookie = &quot;username=John; Max-Age=604800; path=/&quot;;<br><br>// Read all cookies<br>console.log(document.cookie);<br><br>// Delete a cookie<br>document.cookie = &quot;username=; Max-Age=0; path=/&quot;;</pre><h4>When to use cookies</h4><p>Use cookies when the <strong>server needs to read or update</strong> data regularly — for example, when managing user authentication sessions or server-side preferences.</p><h4>Important note</h4><p>Because cookies are sent with every request, having too many or very large cookies can slow down requests slightly.<br> They also shouldn’t store sensitive data unless you protect them with HttpOnly and Secure flags.</p><h3>localStorage</h3><p>localStorage is part of the modern <strong>Web Storage API</strong>.<br> It lets you store data directly in the browser as key–value pairs and is designed for <strong>client-side persistence</strong> — meaning it’s not automatically shared with the server.</p><h4>Key points</h4><ul><li>Each domain can store <strong>around 5MB</strong> (varies by browser).</li><li>Data in localStorage <strong>persists even after the browser is closed</strong>.</li><li>Data is <strong>shared across all tabs and windows</strong> of the same origin.</li><li>The data is stored as <strong>strings only</strong> — if you want to store objects, you must serialize them using JSON.stringify().</li><li>It’s <strong>not sent to the server automatically</strong> with requests.</li></ul><h4>Example</h4><pre>// Save a value<br>localStorage.setItem(&quot;theme&quot;, &quot;dark&quot;);<br><br>// Get the value<br>console.log(localStorage.getItem(&quot;theme&quot;)); // &quot;dark&quot;<br><br>// Store an object<br>const user = { name: &quot;Alice&quot;, age: 25 };<br>localStorage.setItem(&quot;user&quot;, JSON.stringify(user));<br><br>// Retrieve and parse it<br>console.log(JSON.parse(localStorage.getItem(&quot;user&quot;))); // { name: &quot;Alice&quot;, age: 25 }<br><br>// Remove or clear<br>localStorage.removeItem(&quot;theme&quot;);<br>localStorage.clear();</pre><h4>When to use localStorage</h4><p>Use localStorage for <strong>data that stays across sessions</strong> but doesn’t need to be shared with the server — such as:</p><ul><li>User interface preferences (dark mode, layout)</li><li>Cached data or app state</li><li>Small offline storage</li></ul><h4>Important note</h4><p>Because localStorage is accessible via JavaScript, never store sensitive data such as tokens, passwords, or personal information there.<br> Also, since the server cannot read localStorage, it <strong>shouldn’t be used for authentication data</strong> if you rely on server-side rendering or preloading user state.</p><h3>sessionStorage</h3><p>sessionStorage is similar to localStorage but is designed for <strong>temporary storage</strong>.<br> It holds data for as long as the page session lasts — that is, until the tab or browser window is closed.</p><h4>Key points</h4><ul><li>It can typically store around <strong>5MB</strong> per origin.</li><li>Data <strong>disappears when the tab or window closes</strong>.</li><li>It’s <strong>not shared across tabs or windows</strong>, even if they have the same origin.</li><li>It only stores <strong>strings</strong>, like localStorage.</li><li>It’s <strong>not sent to the server automatically</strong>.</li></ul><h4>Example</h4><pre>// Store temporary data<br>sessionStorage.setItem(&quot;draft&quot;, &quot;This is my draft comment&quot;);<br><br>// Retrieve it<br>console.log(sessionStorage.getItem(&quot;draft&quot;));<br><br>// Remove or clear<br>sessionStorage.removeItem(&quot;draft&quot;);<br>sessionStorage.clear();</pre><h4>When to use sessionStorage</h4><p>Use sessionStorage for <strong>temporary data</strong> that you only need during one browser session — for example:</p><ul><li>Form input that resets when the tab closes</li><li>Temporary state for single-page apps</li><li>Data that should not persist between sessions</li></ul><h3>Summary of differences</h3><p>Let’s summarize the key differences clearly in words (no table needed):</p><p><strong>1. Lifetime</strong></p><ul><li><strong>Cookies</strong>: Can persist based on expiration or until browser closes.</li><li><strong>localStorage</strong>: Persists even after closing and reopening the browser.</li><li><strong>sessionStorage</strong>: Only lasts until the tab or window is closed.</li></ul><p><strong>2. Access</strong></p><ul><li><strong>Cookies</strong>: Accessible to both the client and the server (sent with each HTTP request).</li><li><strong>localStorage</strong> and <strong>sessionStorage</strong>: Only accessible on the client side through JavaScript.</li></ul><p><strong>3. Size</strong></p><ul><li><strong>Cookies</strong>: Around 4KB per cookie.</li><li><strong>localStorage</strong> and <strong>sessionStorage</strong>: Around 5MB per origin (depends on browser).</li></ul><p><strong>4. Sharing between tabs</strong></p><ul><li><strong>Cookies</strong>: Shared across tabs and windows.</li><li><strong>localStorage</strong>: Shared across tabs and windows of the same origin.</li><li><strong>sessionStorage</strong>: Unique to each tab or window.</li></ul><p><strong>5. Use cases</strong></p><ul><li><strong>Cookies</strong>: For server communication, authentication, or user tracking.</li><li><strong>localStorage</strong>: For long-term client-side data like UI preferences.</li><li><strong>sessionStorage</strong>: For short-term session data or temporary state.</li></ul><h3>Modern alternatives — the CookieStore API</h3><p>Modern browsers have introduced the <strong>CookieStore API</strong>, which provides a promise-based interface for managing cookies more cleanly in JavaScript.</p><p>For example:</p><pre>// Read cookies asynchronously<br>const cookies = await cookieStore.getAll();<br>console.log(cookies);<br><br>// Set a cookie<br>await cookieStore.set({<br>  name: &quot;theme&quot;,<br>  value: &quot;dark&quot;,<br>  expires: Date.now() + 7 * 24 * 60 * 60 * 1000, // 1 week<br>});</pre><p>This API is still gaining adoption, but it’s a simpler and more modern alternative to manually parsing document.cookie.</p><h3>Important reminders</h3><ul><li>All three methods — cookies, localStorage, and sessionStorage — store <strong>only strings</strong>.<br> Use JSON.stringify() and JSON.parse() for complex data.</li><li>None of them are fully secure by themselves. Sensitive data should always be encrypted or handled server-side.</li><li>Avoid using localStorage or sessionStorage for data that must be available to the server during initial rendering.</li><li>Use cookies carefully to prevent performance issues and potential vulnerabilities.</li></ul><h3>Final thoughts</h3><p>Understanding the differences between cookies, localStorage, and sessionStorage helps you choose the right storage method for your web applications.</p><ul><li><strong>Cookies</strong>: Small, shared with the server, useful for sessions and authentication.</li><li><strong>localStorage</strong>: Persistent, client-only, great for saving preferences and cached data.</li><li><strong>sessionStorage</strong>: Temporary, client-only, ideal for session-based or tab-specific data.</li></ul><p>As you continue learning web development, experiment with each one in your browser’s developer console — it’s the best way to see how they behave in real time.</p><h3>A message from our Founder</h3><p><strong>Hey, </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>Sunil</strong></a><strong> here.</strong> I wanted to take a moment to thank you for reading until the end and for being a part of this community.</p><p>Did you know that our team run these publications as a volunteer effort to over 3.5m monthly readers? <strong>We don’t receive any funding, we do this to support the community. ❤️</strong></p><p>If you want to show some love, please take a moment to <strong>follow me on </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>LinkedIn</strong></a><strong>, </strong><a href="https://tiktok.com/@messyfounder"><strong>TikTok</strong></a>, <a href="https://instagram.com/sunilsandhu"><strong>Instagram</strong></a>. You can also subscribe to our <a href="https://newsletter.plainenglish.io/"><strong>weekly newsletter</strong></a>.</p><p>And before you go, don’t forget to <strong>clap</strong> and <strong>follow</strong> the writer️!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e7d421bd3f6d" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/cookies-vs-localstorage-vs-sessionstorage-a-beginner-friendly-explanation-e7d421bd3f6d">Cookies vs. localStorage vs. sessionStorage — A Beginner-Friendly Explanation</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Modules in JavaScript]]></title>
            <link>https://javascript.plainenglish.io/understanding-modules-in-javascript-1b8db01faee1?source=rss-89c83af3c6c0------2</link>
            <guid isPermaLink="false">https://medium.com/p/1b8db01faee1</guid>
            <category><![CDATA[modules]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[commonjs]]></category>
            <dc:creator><![CDATA[Jun Ukemori]]></dc:creator>
            <pubDate>Fri, 24 Oct 2025 10:43:09 GMT</pubDate>
            <atom:updated>2025-10-27T17:02:02.011Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zdAMyLkNL0qIyIekPzsA3g.png" /></figure><p>Imagine your codebase as a big workshop. Modules are like separate tool-boxes: each holds related tools (functions, variables) and you pull in only what you need. This helps keep things organized, reusable, and easier to manage.</p><p>In JavaScript there are two popular “module systems” you’ll encounter:</p><ul><li><strong>CommonJS</strong> (CJS)</li><li><strong>ES Modules</strong> (ESM)</li></ul><p>They both let you split your code into parts, but they work differently. Let’s walk through the differences, and where each fits.</p><h3>What is CommonJS?</h3><p>CommonJS is the older system, originally built for server-side JavaScript (especially in Node.js).<br> Here are its key traits:</p><ul><li>You <strong>require</strong> modules with require(…).</li><li>You export by assigning to module.exports (or exports).</li><li>Modules are loaded <strong>synchronously</strong> (at runtime) — meaning the code is executed at the moment the require happens.</li><li>It’s dynamic: you can conditionally require modules (inside if, loops, etc.).</li><li>Historically the default in Node-based projects.</li></ul><p><strong>Example:</strong></p><pre>// myModule.js<br>const value = 42;<br>module.exports = { value };<br><br>// main.js<br>const myModule = require(&#39;./myModule.js&#39;);<br>console.log(myModule.value);  // 42</pre><p>Because the loading is synchronous and dynamic, common JS systems tend to work well for server environments where immediate availability is okay.</p><h3>What are ES Modules?</h3><p>ES Modules are the newer, standard module system for JavaScript (introduced in ES2015/ES6). They’re designed to work both in browsers and in server environments (with the right setup). Key features:</p><ul><li>Use import … from … to bring in modules.</li><li>Use export … to export pieces of a module.</li><li>Modules are loaded statically, which means imports/exports are known before runtime in many cases.</li><li>Because of the static structure, tools can perform optimizations (like “tree-shaking”, eliminating unused exports).</li><li>In browsers these modules are now natively supported (in modern ones), and in Node.js you can use them with specific configurations (e.g., using .mjs extension or setting &quot;type&quot;: &quot;module&quot; in package.json).</li></ul><p><strong>Example:</strong></p><pre>// myModule.js<br>export const value = 42;<br><br>// main.js<br>import { value } from &#39;./myModule.js&#39;;<br>console.log(value); ­ // 42</pre><p>Because of the static design, ES Modules encourage a more declarative structure: “this module exports these, this module imports those” at the top — which can improve readability and tooling.</p><h3>Side-by-side: CommonJS vs ES Modules</h3><p>Rather than use a table (Medium doesn’t support tables easily), here’s a bullet style comparison:</p><h4>Syntax</h4><ul><li><strong>CommonJS</strong>: const x = require(&#39;…&#39;);, module.exports = ….</li><li><strong>ES Modules</strong>: import { x } from &#39;…&#39;;, export const x = …;.</li></ul><h4>Loading behaviour</h4><ul><li>CommonJS: Modules loaded synchronously at runtime.</li><li>ES Modules: Modules loaded (or at least processed) statically, enabling asynchronous loading in some contexts.</li></ul><h4>Environment / Compatibility</h4><ul><li>CommonJS: Historically built for Node.js (server).</li><li>ES Modules: Designed for both browser and server environments (with configuration).</li><li>In browsers: ES Modules have native support in modern browsers; CommonJS modules typically need bundlers/transpilers.</li><li>In Node.js: You’ll still find lots of CommonJS code; ES Modules are increasingly used.</li></ul><h4>Optimizations / Tooling</h4><ul><li>CommonJS: Because of its dynamic nature (you can require conditionally, export in runtime), tooling such as tree-shaking is more limited.</li><li>ES Modules: Because the exports/imports are known statically (at compile time), bundlers can better optimize — e.g., remove unused exports, make smaller bundles.</li></ul><h4>File / module naming</h4><ul><li>CommonJS: Usually .js files, and require behaves accordingly.</li><li>ES Modules: Often .mjs extension or .js with &quot;type&quot;: &quot;module&quot; in package.json. Also browsers may require full file paths (including extension).</li></ul><h3>Mixing CommonJS and ES Modules</h3><p>A lot of older Node.js projects were built using <strong>CommonJS</strong>, so you’ll still find many libraries that use require() and module.exports.<br> On the other hand, <strong>ES Modules</strong> are the modern standard, and most new projects use import and export.</p><p>Because both systems exist side-by-side, you might sometimes work with a mix of them. That’s okay — but it can get a little tricky.</p><p>For example:</p><ul><li>A module written with module.exports = something (CommonJS) doesn’t always behave the same as export default something (ES Modules).</li><li>You might need special syntax or configuration for Node.js to understand which system your file uses — for example, setting &quot;type&quot;: &quot;module&quot; in your package.json or using .mjs extensions.</li><li>When converting an old CommonJS project to ES Modules, you may need to update import paths or tweak your bundler setup.</li></ul><p>In short: it’s <em>possible</em> to mix them, but it’s usually easiest to stick to <strong>one module system</strong> in your project whenever you can.</p><h3>When Should You Use Which?</h3><p>Here are some guidelines (for beginners) to help decide:</p><ul><li>If you’re working in a <strong>browser-only</strong> context (modern browsers) and you’re starting fresh: go with ES Modules.</li><li>If you’re using Node.js and working with lots of legacy modules (which use require()): you may stick with CommonJS or gradually migrate to ESM.</li><li>If you are building libraries that will be used both in browser and Node, using ES Modules might give you better future-proofing and tooling advantages.</li><li>If you need features like tree-shaking in bundlers (for smaller bundle size): ES Modules are beneficial.</li><li>If you need conditional loading of modules at runtime (depending on logic) and that’s essential: CommonJS supports more dynamic loading.</li></ul><h3>A Few Gotchas to Watch Out For</h3><ul><li>In Node.js, when using ES Modules you might need to set &quot;type&quot;: &quot;module&quot; in package.json, or use .mjs file extensions.</li><li>Some libraries export in a format optimized for CommonJS and may require interop layers when used in ES Modules.</li><li>Import paths in ES Modules often must include the full filename (including extension) or correct resolution, especially in browsers.</li><li>With CommonJS you can require inside functions/blocks; with ES Modules you cannot import dynamically in the same way (though dynamic import() can be used).</li><li>Default exports vs named exports can cause confusion when mixing systems: CommonJS module.exports = something may be imported differently in ESM environments.</li></ul><h3>The Big Picture</h3><p>In summary:</p><ul><li>Both systems solve the same high-level problem: modularizing code.</li><li>CommonJS is older, simpler in server contexts, highly used in Node history.</li><li>ES Modules bring in the modern standard, better browser support, static structure, and improved tooling.</li><li>For new projects, leaning into ES Modules is a wise choice; for existing codebases with CommonJS, you may continue or migrate gradually.</li></ul><h3>Why This Matters for You</h3><p>As you build JavaScript applications — whether front-end or back-end — you’ll almost certainly need to use modules. Understanding the difference means:</p><ul><li>You can read and understand code that uses either system.</li><li>You can make informed decisions about which module system to use.</li><li>You avoid confusion when your project “just works” in one environment but breaks in another because of module-type mismatches.</li><li>You’ll better understand build-tool configs (like webpack, rollup, babel, etc.) which often talk about “ESM”, “CommonJS”, “module resolution”, etc.</li></ul><h3>Final Thoughts</h3><p>Think of modules as your building blocks. Whether you use CommonJS or ES Modules, the key is to keep your code organized, maintainable, and clear. As JavaScript evolves, ES Modules are becoming the default — so getting comfortable with import/export now will pay off. But knowing CommonJS means you’ll have fewer surprises when working with older code or libraries.</p><h3>A message from our Founder</h3><p><strong>Hey, </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>Sunil</strong></a><strong> here.</strong> I wanted to take a moment to thank you for reading until the end and for being a part of this community.</p><p>Did you know that our team run these publications as a volunteer effort to over 3.5m monthly readers? <strong>We don’t receive any funding, we do this to support the community. ❤️</strong></p><p>If you want to show some love, please take a moment to <strong>follow me on </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>LinkedIn</strong></a><strong>, </strong><a href="https://tiktok.com/@messyfounder"><strong>TikTok</strong></a>, <a href="https://instagram.com/sunilsandhu"><strong>Instagram</strong></a>. You can also subscribe to our <a href="https://newsletter.plainenglish.io/"><strong>weekly newsletter</strong></a>.</p><p>And before you go, don’t forget to <strong>clap</strong> and <strong>follow</strong> the writer️!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b8db01faee1" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/understanding-modules-in-javascript-1b8db01faee1">Understanding Modules in JavaScript</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Debounce in JavaScript: A Simple Explanation for Beginners]]></title>
            <link>https://javascript.plainenglish.io/debounce-in-javascript-a-simple-explanation-for-beginners-6d362d67ea2f?source=rss-89c83af3c6c0------2</link>
            <guid isPermaLink="false">https://medium.com/p/6d362d67ea2f</guid>
            <category><![CDATA[javascript-this]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[debounce]]></category>
            <category><![CDATA[callback-function]]></category>
            <category><![CDATA[event-loop]]></category>
            <dc:creator><![CDATA[Jun Ukemori]]></dc:creator>
            <pubDate>Mon, 20 Oct 2025 13:14:16 GMT</pubDate>
            <atom:updated>2025-10-21T08:39:49.576Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nBHWLw9lH5gHG82yP0m2SQ.png" /></figure><p>When building interactive web pages, you often need to handle user actions like typing, scrolling, or resizing the window.<br> These actions can happen many times per second, and running a function every time can make your page slow or unresponsive.</p><p>To fix that, developers use a technique called <strong>debounce</strong>.<br> It makes sure a function only runs <strong>after</strong> the user stops performing an action for a certain amount of time.</p><h3>What Debounce Does</h3><p>Debounce delays function execution until activity stops.<br> Instead of running a function many times, it waits for a pause and runs it once.</p><h3>Common examples</h3><ul><li><strong>Typing in a search box:</strong> wait until the user stops typing before searching.</li><li><strong>Window resizing:</strong> wait until resizing stops before recalculating the layout.</li><li><strong>Form validation:</strong> wait until typing stops before checking input values.</li></ul><p>This prevents unnecessary work and keeps the app fast.</p><h3>The Debounce Function</h3><p>Here’s the code:</p><pre>export default function debounce(func, wait = 0) {<br>  let timeoutID = null;<br><br>  return function (...args) {<br>    const context = this;<br>    clearTimeout(timeoutID);<br><br>    timeoutID = setTimeout(function () {<br>      timeoutID = null;<br>      func.apply(context, args);<br>    }, wait);<br>  };<br>}</pre><p>This might look simple, but there’s a lot going on. Let’s go through it step by step.</p><h3>Step-by-Step Breakdown</h3><h4>Timeout and clearTimeout</h4><p>When you use setTimeout, you schedule a function to run after a delay.<br> It doesn’t stop the code — it just says, “run this later.”</p><pre>setTimeout(() =&gt; {<br>  console.log(&quot;Runs after 2 seconds&quot;);<br>}, 2000);<br><br>console.log(&quot;Runs immediately&quot;);</pre><p>Output:</p><pre>Runs immediately<br>Runs after 2 seconds</pre><p>If you call setTimeout many times, all those scheduled tasks will still run — unless you cancel them using clearTimeout.</p><pre>const id = setTimeout(() =&gt; console.log(&quot;This won&#39;t run&quot;), 2000);<br>clearTimeout(id);</pre><p>Here, the timeout is cleared, so nothing happens.<br> Debounce uses this behavior to make sure only the <strong>last call</strong> executes.</p><h4>Understanding the Event Loop</h4><p>JavaScript runs code line by line, but some things — like setTimeout — happen asynchronously.</p><p>Here’s a simple demonstration:</p><pre>console.log(&quot;A&quot;);<br><br>setTimeout(() =&gt; {<br>  console.log(&quot;B&quot;);<br>}, 1000);<br><br>console.log(&quot;C&quot;);</pre><p>Output:</p><pre>A<br>C<br>B</pre><p>Even though B was scheduled first, it runs last because setTimeout adds it to the <strong>task queue</strong>, and the event loop executes it only after the current call stack is empty.</p><p>This is how debounce can delay execution without blocking other code.</p><h4>Storing this with Context</h4><p>One of the most confusing parts for beginners is this line:</p><pre>const context = this;</pre><p>Let’s understand why it’s needed.</p><p>When the returned function runs (debouncedSearch in our example), this refers to the object that triggered it — for example, an input element or a button.<br>But inside the setTimeout callback, this would normally be lost, because the timer function runs in a different context (usually window).</p><p>So we store this in context before setting the timeout:</p><pre>const context = this;</pre><p>Then later, we use:</p><pre>func.apply(context, args);</pre><p>This ensures that the original function (func) runs with the <strong>correct </strong><strong>this value</strong>.</p><h4>Real Example: Context in Action</h4><p>Suppose you use debounce for a search box:</p><pre>import debounce from &#39;./debounce.js&#39;;<br><br>function handleSearchInput(event) {<br>  console.log(&quot;this is:&quot;, this);<br>  console.log(&quot;Searching for:&quot;, event.target.value);<br>}<br><br>const debouncedSearch = debounce(handleSearchInput, 500);<br>const input = document.querySelector(&quot;#search&quot;);<br>input.addEventListener(&quot;input&quot;, debouncedSearch);</pre><p>When you type in the input and pause for 500ms, the output is:</p><pre>this is: &lt;input id=&quot;search&quot;&gt;<br>Searching for: hello</pre><p>Here’s what happens behind the scenes:</p><ul><li>The &quot;input&quot; event fires and calls debouncedSearch.</li><li>Inside debouncedSearch, this refers to the input element (because it’s attached via addEventListener).</li><li>We store that in context.</li><li>When the timeout finishes, we call:</li></ul><pre>func.apply(context, args);</pre><ul><li>which becomes:</li></ul><pre>handleSearchInput.apply(inputElement, [event]);</pre><p>That’s why this still refers to the correct &lt;input&gt; element, even though the function runs later.</p><p>If we didn’t save context, this would become window, and the event handler would lose its proper context.</p><h4>Why Use func.apply(context, args)</h4><p>.apply() calls the original function while keeping:</p><ul><li>The same this (stored in context),</li><li>The same arguments (collected in args).</li></ul><p>Example:</p><pre>function greet(greeting, name) {<br>  console.log(greeting, name, this.extra);<br>}<br><br>const person = { extra: &quot;from USA&quot; };<br><br>greet.apply(person, [&quot;Hello&quot;, &quot;John&quot;]); <br>// Output: &quot;Hello John from USA&quot;</pre><p>So in the debounce function, .apply() ensures the original function runs with the right this and all its original arguments.</p><h3>Example: Debounce in Action</h3><pre>function logInput(value) {<br>  console.log(&quot;Input value:&quot;, value);<br>}<br><br>const debouncedLog = debounce(logInput, 500);<br><br>// Simulate fast typing<br>debouncedLog(&quot;H&quot;);<br>debouncedLog(&quot;He&quot;);<br>debouncedLog(&quot;Hel&quot;);<br>debouncedLog(&quot;Hell&quot;);<br>debouncedLog(&quot;Hello&quot;);</pre><p><strong>What happens:</strong></p><ol><li>Each call starts a new timer (500ms).</li><li>Before the 500ms passes, the next call cancels the previous timer.</li><li>The final call (“Hello”) is the only one that isn’t canceled.</li><li>After 500ms of no new calls, it runs and logs:</li></ol><pre>Input value: Hello</pre><h3>Real-World Examples</h3><h4>Example 1: Search Box — Run Function After User Stops Typing</h4><pre>import debounce from &#39;./debounce.js&#39;;<br><br>function handleSearchInput(event) {<br>  console.log(&quot;Searching for:&quot;, event.target.value);<br>  // Imagine sending an API request here<br>}<br><br>// Wait 500ms after user stops typing<br>const debouncedSearch = debounce(handleSearchInput, 500);<br><br>const input = document.querySelector(&quot;#search&quot;);<br>input.addEventListener(&quot;input&quot;, debouncedSearch);</pre><p><strong>How it works:</strong></p><ul><li>While typing, the timer keeps resetting.</li><li>Only after the user stops typing for 500ms does it run the handleSearchInput function.</li><li>Prevents unnecessary API calls.</li></ul><h4>Example 2: Window Resize — Run Function After User Stops Resizing</h4><pre>import debounce from &#39;./debounce.js&#39;;<br><br>function handleResize() {<br>  console.log(&quot;Window resized to:&quot;, window.innerWidth, &quot;x&quot;, window.innerHeight);<br>}<br><br>// Wait 300ms after resizing stops<br>const debouncedResize = debounce(handleResize, 300);<br><br>window.addEventListener(&quot;resize&quot;, debouncedResize);</pre><p><strong>How it works:</strong></p><ul><li>Resizing triggers many events per second.</li><li>Debounce ensures the function runs only <em>after</em> resizing stops for 300ms.</li></ul><h4>Example 3: Step-by-Step Console Demo</h4><p>Here’s a simplified version that shows how the function keeps getting canceled and replaced:</p><pre>function logMessage(message) {<br>  console.log(&quot;Run:&quot;, message);<br>}<br><br>const debouncedLog = debounce(logMessage, 1000);<br>debouncedLog(&quot;First&quot;);<br>setTimeout(() =&gt; debouncedLog(&quot;Second&quot;), 300);<br>setTimeout(() =&gt; debouncedLog(&quot;Third&quot;), 600);<br>setTimeout(() =&gt; debouncedLog(&quot;Final&quot;), 1200);</pre><p><strong>Timeline:</strong></p><pre>0ms  → &quot;First&quot; scheduled<br>300ms → &quot;First&quot; canceled, &quot;Second&quot; scheduled<br>600ms → &quot;Second&quot; canceled, &quot;Third&quot; scheduled<br>1200ms → &quot;Third&quot; canceled, &quot;Final&quot; scheduled<br>2200ms → &quot;Final&quot; runs</pre><p><strong>Output:</strong></p><pre>Run: Final</pre><p>Only the last call executes after all others were cleared.</p><h3>Summary</h3><ul><li><strong>Debounce</strong> delays function execution until the user stops triggering it.</li><li>setTimeout() schedules code to run after a delay, without pausing other code.</li><li>clearTimeout() cancels a scheduled timer so it doesn’t run.</li><li><strong>The event loop</strong> manages when scheduled tasks (like timeouts) are executed — after the current code finishes.</li><li>.apply() ensures the original function runs with the correct this and arguments.</li></ul><h3>Final Thought</h3><p>Debounce is like saying:</p><blockquote><em>“Wait until the user stops doing something — then run the function once.”</em></blockquote><p>It’s one of the simplest and most powerful tools to make your JavaScript apps smoother, faster, and easier to use.</p><h3>A message from our Founder</h3><p><strong>Hey, </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>Sunil</strong></a><strong> here.</strong> I wanted to take a moment to thank you for reading until the end and for being a part of this community.</p><p>Did you know that our team run these publications as a volunteer effort to over 3.5m monthly readers? <strong>We don’t receive any funding, we do this to support the community. ❤️</strong></p><p>If you want to show some love, please take a moment to <strong>follow me on </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>LinkedIn</strong></a><strong>, </strong><a href="https://tiktok.com/@messyfounder"><strong>TikTok</strong></a>, <a href="https://instagram.com/sunilsandhu"><strong>Instagram</strong></a>. You can also subscribe to our <a href="https://newsletter.plainenglish.io/"><strong>weekly newsletter</strong></a>.</p><p>And before you go, don’t forget to <strong>clap</strong> and <strong>follow</strong> the writer️!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6d362d67ea2f" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/debounce-in-javascript-a-simple-explanation-for-beginners-6d362d67ea2f">Debounce in JavaScript: A Simple Explanation for Beginners</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Promises vs Callbacks in JavaScript — What’s the Difference and Which Should You Use?]]></title>
            <link>https://javascript.plainenglish.io/promises-vs-callbacks-in-javascript-whats-the-difference-and-which-should-you-use-788936b2713e?source=rss-89c83af3c6c0------2</link>
            <guid isPermaLink="false">https://medium.com/p/788936b2713e</guid>
            <category><![CDATA[callback-function]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[callbacks-vs-promises]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[promises-in-javascript]]></category>
            <dc:creator><![CDATA[Jun Ukemori]]></dc:creator>
            <pubDate>Sun, 19 Oct 2025 23:09:33 GMT</pubDate>
            <atom:updated>2025-10-21T07:21:57.273Z</atom:updated>
            <content:encoded><![CDATA[<h3>Promises vs Callbacks in JavaScript — What’s the Difference and Which Should You Use?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*44nSP87LemC_QGWgLTkHdQ.png" /></figure><p>If you’ve written JavaScript for a while, you’ve probably faced this situation:</p><p>You make a network request.<br> You wait for it to finish.<br> Then you want to do something with the result.</p><p>That’s asynchronous programming — when something takes time, like fetching data or reading files, and you don’t want your entire program to freeze while waiting.</p><p>For years, JavaScript handled this with <strong>callbacks</strong> — functions passed as arguments that get executed later.<br>Then came <strong>Promises</strong>, a cleaner way to handle the same thing.</p><p>In this article, you’ll learn what callbacks and promises are, how they differ, and the pros and cons of using promises instead of callbacks.</p><h3>What Are Callbacks?</h3><p>A <strong>callback</strong> is simply a function that gets passed to another function to be executed later.</p><p>Example:</p><pre>function getData(callback) {<br>  setTimeout(() =&gt; {<br>    callback(&quot;Data fetched!&quot;);<br>  }, 1000);<br>}<br><br>getData((message) =&gt; {<br>  console.log(message); // &quot;Data fetched!&quot;<br>});</pre><p>It’s a simple concept — but when your logic grows, callbacks can become difficult to manage.</p><h3>Callback Hell</h3><p>When you have multiple async operations that depend on each other, callbacks can quickly get messy.</p><pre>getUser((user) =&gt; {<br>  getOrders(user, (orders) =&gt; {<br>    getPaymentInfo(orders, (payment) =&gt; {<br>      console.log(&quot;Payment:&quot;, payment);<br>    });<br>  });<br>});</pre><p>This deeply nested pattern is often called <strong>callback hell</strong>.<br> It’s hard to read, hard to maintain, and easy to make mistakes with error handling.</p><h3>Promises</h3><p>A <strong>Promise</strong> is a JavaScript object that represents a value that will be available in the future.</p><p>Think of it as a container for a value that’s not ready yet.<br>When you start an asynchronous operation, you get a promise.</p><p>A Promise is an object that represents a value that may be available now, later, or never.<br> It has three states:</p><ul><li><strong>Pending:</strong> The operation hasn’t completed yet.</li><li><strong>Fulfilled:</strong> The operation completed successfully.</li><li><strong>Rejected:</strong> The operation failed.</li></ul><h4>Example:</h4><pre>const getData = new Promise((resolve, reject) =&gt; {<br>  setTimeout(() =&gt; {<br>    resolve(&quot;Data received&quot;);<br>    // or reject(&quot;Error occurred&quot;);<br>  }, 1000);<br>});<br><br>getData<br>  .then((result) =&gt; console.log(result))<br>  .catch((error) =&gt; console.error(error))<br>  .finally(() =&gt; console.log(&quot;Operation finished&quot;));</pre><p>Here:</p><ul><li>.then() runs when the Promise is successful.</li><li>.catch() runs if there’s an error.</li><li>.finally() runs <strong>no matter what happens</strong> — whether the Promise is fulfilled or rejected. It’s a great place for <strong>cleanup actions</strong> like hiding a loading spinner or closing a connection.</li></ul><h3>Pros of Using Promises</h3><h4>1. Cleaner and More Readable Code</h4><p>Promises help flatten nested callback chains into a linear, readable flow.</p><p><strong>Callback version:</strong></p><pre>getUser((user) =&gt; {<br>  getOrders(user, (orders) =&gt; {<br>    getPaymentInfo(orders, (payment) =&gt; {<br>      console.log(payment);<br>    });<br>  });<br>});</pre><p><strong>Promise version:</strong></p><pre>getUser()<br>  .then(getOrders)<br>  .then(getPaymentInfo)<br>  .then(console.log)<br>  .catch(console.error);</pre><p>The promise version reads top to bottom and is much easier to follow.</p><h4>2. Easier Error Handling</h4><p>With callbacks, you need to handle errors in each layer manually.<br> With promises, you can handle all errors in one place using .catch().</p><pre>getUser()<br>  .then(getOrders)<br>  .then(getPaymentInfo)<br>  .catch((err) =&gt; console.error(&quot;Something failed:&quot;, err));</pre><p>A single .catch() can handle any error in the chain.</p><h4>3. Better Flow Control</h4><p>Promises make it easy to run asynchronous tasks in sequence or in parallel.</p><pre>Promise.all([fetchUser(), fetchPosts(), fetchComments()])<br>  .then(([user, posts, comments]) =&gt; {<br>    console.log(&quot;All done!&quot;);<br>  })<br>  .catch(console.error);</pre><p>Coordinating multiple async tasks like this is much simpler than managing counters or nested callbacks.</p><h4>4. Fewer Common Mistakes</h4><p>With callbacks, you can easily:</p><ul><li>Forget to call the callback</li><li>Call it too early</li><li>Or call it more than once</li></ul><p>Promises avoid these problems because once a promise is resolved or rejected, it can’t change state.</p><h4>5. Works with Async/Await</h4><p>Promises are the foundation of modern async/await syntax, which makes asynchronous code look synchronous.</p><h3>Async/Await — The Modern Way</h3><p>async/await is built on top of Promises and makes asynchronous code look synchronous.<br> It’s easier to read and debug, especially for multiple steps.</p><h4>Example:</h4><pre>async function fetchData() {<br>  try {<br>    const data = await getData();<br>    console.log(data);<br>  } catch (error) {<br>    console.error(error);<br>  } finally {<br>    console.log(&quot;Operation finished&quot;);<br>  }<br>}<br><br>fetchData();</pre><p>This version is even cleaner:</p><ul><li>await pauses execution until the Promise resolves or rejects.</li><li>try...catch handles errors just like .then() and .catch().</li><li>The finally block works exactly the same way as .finally() — it always runs, no matter what.</li></ul><h3>When to Use Which</h3><p><strong>Use Callbacks When:</strong></p><ul><li>The async task is very simple, like a quick animation or a small user event handler.</li><li>You’re working with legacy code or older libraries that rely on callbacks.</li><li>You don’t need to chain multiple asynchronous operations.</li></ul><blockquote><em>Callbacks are easy to write, but for larger tasks or complex flows, they can become messy and hard to maintain.</em></blockquote><p><strong>Use Promises When:</strong></p><ul><li>You have multiple async tasks that depend on each other.</li><li>You want cleaner and more maintainable code.</li><li>You need centralized error handling.</li><li>You want to run tasks in parallel (using Promise.all() or similar).</li><li>You’re using async/await in modern JavaScript.</li></ul><blockquote><em>Promises are generally the better long-term choice for most new codebases, making async code easier to read and less error-prone</em></blockquote><h3>Best Practices for Promises</h3><ul><li>Always <strong>return</strong> your promises from functions.</li><li>Always include a .catch() or wrap with try...catch if using async/await.</li><li>Don’t mix callbacks and promises in the same function.</li><li>Use Promise.all() or Promise.allSettled() for multiple async tasks.</li><li>Prefer async/await when possible for readability.</li></ul><h3>Conclusion</h3><p>Promises make your asynchronous code easier to read, maintain, and debug.<br> They simplify error handling and provide powerful tools for coordinating multiple async operations.</p><p>But like any tool, they have trade-offs. For simple or legacy cases, callbacks still work fine.<br> For modern JavaScript development, though, Promises (and async/await) are the standard way forward.</p><p>If you’re learning, start by rewriting a simple callback function into a promise, then try converting that into async/await.<br> You’ll quickly see how much cleaner and easier your code becomes.</p><h3>A message from our Founder</h3><p><strong>Hey, </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>Sunil</strong></a><strong> here.</strong> I wanted to take a moment to thank you for reading until the end and for being a part of this community.</p><p>Did you know that our team run these publications as a volunteer effort to over 3.5m monthly readers? <strong>We don’t receive any funding, we do this to support the community. ❤️</strong></p><p>If you want to show some love, please take a moment to <strong>follow me on </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>LinkedIn</strong></a><strong>, </strong><a href="https://tiktok.com/@messyfounder"><strong>TikTok</strong></a>, <a href="https://instagram.com/sunilsandhu"><strong>Instagram</strong></a>. You can also subscribe to our <a href="https://newsletter.plainenglish.io/"><strong>weekly newsletter</strong></a>.</p><p>And before you go, don’t forget to <strong>clap</strong> and <strong>follow</strong> the writer️!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=788936b2713e" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/promises-vs-callbacks-in-javascript-whats-the-difference-and-which-should-you-use-788936b2713e">Promises vs Callbacks in JavaScript — What’s the Difference and Which Should You Use?</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Array.prototype.call by Implementing myCall Step by Step]]></title>
            <link>https://javascript.plainenglish.io/creating-mycall-in-javascript-beginner-friendly-guide-d2dd7b8833bc?source=rss-89c83af3c6c0------2</link>
            <guid isPermaLink="false">https://medium.com/p/d2dd7b8833bc</guid>
            <category><![CDATA[call-method]]></category>
            <category><![CDATA[apply-method]]></category>
            <category><![CDATA[bind-method]]></category>
            <category><![CDATA[javascript-interview]]></category>
            <category><![CDATA[javascript-this]]></category>
            <dc:creator><![CDATA[Jun Ukemori]]></dc:creator>
            <pubDate>Wed, 15 Oct 2025 00:24:59 GMT</pubDate>
            <atom:updated>2025-10-20T12:48:01.510Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-qmyVsHUHrgdMaPcuXGxng.png" /></figure><p>In JavaScript, functions are more than just code — they can belong to objects. Normally, thisinside a function refers to the object that owns it. Sometimes, though, you want a function to temporarily belong to a different object.</p><p>This is where call(), apply(), and bind() come in. In this article, we’ll explain them and show how to create your own myCall().</p><h3>What is call?</h3><p>The call() method calls a function with a specific this value, passing arguments individually.</p><p><strong>Example:</strong></p><pre>function greet(greeting, emoji) {<br>  console.log(`${greeting}, I am ${this.name} ${emoji}`);<br>}<br><br>const alice = { name: &quot;Alice&quot; };<br><br>greet.call(alice, &quot;Hello&quot;, &quot;😊&quot;); // Hello, I am Alice 😊</pre><ul><li>this temporarily becomes alice.</li><li>Arguments &quot;Hello&quot; and &quot;😊&quot; are passed one by one.</li></ul><p><strong>Key idea:</strong> call() lets you <strong>control which object a function works for</strong>.</p><h3>Approach 1: Using bind</h3><h4>How bind works</h4><ul><li>bind() creates a new function permanently tied to a specific object.</li><li>The function does not run immediately.</li><li>You can also pass arguments while binding, which will be used when the function runs.</li></ul><p><strong>example:</strong></p><pre>const person = { name: &quot;Alice&quot;, age: 25 };<br><br>function sayHello(greeting) {<br>  console.log(`${greeting}! My name is ${this.name} and I am ${this.age} years old.`);<br>}<br><br>// Without bind, `this` is undefined<br>sayHello(); // My name is undefined and I am undefined years old<br><br>// Bind `this` to person<br>const sayHelloToAlice = sayHello.bind(person);<br><br>// Run it later<br>sayHelloToAlice(&quot;Hello&quot;); // Hello! My name is Alice and I am 25 years old</pre><p><strong>Creating myCall() with bind:</strong></p><pre>Function.prototype.myCall = function(thisArg, ...args) {<br>  return this.bind(thisArg)(...args);<br>};<br><br>function doubleAge(multiplier = 1) {<br>  return this.age * multiplier;<br>}<br><br>console.log(doubleAge.myCall(person));    // 25<br>console.log(doubleAge.myCall(person, 3)); // 75</pre><p><strong>Explanation:</strong></p><ul><li>this.bind(thisArg) → creates a new function bound to person.</li><li>(...args) → immediately runs the bound function with the arguments.</li><li>bind is perfect here because it can set this for us, and we run it immediately to mimic call().</li></ul><h3>Approach 2: Using apply</h3><h4>How apply works</h4><ul><li>apply() is very similar to call(), but it takes arguments as an array.</li><li>It runs the function immediately.</li></ul><p><strong>example:</strong></p><pre>const dog = { name: &quot;Buddy&quot;, age: 5 };<br><br>function introduce(petType, emoji) {<br>  console.log(`I have a ${petType} named ${this.name} ${emoji}, and he is ${this.age} years old.`);<br>}<br><br>// Use apply to run function immediately with `this` set to dog<br>introduce.apply(dog, [&quot;dog&quot;, &quot;🐶&quot;]);<br>// Output: I have a dog named Buddy 🐶, and he is 5 years old</pre><p><strong>Creating myCall() with apply:</strong></p><pre>const dog = { age: 5 };<br><br>function multiplyAge(multiplier = 1) {<br>  return this.age * multiplier;<br>}<br><br>// Using our custom myCall<br>Function.prototype.myCall = function(thisArg, ...args) {<br>  return this.apply(thisArg, args);<br>};<br><br>console.log(multiplyAge.myCall(dog));      // 5  → multiplier defaults to 1<br>console.log(multiplyAge.myCall(dog, 2));   // 10 → 5 * 2<br>console.log(multiplyAge.myCall(dog, 3));   // 15 → 5 * 3</pre><p><strong>Explanation:</strong></p><ul><li>...args collects arguments into an array.</li><li>this.apply(thisArg, args) runs the function immediately, spreading the array as individual arguments.</li><li>apply is a natural alternative to call when working with arrays of arguments.</li></ul><h3>Summary</h3><p>By creating your own myCall() function, you not only learn how to mimic the behavior of call(), but you also gain a deeper understanding of how this, call, apply, and bind work in JavaScript.</p><ul><li>call() → immediately runs a function with a specific this and comma-separated arguments.</li><li>apply() → immediately runs a function with a specific this and arguments as an array.</li><li>bind() → creates a new function permanently bound to a specific this, run later.</li><li>myCall() → a hands-on way to explore how call() works under the hood.</li></ul><p>Key takeaway: Learning to implement myCall() helps you understand the mechanics of this and function context in JavaScript, which is essential for writing flexible and powerful code.</p><h3>A message from our Founder</h3><p><strong>Hey, </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>Sunil</strong></a><strong> here.</strong> I wanted to take a moment to thank you for reading until the end and for being a part of this community.</p><p>Did you know that our team run these publications as a volunteer effort to over 3.5m monthly readers? <strong>We don’t receive any funding, we do this to support the community. ❤️</strong></p><p>If you want to show some love, please take a moment to <strong>follow me on </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>LinkedIn</strong></a><strong>, </strong><a href="https://tiktok.com/@messyfounder"><strong>TikTok</strong></a>, <a href="https://instagram.com/sunilsandhu"><strong>Instagram</strong></a>. You can also subscribe to our <a href="https://newsletter.plainenglish.io/"><strong>weekly newsletter</strong></a>.</p><p>And before you go, don’t forget to <strong>clap</strong> and <strong>follow</strong> the writer️!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d2dd7b8833bc" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/creating-mycall-in-javascript-beginner-friendly-guide-d2dd7b8833bc">Understanding Array.prototype.call by Implementing myCall Step by Step</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Array.prototype.reduce by Implementing myReduce Step by Step]]></title>
            <link>https://javascript.plainenglish.io/understanding-array-prototype-reduce-by-implementing-myreduce-step-by-step-c436f5954085?source=rss-89c83af3c6c0------2</link>
            <guid isPermaLink="false">https://medium.com/p/c436f5954085</guid>
            <category><![CDATA[callback-function]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[javascript-reduce]]></category>
            <category><![CDATA[javascript-array-methods]]></category>
            <category><![CDATA[closure]]></category>
            <dc:creator><![CDATA[Jun Ukemori]]></dc:creator>
            <pubDate>Tue, 14 Oct 2025 00:15:53 GMT</pubDate>
            <atom:updated>2025-10-15T02:33:25.605Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*t_MKSvF68HkOq1Wz" /></figure><p>reduce is a powerful array method that turns an array of values into a single accumulated result. For example, summing [1, 2, 3] into 6.</p><p>We’ll implement our own version, myReduce, and break down how it works line by line.</p><h3>The code</h3><pre>Array.prototype.myReduce = function (callbackFn, initialValue) {<br>  const noInitialValue = initialValue === undefined;<br>  const len = this.length;<br><br>  if (noInitialValue &amp;&amp; len === 0) {<br>    throw new TypeError(&#39;Reduce of empty array with no initial value&#39;);<br>  }<br><br>  let acc = noInitialValue ? this[0] : initialValue;<br>  let startingIndex = noInitialValue ? 1 : 0;<br><br>  for (let k = startingIndex; k &lt; len; k++) {<br>    if (Object.hasOwn(this, k)) {<br>      acc = callbackFn(acc, this[k], k, this);<br>    }<br>  }<br><br>  return acc;<br>};</pre><h3>Step-by-step explanation</h3><h4>Attach method to Array.prototype</h4><pre>Array.prototype.myReduce = function (...)</pre><ul><li>Adds myReduce to all arrays.</li><li>Example: [1,2,3].myReduce(...) works because arrays share the Array.prototype toolbox.</li></ul><h4>Check if initial value exists</h4><pre>const noInitialValue = initialValue === undefined;</pre><ul><li>Detects whether the user passed an initialValue.</li><li>Important because reduce behaves differently with and without it.</li></ul><h4>Get array length</h4><pre>const len = this.length;</pre><ul><li>Stores the length of the array to loop over later.</li><li>this refers to the array calling myReduce.</li></ul><h4>Handle empty array without initial value</h4><pre>if (noInitialValue &amp;&amp; len === 0) {<br>  throw new TypeError(&#39;Reduce of empty array with no initial value&#39;);<br>}</pre><ul><li>If array is empty and no initial value is provided, reduce can’t produce a result → throw error.</li></ul><h4>Set initial accumulator and starting index</h4><pre>let acc = noInitialValue ? this[0] : initialValue;<br>let startingIndex = noInitialValue ? 1 : 0;</pre><ul><li>acc = accumulator (the running total).</li><li>If there’s no initial value, use the <strong>first element</strong> of the array.</li><li>startingIndex = where the loop should start:</li><li>1 if first element is used as accumulator.</li><li>0 if we have an initial value.</li></ul><h4>Loop through the array</h4><pre>for (let k = startingIndex; k &lt; len; k++) {<br>  if (Object.hasOwn(this, k)) {<br>    acc = callbackFn(acc, this[k], k, this);<br>  }<br>}</pre><ol><li>Loops from startingIndex to len - 1.</li><li>Object.hasOwn(this, k) → checks that the array has a value at this index (skips holes in sparse arrays).</li><li>Calls the callbackFn with:</li></ol><ul><li>acc = accumulator</li><li>this[k] = current element</li><li>k = current index</li><li>this = the array itself</li></ul><p>4. Sets acc to the result of the callback.</p><h4>Return the final result</h4><pre>return acc;</pre><ul><li>After all iterations, acc contains the reduced value.</li></ul><h3>The Callback Function Explained</h3><p>This is the <strong>most important part</strong> — it defines <em>how</em> your array gets reduced.</p><p>In your myReduce function, you pass in something like:</p><pre>[1, 2, 3].myReduce((acc, curr) =&gt; acc + curr, 0);</pre><p>Here:</p><ul><li>callbackFn = (acc, curr) =&gt; acc + curr</li><li>acc = accumulator (the running result)</li><li>curr = current element</li><li>k = current index</li><li>this = the whole array</li></ul><p>Each time the loop runs:</p><pre>acc = callbackFn(acc, this[k], k, this);</pre><p>it updates the accumulator based on your callback’s logic.</p><h4>Example</h4><pre>const result = [1, 2, 3].myReduce((acc, curr) =&gt; acc + curr, 0);<br>// Step 1: acc=0, curr=1 → acc=1<br>// Step 2: acc=1, curr=2 → acc=3<br>// Step 3: acc=3, curr=3 → acc=6<br>console.log(result); // 6</pre><h4>How “this” works</h4><ul><li>Inside myReduce, this is the array that called the method.</li></ul><pre>[1,2,3].myReduce(function(a,b){ console.log(this); return a+b; }, 0);</pre><ul><li>Prints: [1,2,3]</li></ul><h3>How Object.hasOwn() works</h3><ul><li>Checks whether the array <strong>actually has a value at an index</strong>, skipping holes:</li></ul><pre>const arr = [1, , 3]; // index 1 is missing<br>Object.hasOwn(arr, 1); // false</pre><ul><li>This prevents errors when using sparse arrays.</li></ul><h3>Examples</h3><h4>Normal usage</h4><pre>[1, 2, 3].myReduce((prev, curr) =&gt; prev + curr, 0); // 6<br>[1, 2, 3].myReduce((prev, curr) =&gt; prev + curr, 4); // 10</pre><h4>Without initial value</h4><pre>[1, 2, 3].myReduce((prev, curr) =&gt; prev + curr); // 6</pre><h4>Sparse array</h4><pre>const arr = [ , 2, , 4]; <br>arr.myReduce((acc, curr) =&gt; acc + curr, 0); // 6</pre><h4>Empty array with initial value</h4><pre>[].myReduce((acc, curr) =&gt; acc + curr, 10); // 10</pre><h4>Empty array without initial value → error</h4><pre>[].myReduce((acc, curr) =&gt; acc + curr); // TypeError</pre><h3>Why building myReduce matters</h3><p>When you implement reduce yourself:</p><ul><li>You understand how <strong>accumulation works</strong> step by step.</li><li>You learn how <strong>callbacks</strong> and <strong>closures</strong> interact.</li><li>You see how <strong>array methods</strong> handle special cases (like empty arrays).</li></ul><p>It’s not just a coding test — it’s a powerful lesson in how JavaScript’s array methods work internally.</p><h3>A message from our Founder</h3><p><strong>Hey, </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>Sunil</strong></a><strong> here.</strong> I wanted to take a moment to thank you for reading until the end and for being a part of this community.</p><p>Did you know that our team run these publications as a volunteer effort to over 3.5m monthly readers? <strong>We don’t receive any funding, we do this to support the community. ❤️</strong></p><p>If you want to show some love, please take a moment to <strong>follow me on </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>LinkedIn</strong></a><strong>, </strong><a href="https://tiktok.com/@messyfounder"><strong>TikTok</strong></a>, <a href="https://instagram.com/sunilsandhu"><strong>Instagram</strong></a>. You can also subscribe to our <a href="https://newsletter.plainenglish.io/"><strong>weekly newsletter</strong></a>.</p><p>And before you go, don’t forget to <strong>clap</strong> and <strong>follow</strong> the writer️!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c436f5954085" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/understanding-array-prototype-reduce-by-implementing-myreduce-step-by-step-c436f5954085">Understanding Array.prototype.reduce by Implementing myReduce Step by Step</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Event Bubbling in JavaScript Explained Clearly]]></title>
            <link>https://javascript.plainenglish.io/event-bubbling-in-javascript-explained-clearly-8c70552d337b?source=rss-89c83af3c6c0------2</link>
            <guid isPermaLink="false">https://medium.com/p/8c70552d337b</guid>
            <category><![CDATA[javascript-events]]></category>
            <category><![CDATA[event-delegation]]></category>
            <category><![CDATA[addeventlistener]]></category>
            <category><![CDATA[event-bubbling]]></category>
            <category><![CDATA[event-propagation]]></category>
            <dc:creator><![CDATA[Jun Ukemori]]></dc:creator>
            <pubDate>Sun, 12 Oct 2025 06:11:24 GMT</pubDate>
            <atom:updated>2025-10-14T07:24:54.496Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WEkxAGJcxG0wI6s0" /></figure><p>Event bubbling is a fundamental concept in how the browser handles DOM events. It explains <strong>how events propagate</strong> from the element that was actually interacted with up through its ancestors in the DOM tree.</p><h3>What Is Event Bubbling?</h3><p>Event bubbling means that when an event occurs on a target element, it <strong>first runs the event handler on that element</strong>, and then it <strong>bubbles up</strong> — triggering handlers on ancestor elements one by one, until it reaches the root of the document.</p><p>This gives parent elements the opportunity to react to events that originally happened deep inside their child elements.</p><h3>The Bubbling Phase in Action</h3><p>After an event is dispatched to its target, it enters the <strong>bubbling phase</strong>. During this phase, the event travels upward from the target element through its ancestors, and each ancestor’s event listener (if any) gets a chance to run.</p><p>By default, addEventListener(type, handler) listens for events in the <strong>bubbling phase</strong>, unless explicitly told to use capturing.</p><h3>Example</h3><pre>&lt;div id=&quot;parent&quot;&gt;<br>  &lt;button id=&quot;child&quot;&gt;Click me!&lt;/button&gt;<br>&lt;/div&gt;</pre><pre>const parent = document.getElementById(&#39;parent&#39;);<br>const child = document.getElementById(&#39;child&#39;);<br><br>parent.addEventListener(&#39;click&#39;, () =&gt; {<br>  console.log(&#39;Parent element clicked&#39;);<br>});<br><br>child.addEventListener(&#39;click&#39;, () =&gt; {<br>  console.log(&#39;Child element clicked&#39;);<br>});</pre><p><strong>Output when clicking the child:</strong></p><pre>Child element clicked<br>Parent element clicked</pre><p>The event first fires on the child, then bubbles up to the parent.</p><h3>How to Stop Bubbling</h3><p>Sometimes, you may not want an event to bubble up beyond a certain element.<br> You can stop it using event.stopPropagation().</p><h4>Example</h4><pre>child.addEventListener(&#39;click&#39;, (event) =&gt; {<br>  console.log(&#39;Child element clicked&#39;);<br>  event.stopPropagation(); // Prevent parent’s handler from running<br>});</pre><p>Now, when you click the child element, only &quot;Child element clicked&quot; appears in the console.<br> The parent listener no longer fires.</p><h3>Event Delegation</h3><p>Event bubbling enables a very powerful pattern known as <strong>event delegation</strong>.</p><p>Instead of adding separate event listeners to every single child element, you can add <strong>just one listener</strong> to a parent element and use the bubbling event to detect which child was interacted with.</p><h4>Example</h4><pre>parent.addEventListener(&#39;click&#39;, (event) =&gt; {<br>  if (event.target &amp;&amp; event.target.id === &#39;child&#39;) {<br>    console.log(&#39;Child element clicked&#39;);<br>  }<br>});</pre><p>When you click the child button, the parent’s single listener detects it through event.target.<br> This pattern simplifies code, improves performance, and works even if new child elements are dynamically added later.</p><h3>Use Case 1: Handling Actions in a Dynamic List</h3><p>One of the most practical uses of bubbling is <strong>event delegation</strong>.</p><p>Instead of adding an event listener to every single element, you attach one listener to a parent container and let the event bubble up.<br>Inside that listener, you check where the event originally occurred.</p><p>Imagine a list of items that users can favorite or remove dynamically:</p><pre>&lt;ul id=&quot;item-list&quot;&gt;<br>  &lt;li data-id=&quot;1&quot;&gt;&lt;button class=&quot;fav-btn&quot;&gt;☆ Favorite&lt;/button&gt;&lt;/li&gt;<br>  &lt;li data-id=&quot;2&quot;&gt;&lt;button class=&quot;fav-btn&quot;&gt;☆ Favorite&lt;/button&gt;&lt;/li&gt;<br>&lt;/ul&gt;</pre><pre>const list = document.getElementById(&#39;item-list&#39;);<br><br>list.addEventListener(&#39;click&#39;, (event) =&gt; {<br>  if (event.target.classList.contains(&#39;fav-btn&#39;)) {<br>    const item = event.target.closest(&#39;li&#39;);<br>    console.log(`Favorited item ${item.dataset.id}`);<br>    event.target.textContent = &#39;★ Favorited&#39;;<br>  }<br>});</pre><p><strong>Why this works well:</strong></p><ul><li>Only <strong>one</strong> listener is needed for the entire list.</li><li>Works even if new items are added later with JavaScript.</li><li>Keeps code efficient and clean.</li></ul><p>This is the essence of <strong>event delegation</strong> — taking advantage of bubbling for flexible, scalable event handling.</p><h3>Use Case 2: Managing Nested UI Components</h3><p>Event bubbling also helps in <strong>managing hierarchical UI structures</strong>,<br>such as when you have multiple layers of interactive components.</p><p>For example, suppose you have a <strong>post container</strong> with a “Like” button inside it.<br> You want clicks on the container to open a detail view,<br> but clicks on the like button should <em>not</em> trigger that container action.</p><pre>&lt;div id=&quot;post&quot;&gt;<br>  &lt;button id=&quot;like&quot;&gt;Like&lt;/button&gt;<br>&lt;/div&gt;</pre><pre>const post = document.getElementById(&#39;post&#39;);<br>const like = document.getElementById(&#39;like&#39;);<br><br>post.addEventListener(&#39;click&#39;, () =&gt; {<br>  console.log(&#39;Post clicked → open detail view&#39;);<br>});<br><br>like.addEventListener(&#39;click&#39;, (event) =&gt; {<br>  console.log(&#39;Liked the post&#39;);<br>  event.stopPropagation(); // prevent triggering post click<br>});</pre><p><strong>Result:</strong></p><ul><li>Clicking the <strong>post container</strong> logs <em>“Post clicked → open detail view.”</em></li><li>Clicking the <strong>Like button</strong> logs <em>“Liked the post.”</em><br> The event stops there, so the container’s listener doesn’t also fire.</li></ul><p>This use case mirrors how bubbling is often used (and controlled) in real web apps — like buttons inside cards, comments, or posts that have their own click handlers.</p><h3>Benefits &amp; Pitfalls</h3><h4>Benefits</h4><ul><li><strong>Cleaner code:</strong> Fewer event listeners to maintain.</li><li><strong>Better performance:</strong> Centralized event handling reduces overhead.</li><li><strong>Dynamic flexibility:</strong> Works for elements added after page load.</li></ul><h4>Pitfalls</h4><ul><li><strong>Unintended handling:</strong> Parent elements might respond to child events you didn’t mean to catch.</li><li><strong>Order of execution:</strong> Handlers run in ancestor order, which can cause confusion if multiple layers respond.</li><li><strong>Over-delegation:</strong> Attaching listeners too high in the DOM can make them respond to irrelevant events.</li></ul><h3>Summary</h3><p>Event bubbling describes how events propagate from a specific target element up through its ancestors.<br> It’s the default behavior of most DOM events in modern browsers and is essential to patterns like <strong>event delegation</strong>.</p><p>By understanding how to use (and control) bubbling effectively, you can write cleaner, more efficient, and more flexible JavaScript code.</p><h3>A message from our Founder</h3><p><strong>Hey, </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>Sunil</strong></a><strong> here.</strong> I wanted to take a moment to thank you for reading until the end and for being a part of this community.</p><p>Did you know that our team run these publications as a volunteer effort to over 3.5m monthly readers? <strong>We don’t receive any funding, we do this to support the community. ❤️</strong></p><p>If you want to show some love, please take a moment to <strong>follow me on </strong><a href="https://linkedin.com/in/sunilsandhu"><strong>LinkedIn</strong></a><strong>, </strong><a href="https://tiktok.com/@messyfounder"><strong>TikTok</strong></a>, <a href="https://instagram.com/sunilsandhu"><strong>Instagram</strong></a>. You can also subscribe to our <a href="https://newsletter.plainenglish.io/"><strong>weekly newsletter</strong></a>.</p><p>And before you go, don’t forget to <strong>clap</strong> and <strong>follow</strong> the writer️!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c70552d337b" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/event-bubbling-in-javascript-explained-clearly-8c70552d337b">Event Bubbling in JavaScript Explained Clearly</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>