<?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 Prateek Singh on Medium]]></title>
        <description><![CDATA[Stories by Prateek Singh on Medium]]></description>
        <link>https://medium.com/@prateekchadha15?source=rss-61b6d0894c80------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*yDIu6hBPlWlwi4d5wLNnxw.jpeg</url>
            <title>Stories by Prateek Singh on Medium</title>
            <link>https://medium.com/@prateekchadha15?source=rss-61b6d0894c80------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 11:13:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@prateekchadha15/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 let, const, and var in JavaScript – Scope & Hoisting Demystified]]></title>
            <link>https://medium.com/@prateekchadha15/understanding-let-const-and-var-in-javascript-scope-hoisting-demystified-63165eb982b3?source=rss-61b6d0894c80------2</link>
            <guid isPermaLink="false">https://medium.com/p/63165eb982b3</guid>
            <dc:creator><![CDATA[Prateek Singh]]></dc:creator>
            <pubDate>Sun, 08 Jun 2025 17:37:21 GMT</pubDate>
            <atom:updated>2025-06-08T17:37:21.847Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*7WSN5XhwcPqOXA4nbiyhbA.png" /></figure><p>In JavaScript, how you declare variables matters. The difference between var, let, and const can impact how your code behaves — and it’s a favorite interview topic.</p><p>Let’s break it down clearly with examples.</p><h3>What is Scope?</h3><p><strong>Scope</strong> refers to where a variable is accessible in your code.</p><ul><li><strong>Function scope</strong>: Accessible only inside the function where it is defined.</li><li><strong>Block scope</strong>: Accessible only inside a { ... } block (like if, for, or {}).</li></ul><h3>1. var – Function Scoped &amp; Hoisted</h3><h3>Characteristics:</h3><ul><li>Scoped to the nearest <strong>function</strong>, not block.</li><li>Can be <strong>re-declared</strong> and <strong>updated</strong>.</li><li><strong>Hoisted</strong> to the top of the function or global scope, initialized as undefined.</li></ul><h3>Example:</h3><pre>function testVar() {<br>  if (true) {<br>    var name = &quot;Prateek&quot;;<br>  }<br>  console.log(name); // ✅ Works — function-scoped<br>}<br>testVar();</pre><h3>Hoisting with var:</h3><pre>console.log(score); // undefined (not error!)<br>var score = 100;</pre><h3>2. let – Block Scoped, Not Hoisted to Top</h3><h3>Characteristics:</h3><ul><li>Scoped to the nearest <strong>block </strong><strong>{}</strong></li><li>Can be <strong>updated</strong> but <strong>not re-declared</strong> in the same scope.</li><li><strong>Hoisted</strong>, but not initialized → leads to <strong>TDZ (Temporal Dead Zone)</strong></li></ul><h3>Example:</h3><pre>if (true) {<br>  let name = &quot;Prateek&quot;;<br>}<br>console.log(name); // ❌ ReferenceError: name is not defined</pre><h3>TDZ Example:</h3><pre>console.log(a); // ❌ ReferenceError<br>let a = 10;</pre><h3>3. const – Block Scoped, Immutable Binding</h3><h3>Characteristics:</h3><ul><li>Also block scoped (like let)</li><li><strong>Must be initialized</strong> at declaration</li><li>Cannot be <strong>reassigned</strong> or <strong>re-declared</strong></li></ul><pre>const PI = 3.14;<br>PI = 3.14159; // ❌ TypeError</pre><h3>But objects can be mutated:</h3><pre>const user = { name: &quot;Alice&quot; };<br>user.name = &quot;Bob&quot;; // ✅ Allowed</pre><h3>Best Practices</h3><ul><li>Use const by default for constants and never reassigned variables.</li><li>Use let for variables that need to change.</li><li>Avoid var in modern JavaScript (except in legacy code).</li></ul><h3>* Top JavaScript Interview Questions on var, let, and const</h3><p><strong>1. Why is </strong><strong>var considered function-scoped while </strong><strong>let and </strong><strong>const are block-scoped?</strong></p><ul><li>var is accessible <strong>anywhere inside the function</strong> it&#39;s declared.</li><li>let and const are only accessible <strong>within the block </strong><strong>{}</strong> where they&#39;re declared.</li></ul><pre>function example() {<br>  if (true) {<br>    var x = 10;<br>    let y = 20;<br>  }<br>  console.log(x); // ✅ 10<br>  console.log(y); // ❌ ReferenceError<br>}</pre><p><strong>2. What happens when you access a </strong><strong>let or </strong><strong>const variable before its declaration?</strong></p><ul><li>You get a <strong>ReferenceError</strong> due to the <strong>Temporal Dead Zone</strong>.</li></ul><pre>console.log(a); // ❌ ReferenceError<br>let a = 5;</pre><p><strong>3. Explain the concept of Temporal Dead Zone (TDZ).</strong></p><p>TDZ is the period between entering the block and the variable’s actual declaration where accessing the variable causes an error.</p><pre>{<br>  // TDZ starts here<br>  console.log(num); // ❌ ReferenceError<br>  let num = 5;<br>}</pre><p><strong>4. Can you re-declare or reassign a variable declared with </strong><strong>let or </strong><strong>const?</strong></p><ul><li>let: <strong>Can be reassigned</strong>, but <strong>cannot be re-declared</strong> in the same scope.</li><li>const: <strong>Cannot be reassigned or re-declared</strong>.</li></ul><pre>let x = 10;<br>x = 20;        // ✅<br>let x = 30;    // ❌ SyntaxError<br><br>const y = 100;<br>y = 200;       // ❌ TypeError<br>const y = 300; // ❌ SyntaxError</pre><p><strong>5. What is hoisting, and how does it differ for </strong><strong>var, </strong><strong>let, and </strong><strong>const?</strong></p><p><strong>All variables are hoisted</strong>, but:</p><ul><li>var is <strong>initialized as </strong><strong>undefined</strong></li><li>let and const remain in the <strong>TDZ</strong> until declared</li></ul><pre>console.log(a); // undefined<br>var a = 10;<br><br>console.log(b); // ❌ ReferenceError<br>let b = 20;<br>console.log(c); // ❌ ReferenceError<br>const c = 30;</pre><p><strong>6. What is the output of this code?</strong></p><pre>console.log(x);<br>let x = 10;</pre><p><strong>Answer:</strong> ReferenceError: Cannot access &#39;x&#39; before initialization</p><p>Explanation: x is hoisted but is in the <strong>Temporal Dead Zone</strong>.</p><p><strong>7. Is it possible to mutate a </strong><strong>const object or array? Explain with example.</strong></p><p>Yes! const only makes the <strong>binding immutable</strong>, not the <strong>content</strong>.</p><pre>const person = { name: &quot;Alice&quot; };<br>person.name = &quot;Bob&quot;; // ✅ Allowed<br>console.log(person.name); // Bob<br><br>const arr = [1, 2, 3];<br>arr.push(4); // ✅ Allowed<br>console.log(arr); // [1, 2, 3, 4]</pre><p><strong>8. Which variable declaration is safer to use in modern JavaScript and why?</strong></p><ul><li><strong>Use </strong><strong>const by default</strong>, because it prevents accidental reassignments.</li><li>Use let when you know the value needs to change.</li><li><strong>Avoid </strong><strong>var</strong> due to scoping and hoisting quirks.</li></ul><p><strong>9. Print numbers </strong><strong>0 to 4 with a delay using </strong><strong>setTimeout</strong></p><p>Using var (Unexpected Output)</p><pre>for (var i = 0; i &lt; 5; i++) {<br>  setTimeout(() =&gt; {<br>    console.log(&quot;var:&quot;, i);<br>  }, 1000);<br>}</pre><p>Output after 1 second:</p><pre>var: 5<br>var: 5<br>var: 5<br>var: 5<br>var: 5</pre><h4>Why?</h4><ul><li>var is <strong>function-scoped</strong>. All callbacks <strong>share the same </strong><strong>i</strong>, which ends at 5 after the loop completes.</li><li>So all setTimeouts print 5.</li></ul><p>Using let (Correct Output)</p><pre>for (let i = 0; i &lt; 5; i++) {<br>  setTimeout(() =&gt; {<br>    console.log(&quot;let:&quot;, i);<br>  }, 1000);<br>}</pre><p>Output after 1 second:</p><pre>let: 0<br>let: 1<br>let: 2<br>let: 3<br>let: 4</pre><h4>Why?</h4><ul><li>let is <strong>block-scoped</strong>, so each loop iteration gets a <strong>fresh copy of </strong><strong>i</strong>.</li><li>setTimeout closure captures the correct i in each iteration.</li></ul><h3>** Summary</h3><p>Choosing between var, let, and const affects:</p><ul><li>Scope visibility</li><li>Code readability</li><li>Bug prevention</li></ul><p>Stick to let and const in modern code. Avoid var unless maintaining older codebases.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=63165eb982b3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Debouncing and Throttling in JavaScript: A Complete Guide]]></title>
            <link>https://medium.com/@prateekchadha15/debouncing-and-throttling-in-javascript-a-complete-guide-30173fe77875?source=rss-61b6d0894c80------2</link>
            <guid isPermaLink="false">https://medium.com/p/30173fe77875</guid>
            <dc:creator><![CDATA[Prateek Singh]]></dc:creator>
            <pubDate>Mon, 13 Jan 2025 18:08:38 GMT</pubDate>
            <atom:updated>2025-01-13T18:08:38.288Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tpzOKtQyMCqHhLEXdauYag.png" /></figure><p>In JavaScript, managing frequent and repetitive events, such as scrolling, typing, or resizing a window, is critical for maintaining application performance and ensuring a smooth user experience. Two popular techniques to control how functions are executed in response to these events are <strong>debouncing</strong> and <strong>throttling</strong>.</p><h3>What is Debouncing?</h3><p>Debouncing is a technique that delays the execution of a function until after a specified amount of time has passed since it was last called. If the function is called again during this delay, the timer resets.</p><h4>Use Cases for Debouncing</h4><ul><li><strong>Search Inputs</strong>: Triggering an API call only after the user has stopped typing.</li><li><strong>Resize Events</strong>: Adjusting the layout after the user finishes resizing the browser window.</li><li><strong>Button Clicks</strong>: Preventing multiple rapid clicks from executing the same action.</li></ul><h4>How Debouncing Works</h4><p>When an event occurs (e.g., typing in a text box), a timer starts. If the event happens again before the timer completes, the timer resets. The function executes only after the timer finishes.</p><h4>Implementation</h4><p>Here’s an example of a debounce function:</p><pre>function debounce(func, delay) {<br>  let timer;<br>  return function (...args) {<br>    clearTimeout(timer); // Clear the previous timer<br>    timer = setTimeout(() =&gt; {<br>      func.apply(this, args); // Call the function after the delay<br>    }, delay);<br>  };<br>}<br><br>// Usage Example<br>const handleInput = debounce((text) =&gt; {<br>  console.log(&quot;Searching for:&quot;, text);<br>}, 300);<br>document.getElementById(&quot;search&quot;).addEventListener(&quot;input&quot;, (e) =&gt; {<br>  handleInput(e.target.value);<br>});</pre><h3>What is Throttling?</h3><p>Throttling is a technique that ensures a function is executed at most once every specified time interval, regardless of how often the event occurs.</p><h4>Use Cases for Throttling</h4><ul><li><strong>Scroll Events</strong>: Running a function periodically as the user scrolls.</li><li><strong>Resize Events</strong>: Updating the UI during window resizing without overloading the system.</li><li><strong>Form Submissions</strong>: Limiting the number of submissions during rapid clicks on a submit button.</li></ul><h4>How Throttling Works</h4><p>When an event occurs, the function executes immediately and then ignores subsequent events for the specified interval.</p><h4>Implementation</h4><p>Here’s an example of a throttle function:</p><pre>function throttle(func, limit) {<br>  let lastFunc;<br>  let lastRan;<br>  return function (...args) {<br>    const context = this;<br>    if (!lastRan) {<br>      func.apply(context, args); // Call immediately if first time<br>      lastRan = Date.now();<br>    } else {<br>      clearTimeout(lastFunc); // Clear any pending calls<br>      lastFunc = setTimeout(() =&gt; {<br>        if (Date.now() - lastRan &gt;= limit) {<br>          func.apply(context, args); // Call after the limit<br>          lastRan = Date.now();<br>        }<br>      }, limit - (Date.now() - lastRan));<br>    }<br>  };<br>}<br><br>// Usage Example<br>const handleScroll = throttle(() =&gt; {<br>  console.log(&quot;Scrolling...&quot;);<br>}, 1000);<br>window.addEventListener(&quot;scroll&quot;, handleScroll);<br></pre><p><strong>Debouncing vs. Throttling</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/715/1*W_aQ2Q0ONRxFB32IR8lz3Q.png" /></figure><h3>Practical Examples</h3><h4>Debouncing Example: Search Bar</h4><pre>const searchInput = document.getElementById(&quot;search&quot;);<br><br>const fetchSearchResults = debounce((query) =&gt; {<br>  console.log(`Fetching results for: ${query}`);<br>}, 300);<br>searchInput.addEventListener(&quot;input&quot;, (e) =&gt; {<br>  fetchSearchResults(e.target.value);<br>});</pre><h4>Throttling Example: Scroll Event</h4><pre>const logScrollPosition = throttle(() =&gt; {<br>  console.log(`Scroll position: ${window.scrollY}`);<br>}, 1000);<br><br>window.addEventListener(&quot;scroll&quot;, logScrollPosition);</pre><h3>Combining Debouncing and Throttling</h3><p>Sometimes, you may want to debounce the start of an action and throttle its execution. For example, initializing a heavy operation on the first input and limiting its frequency thereafter.</p><pre>function debounceThrottle(func, debounceDelay, throttleLimit) {<br>  let timer;<br>  let lastRan;<br>  return function (...args) {<br>    const context = this;<br>    clearTimeout(timer); // Debounce<br>    timer = setTimeout(() =&gt; {<br>      if (!lastRan || Date.now() - lastRan &gt;= throttleLimit) {<br>        func.apply(context, args); // Throttle<br>        lastRan = Date.now();<br>      }<br>    }, debounceDelay);<br>  };<br>}<br><br>// Example Usage<br>const optimizedFunc = debounceThrottle(<br>  () =&gt; console.log(&quot;Action executed!&quot;),<br>  300,<br>  1000<br>);<br>window.addEventListener(&quot;resize&quot;, optimizedFunc);</pre><h3>Using Libraries for Convenience</h3><p>Popular libraries like <strong>Lodash</strong> provide built-in methods for debouncing and throttling:</p><p><strong>Debouncing</strong> with Lodash:</p><pre>import _ from &#39;lodash&#39;;<br>const handleInput = _.debounce((query) =&gt; console.log(query), 300);</pre><p><strong>Throttling</strong> with Lodash:</p><pre>import _ from &#39;lodash&#39;;<br>const handleScroll = _.throttle(() =&gt; console.log(&#39;Scroll&#39;), 1000);</pre><h3>Conclusion</h3><ul><li>Use <strong>debouncing</strong> when you need to delay a function until the event ceases, such as search bar inputs or window resizing.</li><li>Use <strong>throttling</strong> when you want to ensure consistent execution over time, such as for scroll or drag events.</li><li>Both techniques improve performance and provide a better user experience, especially in high-frequency event scenarios.</li></ul><p>Understanding and implementing these techniques effectively can make your JavaScript applications faster and more responsive!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30173fe77875" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Prototypal Inheritance, Custom Polyfills (bind, map, Promise) in JavaScript]]></title>
            <link>https://medium.com/@prateekchadha15/prototypal-inheritance-custom-polyfills-bind-map-promise-in-javascript-2c4116cb2ad4?source=rss-61b6d0894c80------2</link>
            <guid isPermaLink="false">https://medium.com/p/2c4116cb2ad4</guid>
            <dc:creator><![CDATA[Prateek Singh]]></dc:creator>
            <pubDate>Sun, 12 Jan 2025 17:38:42 GMT</pubDate>
            <atom:updated>2025-01-12T17:38:42.924Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/869/1*Agl4YofTPBWdAL-TJUh9fQ.jpeg" /></figure><p>JavaScript’s flexibility and power stem from its unique features, such as prototypal inheritance and the ability to customize the language with polyfills. In this blog, we’ll dive into <strong>prototypal inheritance</strong> and explore how to write custom polyfills for some commonly used functions like bind, map, and even Promise.</p><h3>Prototypal Inheritance in JavaScript</h3><p>Prototypal inheritance is a way for objects to share properties and methods. In JavaScript, objects can inherit directly from other objects using the prototype chain.</p><h3>How It Works</h3><p>When you try to access a property on an object, the JavaScript engine first looks at the object itself. If the property doesn’t exist, it moves up the prototype chain until it either finds the property or reaches the end of the chain (null).</p><h3>Example of Prototypal Inheritance</h3><pre>const animal = {<br>  speak() {<br>    console.log(`${this.name} makes a sound.`);<br>  }<br>};<br><br>const dog = Object.create(animal);<br>dog.name = &quot;Buddy&quot;;<br>dog.speak(); // Output: Buddy makes a sound.<br>console.log(dog.__proto__ === animal); // true</pre><p>Here, the dog object inherits the speak method from the animal object via prototypal inheritance.</p><h3>Using class in JavaScript</h3><p>Although JavaScript uses prototypes under the hood, the class syntax provides a more familiar way to work with inheritance</p><pre>class Animal {<br>  constructor(name) {<br>    this.name = name;<br>  }<br>  speak() {<br>    console.log(`${this.name} makes a sound.`);<br>  }<br>}<br><br>class Dog extends Animal {<br>  speak() {<br>    console.log(`${this.name} barks.`);<br>  }<br>}<br>const dog = new Dog(&quot;Buddy&quot;);<br>dog.speak(); // Output: Buddy barks.</pre><h3>Custom Polyfills</h3><p>A polyfill is a piece of code that adds missing functionality to older browsers or environments. Writing polyfills is a great way to understand how JavaScript functions work.</p><h3>1. Polyfill for bind</h3><p>The bind method creates a new function with a specific this context and optional arguments.</p><pre>Function.prototype.myBind = function (context, ...args) {<br>  if (typeof this !== &quot;function&quot;) {<br>    throw new TypeError(&quot;Bind can only be called on functions&quot;);<br>  }<br><br>const fn = this; // Reference to the function being bound<br>  return function (...newArgs) {<br>    return fn.apply(context, [...args, ...newArgs]);<br>  };<br>};<br>// Example<br>function greet(greeting, punctuation) {<br>  console.log(`${greeting}, ${this.name}${punctuation}`);<br>}<br>const person = { name: &quot;John&quot; };<br>const greetJohn = greet.myBind(person, &quot;Hello&quot;);<br>greetJohn(&quot;!&quot;); // Output: Hello, John!</pre><h3>2. Polyfill for map</h3><p>The map method creates a new array with the results of calling a provided function on every element in the original array.</p><pre>Array.prototype.myMap = function (callback) {<br>  if (typeof callback !== &quot;function&quot;) {<br>    throw new TypeError(callback + &quot; is not a function&quot;);<br>  }<br><br>const result = [];<br>  for (let i = 0; i &lt; this.length; i++) {<br>    if (this.hasOwnProperty(i)) {<br>      result.push(callback(this[i], i, this));<br>    }<br>  }<br>  return result;<br>};<br>// Example<br>const arr = [1, 2, 3];<br>const doubled = arr.myMap((num) =&gt; num * 2);<br>console.log(doubled); // Output: [2, 4, 6]</pre><h3>3. Polyfill for Promise</h3><p>The Promise object represents the eventual completion (or failure) of an asynchronous operation and its resulting value.</p><pre>function MyPromise(executor) {<br>  let onResolve, onReject;<br>  let fulfilled = false, rejected = false, called = false;<br>  let val<br><br>ue;<br>  function resolve(val) {<br>    fulfilled = true;<br>    value = val;<br>    if (typeof onResolve === &quot;function&quot;) {<br>      onResolve(val);<br>    }<br>  }<br>  function reject(val) {<br>    rejected = true;<br>    value = val;<br>    if (typeof onReject === &quot;function&quot;) {<br>      onReject(val);<br>    }<br>  }<br>  this.then = function (callback) {<br>    onResolve = callback;<br>    if (fulfilled &amp;&amp; !called) {<br>      called = true;<br>      onResolve(value);<br>    }<br>    return this;<br>  };<br>  this.catch = function (callback) {<br>    onReject = callback;<br>    if (rejected &amp;&amp; !called) {<br>      called = true;<br>      onReject(value);<br>    }<br>    return this;<br>  };<br>  try {<br>    executor(resolve, reject);<br>  } catch (err) {<br>    reject(err);<br>  }<br>}<br>// Example<br>const promise = new MyPromise((resolve, reject) =&gt; {<br>  setTimeout(() =&gt; resolve(&quot;Success!&quot;), 1000);<br>});<br>promise.then((res) =&gt; console.log(res)); // Output: Success! (after 1 second)</pre><h3>Conclusion</h3><p>Understanding <strong>prototypal inheritance</strong> and creating custom <strong>polyfills</strong> for methods like bind, map, and Promise provides deep insight into JavaScript&#39;s inner workings. These concepts form the backbone of modern JavaScript development, and mastering them will undoubtedly elevate your skills as a developer.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2c4116cb2ad4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Core Web Vitals in React.js: A Complete Guide]]></title>
            <link>https://medium.com/@prateekchadha15/core-web-vitals-in-react-js-a-complete-guide-f814eb794367?source=rss-61b6d0894c80------2</link>
            <guid isPermaLink="false">https://medium.com/p/f814eb794367</guid>
            <dc:creator><![CDATA[Prateek Singh]]></dc:creator>
            <pubDate>Sun, 08 Dec 2024 13:47:00 GMT</pubDate>
            <atom:updated>2024-12-08T13:47:00.497Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kGp46nGDk6MXobDbVRm-7g.png" /></figure><p>Core Web Vitals are critical metrics introduced by Google to measure the user experience of websites. They focus on loading performance, interactivity, and visual stability. For React developers, understanding and optimizing these metrics is essential to ensure high-performing applications and better search engine rankings.</p><p>In this blog, we’ll dive into the Core Web Vitals and how to improve them in React applications.</p><h3>1. What Are Core Web Vitals?</h3><p>Core Web Vitals consist of three key metrics:</p><ol><li><strong>Largest Contentful Paint (LCP):</strong></li></ol><ul><li>Measures loading performance.</li><li>Represents the time taken for the largest visible element (e.g., an image or heading) to load and render on the screen.</li><li><strong>Good LCP score:</strong> Less than <strong>2.5 seconds</strong>.</li></ul><p><strong>2. First Input Delay (FID):</strong></p><ul><li>Measures interactivity.</li><li>Tracks the time from when a user first interacts with the page (e.g., clicks a button) to when the browser responds.</li><li><strong>Good FID score:</strong> Less than <strong>100 milliseconds</strong>.</li></ul><p><strong>3. Cumulative Layout Shift (CLS):</strong></p><ul><li>Measures visual stability.</li><li>Calculates how much content unexpectedly moves during loading.</li><li><strong>Good CLS score:</strong> Less than <strong>0.1</strong>.</li></ul><h3>2. Why Do Core Web Vitals Matter in React?</h3><ul><li><strong>User Experience:</strong> Faster, more stable applications ensure higher user satisfaction and engagement.</li><li><strong>SEO:</strong> Google uses Core Web Vitals as a ranking factor.</li><li><strong>Conversions:</strong> Better performance often leads to higher conversion rates.</li></ul><h3>3. Tools to Measure Core Web Vitals</h3><ul><li><strong>Google Lighthouse:</strong> Integrated into Chrome DevTools.</li><li><strong>Web Vitals Extension:</strong> Chrome extension for real-time monitoring.</li><li><strong>PageSpeed Insights:</strong> Provides detailed insights and suggestions for improvement.</li><li><strong>Web Vitals Library:</strong> A JavaScript library to measure Core Web Vitals in real-time.</li></ul><h3>4. How to Optimize Core Web Vitals in React</h3><h4>A. Improving LCP (Largest Contentful Paint)</h4><ol><li><strong>Optimize Images:</strong></li></ol><ul><li>Use next-gen formats like WebP or AVIF.</li><li>Implement lazy loading for offscreen images using libraries like react-lazyload.</li></ul><pre>import LazyLoad from &#39;react-lazyload&#39;;<br><br>&lt;LazyLoad height={200} offset={100}&gt;<br>  &lt;img src=&quot;image.jpg&quot; alt=&quot;example&quot; /&gt;<br>&lt;/LazyLoad&gt;</pre><ul><li>Use a Content Delivery Network (CDN) to serve images quickly.</li></ul><p><strong>2. Preload Critical Resources:</strong></p><ul><li>Preload important assets (e.g., hero images, fonts).</li></ul><pre>&lt;link rel=&quot;preload&quot; href=&quot;/path-to-image.jpg&quot; as=&quot;image&quot; /&gt;</pre><p><strong>3. Minimize JavaScript Execution:</strong></p><ul><li>Use React’s Suspense and lazy for code splitting.</li></ul><pre>const LazyComponent = React.lazy(() =&gt; import(&#39;./Component&#39;));<br><br>&lt;Suspense fallback={&lt;div&gt;Loading...&lt;/div&gt;}&gt;<br>  &lt;LazyComponent /&gt;<br>&lt;/Suspense&gt;;</pre><h4>B. Reducing FID (First Input Delay)</h4><ol><li><strong>Optimize JavaScript Execution:</strong></li></ol><ul><li>Avoid blocking the main thread with large bundles.</li><li>Use tools like Webpack or Vite for code splitting.</li></ul><p><strong>2. Defer Non-Critical JavaScript:</strong></p><ul><li>Use React.useEffect for tasks that don&#39;t need to block rendering.</li></ul><p><strong>3. Minimize Third-Party Dependencies:</strong></p><ul><li>Audit your node_modules and remove unnecessary libraries.</li><li>Use lightweight alternatives whenever possible.</li></ul><h4>C. Minimizing CLS (Cumulative Layout Shift)</h4><ol><li><strong>Set Dimensions for Media:</strong></li></ol><ul><li>Always define width and height for images, videos, and iframes to reserve space.</li></ul><pre>&lt;img src=&quot;image.jpg&quot; width=&quot;300&quot; height=&quot;200&quot; alt=&quot;example&quot; /&gt;</pre><p><strong>2. Avoid Injecting Content Above Existing Elements:</strong></p><ul><li>Use placeholders or skeleton loaders for dynamic content.</li></ul><p><strong>3. Font Optimization:</strong></p><ul><li>Use font-display: swap for custom fonts to prevent invisible text during font loading.</li></ul><pre>@font-face { <br>    font-family: &#39;CustomFont&#39;;   <br>    src: url(https://medium.com/&#39;custom-font.woff2&#39;) format(&#39;woff2&#39;);   <br>    font-display: swap; <br>}</pre><h3>5. Monitoring Core Web Vitals in React</h3><h4>Using Web Vitals Library</h4><p>Google provides a web-vitals library to measure these metrics in React.</p><ol><li>Install the library:</li></ol><pre>npm install web-vitals</pre><p>2. Integrate it in your application:</p><pre>import { getCLS, getFID, getLCP } from &#39;web-vitals&#39;;<br><br>const sendToAnalytics = (metric) =&gt; {<br>  console.log(metric);<br>  // Send metric to analytics server<br>};<br>getCLS(sendToAnalytics);<br>getFID(sendToAnalytics);<br>getLCP(sendToAnalytics);</pre><h4>Using Performance Metrics API</h4><p>React’s useEffect can help measure performance:</p><pre>import { useEffect } from &#39;react&#39;;<br><br>const usePerformance = () =&gt; {<br>  useEffect(() =&gt; {<br>    const observer = new PerformanceObserver((list) =&gt; {<br>      list.getEntries().forEach((entry) =&gt; console.log(entry));<br>    });<br>    observer.observe({ type: &#39;paint&#39;, buffered: true });<br>    return () =&gt; observer.disconnect();<br>  }, []);<br>};<br><br>export default usePerformance;</pre><h3>6. Advanced Optimization Tips</h3><ol><li><strong>Server-Side Rendering (SSR):</strong></li></ol><ul><li>Use frameworks like Next.js or Implement SSR with Node js and React to pre-render pages for faster loading.</li></ul><p><strong>2. Static Site Generation (SSG):</strong></p><ul><li>Generate HTML at build time for static content.</li></ul><p><strong>3. React Profiler:</strong></p><ul><li>Use React’s built-in Profiler to identify performance bottlenecks.</li></ul><p><strong>4. Priority Hints:</strong></p><ul><li>Assign priorities to resources using the <strong>fetchPriority</strong> attribute.</li></ul><pre>const img = new Image();<br>img.fetchPriority = &quot;high&quot;;<br>img.src = &quot;img/logo.png&quot;;</pre><h3>Conclusion</h3><p>Core Web Vitals are a vital part of building performant and user-friendly React applications. By focusing on optimizing LCP, FID, and CLS, you can improve both user experience and search engine rankings.</p><p>Start by measuring your app’s performance, apply the optimization strategies shared above, and iterate continuously. With consistent effort, your React app will not only load faster but also offer a seamless experience to your users. 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f814eb794367" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding the Event Loop: JavaScript’s Secret to Asynchronous Magic]]></title>
            <link>https://medium.com/@prateekchadha15/understanding-the-event-loop-javascripts-secret-to-asynchronous-magic-6f03e6d59fe4?source=rss-61b6d0894c80------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f03e6d59fe4</guid>
            <dc:creator><![CDATA[Prateek Singh]]></dc:creator>
            <pubDate>Sat, 07 Dec 2024 13:19:27 GMT</pubDate>
            <atom:updated>2024-12-07T13:19:27.091Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*cdp67R0_X-8iAR9eZbh4Vg.png" /></figure><p>JavaScript is known for its <strong>single-threaded, non-blocking</strong> nature, allowing it to handle multiple tasks efficiently without waiting for one to complete before starting the next. The secret behind this ability lies in its <strong>event loop</strong>.</p><p>In this blog, we’ll unravel the magic of the event loop, how it interacts with the call stack, Web APIs, and the message queue, and how these components work together to handle asynchronous operations in JavaScript.</p><h3>The Building Blocks</h3><p>To understand the event loop, let’s first introduce the key components:</p><h3>1. Call Stack</h3><p>The call stack is a data structure that keeps track of function calls. Functions are pushed onto the stack when invoked and popped off when execution is completed. The stack operates on a <strong>Last In, First Out (LIFO)</strong> principle.</p><h3>2. Web APIs</h3><p>Web APIs (or the browser environment) handle asynchronous tasks like setTimeout, HTTP requests (fetch), or DOM events. These tasks are executed outside the call stack and notify JavaScript when they&#39;re ready to be processed.</p><h3>3. Message Queue</h3><p>The message queue is a list of messages (or callbacks) waiting to be executed. When the call stack is empty, the event loop pulls tasks from the queue and pushes them onto the call stack.</p><h3>4. Event Loop</h3><p>The event loop is the conductor of this orchestra. It continuously checks if the call stack is empty. If it is, it takes the first task from the message queue and executes it by pushing it onto the call stack.</p><h3>How It All Works</h3><ol><li>The <strong>call stack</strong> handles synchronous operations.</li><li>For asynchronous tasks, JavaScript sends the task to <strong>Web APIs</strong> (or Node.js APIs in a non-browser environment).</li><li>Once the task is complete, a <strong>callback</strong> is added to the <strong>message queue</strong>.</li><li>The <strong>event loop</strong> ensures the call stack is empty before moving the next callback from the message queue to the call stack.</li></ol><h3>Example 1: Understanding Basics</h3><pre>console.log(&quot;Start&quot;);<br><br>setTimeout(() =&gt; {<br>  console.log(&quot;Inside setTimeout&quot;);<br>}, 0);<br><br>console.log(&quot;End&quot;);</pre><h4>Execution Process:</h4><ol><li><strong>Call Stack:</strong> console.log(&quot;Start&quot;) is pushed, executed, and popped → logs <strong>Start</strong>.</li><li><strong>Web API:</strong> setTimeout is handed to Web APIs, and the callback is queued after 0 ms.</li><li><strong>Call Stack:</strong> console.log(&quot;End&quot;) is pushed, executed, and popped → logs <strong>End</strong>.</li><li><strong>Event Loop:</strong> After the call stack is empty, the event loop pushes the setTimeout callback to the call stack → logs <strong>Inside setTimeout</strong>.</li></ol><h4>Output:</h4><pre>Start<br>End<br>Inside setTimeout</pre><h3>Example 2: Multiple Asynchronous Tasks</h3><pre>console.log(&quot;Start&quot;);<br><br>setTimeout(() =&gt; {<br>  console.log(&quot;Timeout 1&quot;);<br>}, 3000);<br><br>setTimeout(() =&gt; {<br>  console.log(&quot;Timeout 2&quot;);<br>}, 1000);<br><br>console.log(&quot;End&quot;);</pre><h4>Execution Process:</h4><ol><li><strong>Call Stack:</strong> Executes console.log(&quot;Start&quot;) and console.log(&quot;End&quot;) → logs <strong>Start</strong> and <strong>End</strong>.</li><li><strong>Web API:</strong> The first setTimeout is registered for 3000ms, the second for 1000ms.</li><li><strong>Message Queue:</strong> After 1000ms, the callback for Timeout 2 is added to the queue. At 3000ms, Timeout 1 is queued.</li><li><strong>Event Loop:</strong> Processes the queue once the call stack is empty.</li></ol><h4>Output:</h4><pre>Start<br>End<br>Timeout 2<br>Timeout 1</pre><h3>Example 3: Promises and the Microtask Queue</h3><p>Promises and async/await use a special <strong>microtask queue</strong>. Microtasks have a higher priority than tasks in the regular message queue.</p><pre>console.log(&quot;Start&quot;);<br><br>setTimeout(() =&gt; {<br>  console.log(&quot;Timeout&quot;);<br>}, 0);<br><br>Promise.resolve().then(() =&gt; {<br>  console.log(&quot;Promise&quot;);<br>});<br><br>console.log(&quot;End&quot;);</pre><h4>Execution Process:</h4><ol><li><strong>Call Stack:</strong> Executes console.log(&quot;Start&quot;) and console.log(&quot;End&quot;) → logs <strong>Start</strong> and <strong>End</strong>.</li><li><strong>Microtask Queue:</strong> The Promise.resolve().then callback is added to the microtask queue.</li><li><strong>Message Queue:</strong> The setTimeout callback is added to the message queue.</li><li><strong>Event Loop:</strong></li></ol><ul><li>First processes the microtask queue → logs <strong>Promise</strong>.</li><li>Then processes the message queue → logs <strong>Timeout</strong>.</li></ul><h4>Output:</h4><pre>Start<br>End<br>Promise<br>Timeout</pre><h3>Example 4: Nested Asynchronous Operations</h3><pre>console.log(&quot;Start&quot;);<br><br>setTimeout(() =&gt; {<br>  console.log(&quot;Timeout 1&quot;);<br>  Promise.resolve().then(() =&gt; {<br>    console.log(&quot;Promise 1&quot;);<br>  });<br>}, 0);<br><br>Promise.resolve().then(() =&gt; {<br>  console.log(&quot;Promise 2&quot;);<br>});<br><br>console.log(&quot;End&quot;);</pre><h4>Execution Process:</h4><ol><li><strong>Call Stack:</strong> Logs <strong>Start</strong> and <strong>End</strong>.</li><li><strong>Microtask Queue:</strong> Adds Promise 2.</li><li><strong>Message Queue:</strong> Adds Timeout 1 (with its callback).</li><li><strong>Event Loop:</strong></li></ol><ul><li>Processes Promise 2 first → logs <strong>Promise 2</strong>.</li><li>Processes Timeout 1 → logs <strong>Timeout 1</strong>.</li><li>Processes the microtask (Promise 1) from the Timeout 1 callback → logs <strong>Promise 1</strong>.</li></ul><h4>Output:</h4><pre>Start<br>End<br>Promise 2<br>Timeout 1<br>Promise 1</pre><h3>Why Is the Event Loop Important?</h3><p>The event loop allows JavaScript to:</p><ol><li><strong>Handle Asynchronous Code:</strong> Manage callbacks, promises, and events without blocking the main thread.</li><li><strong>Ensure UI Responsiveness:</strong> Prevents freezing by prioritizing essential tasks.</li><li><strong>Execute Tasks in Order:</strong> Ensures microtasks are executed before tasks from the message queue.</li></ol><h3>Tips for Working with the Event Loop</h3><ol><li><strong>Avoid Blocking Code:</strong> Long-running synchronous code blocks the call stack and delays other tasks.</li><li><strong>Leverage Promises and Async/Await:</strong> These provide more control over asynchronous workflows.</li><li><strong>Understand Task Priorities:</strong> Use setTimeout and promises appropriately to manage task execution.</li></ol><h3>Conclusion</h3><p>The event loop, call stack, and message queue form the backbone of JavaScript’s asynchronous capabilities. Understanding their interplay is crucial for writing efficient, non-blocking code and debugging tricky timing issues. With this knowledge, you can unlock JavaScript’s full potential and build faster, more responsive applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f03e6d59fe4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Redux Deprecation and Migrating to Redux Toolkit]]></title>
            <link>https://medium.com/@prateekchadha15/understanding-redux-deprecation-and-migrating-to-redux-toolkit-d182c6b381b9?source=rss-61b6d0894c80------2</link>
            <guid isPermaLink="false">https://medium.com/p/d182c6b381b9</guid>
            <dc:creator><![CDATA[Prateek Singh]]></dc:creator>
            <pubDate>Fri, 06 Dec 2024 15:31:28 GMT</pubDate>
            <atom:updated>2024-12-06T15:31:28.419Z</atom:updated>
            <content:encoded><![CDATA[<h4>Why Redux is Considered “Deprecated”?</h4><p>Redux itself is not officially deprecated; it’s still a powerful and widely-used state management library. However, the <strong>manual boilerplate code</strong> and <strong>complexity of configuration</strong> in vanilla Redux have been addressed with <strong>Redux Toolkit (RTK)</strong>. RTK simplifies the process of setting up and using Redux by providing opinionated defaults and utilities for common use cases.</p><h3>What is Redux Toolkit (RTK)?</h3><p>Redux Toolkit is the <strong>recommended way to write Redux logic</strong>. It includes built-in tools and abstractions to reduce boilerplate, improve code clarity, and make Redux more approachable for modern applications.</p><h3>Key Differences: Redux vs. Redux Toolkit</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/1*VwW9TN4pefSDx_OatLrXFw.png" /></figure><h3>How to Migrate from Redux to Redux Toolkit</h3><h4>1. Install Redux Toolkit</h4><pre>npm install @reduxjs/toolkit</pre><h4>2. Refactor Reducers to Slices</h4><p>Vanilla Redux reducers often involve a lot of boilerplate. RTK simplifies this using createSlice.</p><p><strong>Old Redux Reducer Example:</strong></p><pre>// actions.js<br>export const increment = () =&gt; ({ type: &#39;INCREMENT&#39; });<br>export const decrement = () =&gt; ({ type: &#39;DECREMENT&#39; });<br><br>// reducer.js<br>const initialState = { count: 0 };<br>export default function counterReducer(state = initialState, action) {<br>  switch (action.type) {<br>    case &#39;INCREMENT&#39;:<br>      return { ...state, count: state.count + 1 };<br>    case &#39;DECREMENT&#39;:<br>      return { ...state, count: state.count - 1 };<br>    default:<br>      return state;<br>  }<br>}</pre><p><strong>RTK Slice Example:</strong></p><pre>import { createSlice } from &#39;@reduxjs/toolkit&#39;;<br><br>const counterSlice = createSlice({<br>  name: &#39;counter&#39;,<br>  initialState: { count: 0 },<br>  reducers: {<br>    increment: (state) =&gt; { state.count += 1; },<br>    decrement: (state) =&gt; { state.count -= 1; },<br>  },<br>});<br>export const { increment, decrement } = counterSlice.actions;<br>export default counterSlice.reducer;</pre><h4>3. Replace createStore with configureStore</h4><p>RTK simplifies the store setup with configureStore, which automatically includes Redux DevTools and redux-thunk.</p><p><strong>Old Redux Store Example:</strong></p><pre>import { createStore, applyMiddleware } from &#39;redux&#39;;<br>import thunk from &#39;redux-thunk&#39;;<br>import rootReducer from &#39;./reducers&#39;;<br><br>const store = createStore(rootReducer, applyMiddleware(thunk));<br>export default store;</pre><p><strong>RTK Store Example:</strong></p><pre>import { configureStore } from &#39;@reduxjs/toolkit&#39;;<br>import counterReducer from &#39;./counterSlice&#39;;<br><br>const store = configureStore({<br>  reducer: {<br>    counter: counterReducer,<br>  },<br>});<br>export default store;</pre><h4>4. Update Actions Dispatching</h4><p>In RTK, you dispatch actions from the slice directly.</p><p><strong>Old Redux:</strong></p><pre>import { useDispatch } from &#39;react-redux&#39;;<br>import { increment } from &#39;./actions&#39;;<br><br>const Component = () =&gt; {<br>  const dispatch = useDispatch();<br>  return &lt;button onClick={() =&gt; dispatch(increment())}&gt;Increment&lt;/button&gt;;<br>};</pre><p><strong>RTK:</strong></p><pre>import { useDispatch } from &#39;react-redux&#39;;<br>import { increment } from &#39;./counterSlice&#39;;<br><br>const Component = () =&gt; {<br>  const dispatch = useDispatch();<br>  return &lt;button onClick={() =&gt; dispatch(increment())}&gt;Increment&lt;/button&gt;;<br>};</pre><h4>5. Handle Asynchronous Logic</h4><p>RTK provides createAsyncThunk for managing asynchronous operations.</p><p><strong>Old Redux (Thunk Example):</strong></p><pre>export const fetchData = () =&gt; async (dispatch) =&gt; {<br>  const response = await fetch(&#39;/api/data&#39;);<br>  const data = await response.json();<br>  dispatch({ type: &#39;SET_DATA&#39;, payload: data });<br>};</pre><p><strong>RTK with </strong><strong>createAsyncThunk:</strong></p><pre>import { createAsyncThunk, createSlice } from &#39;@reduxjs/toolkit&#39;;<br><br>export const fetchData = createAsyncThunk(&#39;data/fetch&#39;, async () =&gt; {<br>  const response = await fetch(&#39;/api/data&#39;);<br>  return response.json();<br>});<br>const dataSlice = createSlice({<br>  name: &#39;data&#39;,<br>  initialState: { data: [], loading: false },<br>  extraReducers: (builder) =&gt; {<br>    builder<br>      .addCase(fetchData.pending, (state) =&gt; { state.loading = true; })<br>      .addCase(fetchData.fulfilled, (state, action) =&gt; {<br>        state.loading = false;<br>        state.data = action.payload;<br>      });<br>  },<br>});<br>export default dataSlice.reducer;</pre><h3>Benefits of Switching to Redux Toolkit</h3><ul><li><strong>Reduced Boilerplate:</strong> Combines actions, reducers, and constants into a single createSlice.</li><li><strong>Improved Code Readability:</strong> Cleaner, more declarative structure.</li><li><strong>Built-In Best Practices:</strong> Encourages immutable updates, middleware usage, and asynchronous handling.</li><li><strong>Modern Features:</strong> Compatible with TypeScript, supports code splitting, and easy to use with React.</li></ul><p>Migrating to Redux Toolkit ensures your codebase is future-proof, easier to maintain, and aligned with modern best practices.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d182c6b381b9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What’s Deno, and how is it different from Node.js?]]></title>
            <link>https://medium.com/weekly-webtips/whats-deno-and-how-is-it-different-from-node-js-3f70e46be9ef?source=rss-61b6d0894c80------2</link>
            <guid isPermaLink="false">https://medium.com/p/3f70e46be9ef</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[node]]></category>
            <category><![CDATA[deno]]></category>
            <dc:creator><![CDATA[Prateek Singh]]></dc:creator>
            <pubDate>Mon, 01 Jun 2020 09:22:19 GMT</pubDate>
            <atom:updated>2020-06-02T14:47:33.046Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*y24mgqIBqBjl7Qs6nvKERg.jpeg" /></figure><p>I explore new projects every week, and it’s rare that one grabs my attention as much as <a href="https://deno.land/">Deno</a> did.</p><p>In this post I want to get you up to speed with Deno quickly. We’ll compare it with Node.js, and build your first REST API with it.</p><h3>Table of contents</h3><ul><li>What is Deno</li><li>Why Deno?Why Now</li><li>Should you learn Deno?</li><li>Will it replace NodeJs?</li><li>First-class Typescript support</li><li>Similarities and differences with NodeJs</li><li>No package manager</li><li>Install Deno</li><li>The Deno Commands</li><li>Your First Deno App</li></ul><h3>What is Deno?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kwCah02nhNywD1uFM4P5MQ.png" /></figure><p>If you are familiar with Node.js, the popular server-side JavaScript ecosystem, then Deno is just like Node. Except deeply improved in many ways.</p><p>Let’s start from a quick list of the features I like the most about Deno:</p><ul><li>It is based on modern features of the JavaScript language</li><li>It has an extensive standard library</li><li>It has TypeScript at its core, which brings a huge advantage in many different ways, including a first-class TypeScript support (you don’t have to separately compile TypeScript, it’s automatically done by Deno)</li><li>It embraces ES modules.</li><li>It has no package manager</li><li>It has a first-class await</li><li>It has a built-in testing facility</li><li>It aims to be browser-compatible as much as it can, for example by providing a built-in fetch and the global window object</li></ul><p>We’ll explore all of those features in this guide.</p><p>After you use Deno and learn to appreciate its features, Node.js will look like something <em>old</em>.</p><p>Especially because the Node.js API is callback-based, as it was written way before promises and async/await. There’s no change available for that in Node, because such a change would be monumental. So we’re stuck with callbacks or with promisifying API calls.</p><p>Node.js is <strong>awesome</strong> and will continue to be the de facto standard in the JavaScript world. But I think we’ll gradually see Deno get adopted more and more because of its first-class TypeScript support and modern standard library.</p><p>Deno can afford to have everything written with modern technologies, since there’s no backward compatibility to maintain. Of course there’s no guarantee that in a decade the same will happen to Deno and a new technology will emerge, but this is the reality at the moment.</p><h3>Why Deno? Why now?</h3><p>Deno was announced almost 2 years ago by the original creator of Node.js, Ryan Dahl, at JSConf EU. Watch <a href="https://www.youtube.com/watch?v=M3BM9TB-8yA">the YouTube video of the talk</a>, it’s very interesting and it’s a mandatory watch if you are involved in Node.js and JavaScript in general.</p><p>Every project manager must make decisions. Ryan regretted some early decisions in Node. Also, technology evolves, and today JavaScript is a totally different language than what it was back in 2009 when Node started. Think about the modern ES6/2016/2017 features, and so on.</p><p>So he started a new project to create some sort of second wave of JavaScript-powered server side apps.</p><p>The reason I am writing this guide now and not back then is because technologies need a lot of time to mature. And we have finally reached <strong>Deno 1.0</strong> (1.0 should be released on May 13, 2020), the first release of Deno officially declared stable.</p><p>That’s might seem to be just a number, but 1.0 means there will not be major breaking changes until Deno 2.0. This is a big deal when you dive into a new technology — you don’t want to learn something and then have it change too fast.</p><h3>Should you learn Deno?</h3><p>That’s a big question.</p><p>Learning something new such as Deno is a big effort. My suggestion is that if you are starting out now with server-side JS and you don’t know Node yet, and have never written any TypeScript, I’d start with Node.</p><p>No one was ever fired for choosing Node.js (paraphrasing a common quote).</p><p>But if you love TypeScript, don’t depend on a gazillion npm packages in your projects and you want to use await anywhere, hey Deno might be what you’re looking for.</p><h3>Will it replace Node.js?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/370/1*1CZy1NGFc50mJX7VxlPHQA.png" /></figure><p>No. Node.js is a giant, well established, incredibly well-supported technology that is going to stay around for decades.</p><h3>First-class TypeScript support</h3><p>Deno is written in Rust and TypeScript, two of the languages that are really growing fast today.</p><p>In particular, being written in TypeScript means we get a lot of the benefits of TypeScript even if we might choose to write our code in plain JavaScript.</p><p>And running TypeScript code with Deno does not require a compilation step — Deno does that automatically for you.</p><p>You are not forced to write in TypeScript, but the fact the core of Deno is written in TypeScript is huge.</p><p>First, an increasingly large percentage of JavaScript programmers love TypeScript.</p><p>Second, the tools you use can infer many information about software written in TypeScript, like Deno.</p><p>This means that when we code in VS Code, for example (which of course has a tight integration with TypeScript since both are developed at Micro Soft), we can get benefits like type checking as we write our code, and advanced IntelliSense features. In other words the editor can help us in a deeply useful way.</p><h3>Similarities and differences with Node.js</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uLtaSPrShxcZI5lpu1PTbA.jpeg" /></figure><p>Since Deno is basically a Node.js replacement, it’s useful to compare the two directly.</p><p>Similarities:</p><ul><li>Both are developed upon the <a href="https://flaviocopes.com/v8/">V8 Chromium Engine</a></li><li>Both are great for developing server-side with JavaScript</li></ul><p>Differences:</p><ul><li>Node is written in C++ and JavaScript. Deno is written in Rust and TypeScript.</li><li>Node has an official package manager called npm. Deno does not, and instead lets you import any ES Module from URLs.</li><li>Node uses the CommonJS syntax for importing packages. Deno uses ES Modules, the official way.</li><li>Deno uses modern ECMAScript features in all its API and standard library, while Node.js uses a callbacks-based standard library and has no plans to upgrade it.</li><li>Deno offers a sandbox security layer through permissions. A program can only access the permissions set to the executable as flags by the user. A Node.js program can access anything the user can access.</li><li>Deno has for a long time envisioned the possibility of compiling a program into an executable that you can run without external dependencies, like Go, but it’s still not a thing yet. That’d be a game changer.</li></ul><h3>No package manager</h3><p>Having no package manager and having to rely on URLs to host and import packages has pros and cons. I really like the pros: it’s very flexible, and we can create packages without publishing them on a repository like npm.</p><p>I think that some sort of package manager will emerge, but nothing official is out yet.</p><p>The Deno website provides code hosting (and thus distribution through URLs) to 3rd party packages: <a href="https://deno.land/x/">https://deno.land/x/</a></p><h3>Install Deno</h3><p>Enough talk! Let’s install Deno.</p><p>The easiest way is to use <a href="https://flaviocopes.com/homebrew/">Homebrew</a>:</p><pre>brew install deno</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qhYv19plUF7qRzKD.jpg" /></figure><p>Once this is done, you will have access to the deno command. Here’s the help that you can get using deno --help:</p><pre>flavio@mbp~&gt; deno --help<br>deno 0.42.0<br>A secure JavaScript and TypeScript runtime</pre><pre>Docs: https://deno.land/std/manual.md<br>Modules: https://deno.land/std/ https://deno.land/x/<br>Bugs: https://github.com/denoland/deno/issues</pre><pre>To start the REPL, supply no arguments:<br>  deno</pre><pre>To execute a script:<br>  deno run https://deno.land/std/examples/welcome.ts<br>  deno https://deno.land/std/examples/welcome.ts</pre><pre>To evaluate code in the shell:<br>  deno eval &quot;console.log(30933 + 404)&quot;</pre><pre>Run &#39;deno help run&#39; for &#39;run&#39;-specific flags.</pre><pre>USAGE:<br>    deno [OPTIONS] [SUBCOMMAND]</pre><pre>OPTIONS:<br>    -h, --help<br>            Prints help information</pre><pre>    -L, --log-level &lt;log-level&gt;<br>            Set log level [possible values: debug, info]</pre><pre>    -q, --quiet<br>            Suppress diagnostic output<br>            By default, subcommands print human-readable diagnostic messages to stderr.<br>            If the flag is set, restrict these messages to errors.<br>    -V, --version<br>            Prints version information<br></pre><pre>SUBCOMMANDS:<br>    bundle         Bundle module and dependencies into single file<br>    cache          Cache the dependencies<br>    completions    Generate shell completions<br>    doc            Show documentation for a module<br>    eval           Eval script<br>    fmt            Format source files<br>    help           Prints this message or the help of the given subcommand(s)<br>    info           Show info about cache or info related to source file<br>    install        Install script as an executable<br>    repl           Read Eval Print Loop<br>    run            Run a program given a filename or url to the module<br>    test           Run tests<br>    types          Print runtime TypeScript declarations<br>    upgrade        Upgrade deno executable to newest version</pre><pre>ENVIRONMENT VARIABLES:<br>    DENO_DIR             Set deno&#39;s base directory (defaults to $HOME/.deno)<br>    DENO_INSTALL_ROOT    Set deno install&#39;s output directory<br>                         (defaults to $HOME/.deno/bin)<br>    NO_COLOR             Set to disable color<br>    HTTP_PROXY           Proxy address for HTTP requests<br>                         (module downloads, fetch)<br>    HTTPS_PROXY          Same but for HTTPS</pre><h3>The Deno commands</h3><p>Note the SUBCOMMANDS section in the help, that lists all the commands we can run. What subcommands do we have?</p><ul><li>bundle bundle module and dependencies of a project into single file</li><li>cache cache the dependencies</li><li>completions generate shell completions</li><li>doc show documentation for a module</li><li>eval to evaluate a piece of code, e.g. deno eval &quot;console.log(1 + 2)&quot;</li><li>fmt a built-in code formatter (similar to gofmt in Go)</li><li>help prints this message or the help of the given subcommand(s)</li><li>info show info about cache or info related to source file</li><li>install install script as an executable</li><li>repl Read-Eval-Print-Loop (the default)</li><li>run run a program given a filename or url to the module</li><li>test run tests</li><li>types print runtime TypeScript declarations</li><li>upgrade upgrade deno to the newest version</li></ul><p>You can run deno &lt;subcommand&gt; help to get specific additional documentation for the command, for example deno run --help.</p><p>As the help says, we can use this command to start a REPL (Read-Execute-Print-Loop) using deno without any other option.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EMdxzhzdYtWETPNI.png" /></figure><p>This is the same as running deno repl.</p><p>A more common way you’ll use this command is to execute a Deno app contained in a TypeScript file.</p><p>You can run both TypeScript (.ts) files, or JavaScript (.js) files.</p><p>If you are unfamiliar with TypeScript, don’t worry: Deno is written in TypeScript, buf you can write your “client” applications in JavaScript.</p><p>Here is a video that helps you understand typescript: <a href="https://flaviocopes.com/typescript/"><em>TypeScript tutorial</em></a></p><h3>Your first Deno app</h3><p>Let’s run a Deno app for the first time.</p><p>What I find pretty amazing is that you don’t even have to write a single line — you can run a command from any URL.</p><p>Deno downloads the program, compiles it and then runs it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ft8HBQz9jdGjcpmH.jpg" /></figure><p><em>Of course running arbitrary code from the Internet is not a practice I’d generally recommend. In this case we are running it from the Deno official site, plus Deno has a sandbox that prevents programs to do anything you don’t want to allow. More on this later.</em></p><p>This program is very simple, just a console.log() call:</p><pre>console.log(&#39;Welcome to Deno 🦕&#39;)</pre><p>If you open the <a href="https://deno.land/std/examples/welcome.ts">https://deno.land/std/examples/welcome.ts</a> URL with the browser, you’ll see this page:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/0*wdU3jmL_Y5uqeHqB.png" /></figure><p>Weird, right? You’d probably expect a TypeScript file, but instead we have a web page. The reason is the Web server of the Deno website knows you’re using a browser and serves you a more user friendly page.</p><p>Download the same UR using wget for example, which requests the text/plain version of it instead of text/html:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UfGx7XMFPs6T8xqw.png" /></figure><p>If you want to run the program again, it’s now cached by Deno and it does not need to download it again:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1mXD4rUdC14C9jAi.jpg" /></figure><p>You can force a reload of the original source with the --reload flag:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Kxn6x-r8GLuw1eAv.jpg" /></figure><p>deno run has lots of different options that were not listed in the deno --help. Instead, you need to run deno run --help to reveal them:</p><pre>flavio@mbp~&gt; deno run --help<br>deno-run<br>Run a program given a filename or url to the module.</pre><pre>By default all programs are run in sandbox without access to disk, network or<br>ability to spawn subprocesses.<br>  deno run https://deno.land/std/examples/welcome.ts</pre><pre>Grant all permissions:<br>  deno run -A https://deno.land/std/http/file_server.ts</pre><pre>Grant permission to read from disk and listen to network:<br>  deno run --allow-read --allow-net https://deno.land/std/http/file_server.ts</pre><pre>Grant permission to read whitelisted files from disk:<br>  deno run --allow-read=/etc https://deno.land/std/http/file_server.ts</pre><pre>USAGE:<br>    deno run [OPTIONS] &lt;SCRIPT_ARG&gt;...</pre><pre>OPTIONS:<br>    -A, --allow-all<br>            Allow all permissions</pre><pre>        --allow-env<br>            Allow environment access</pre><pre>        --allow-hrtime<br>            Allow high resolution time measurement</pre><pre>        --allow-net=&lt;allow-net&gt;<br>            Allow network access</pre><pre>        --allow-plugin<br>            Allow loading plugins</pre><pre>        --allow-read=&lt;allow-read&gt;<br>            Allow file system read access</pre><pre>        --allow-run<br>            Allow running subprocesses</pre><pre>        --allow-write=&lt;allow-write&gt;<br>            Allow file system write access</pre><pre>        --cached-only<br>            Require that remote dependencies are already cached</pre><pre>        --cert &lt;FILE&gt;<br>            Load certificate authority from PEM encoded file</pre><pre>    -c, --config &lt;FILE&gt;<br>            Load tsconfig.json configuration file</pre><pre>    -h, --help<br>            Prints help information</pre><pre>        --importmap &lt;FILE&gt;<br>            UNSTABLE:<br>            Load import map file<br>            Docs: https://deno.land/std/manual.md#import-maps<br>            Specification: https://wicg.github.io/import-maps/<br>            Examples: https://github.com/WICG/import-maps#the-import-map<br>        --inspect=&lt;HOST:PORT&gt;<br>            activate inspector on host:port (default: 127.0.0.1:9229)</pre><pre>        --inspect-brk=&lt;HOST:PORT&gt;<br>            activate inspector on host:port and break at start of user script</pre><pre>        --lock &lt;FILE&gt;<br>            Check the specified lock file</pre><pre>        --lock-write<br>            Write lock file. Use with --lock.</pre><pre>    -L, --log-level &lt;log-level&gt;<br>            Set log level [possible values: debug, info]</pre><pre>        --no-remote<br>            Do not resolve remote modules</pre><pre>    -q, --quiet<br>            Suppress diagnostic output<br>            By default, subcommands print human-readable diagnostic messages to stderr.<br>            If the flag is set, restrict these messages to errors.<br>    -r, --reload=&lt;CACHE_BLACKLIST&gt;<br>            Reload source code cache (recompile TypeScript)<br>            --reload<br>              Reload everything<br>            --reload=https://deno.land/std<br>              Reload only standard modules<br>            --reload=https://deno.land/std/fs/utils.ts,https://deno.land/std/fmt/colors.ts<br>              Reloads specific modules<br>        --seed &lt;NUMBER&gt;<br>            Seed Math.random()</pre><pre>        --unstable<br>            Enable unstable APIs</pre><pre>        --v8-flags=&lt;v8-flags&gt;<br>            Set V8 command line options. For help: --v8-flags=--help<br></pre><pre>ARGS:<br>    &lt;SCRIPT_ARG&gt;...<br>            script args</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3f70e46be9ef" width="1" height="1" alt=""><hr><p><a href="https://medium.com/weekly-webtips/whats-deno-and-how-is-it-different-from-node-js-3f70e46be9ef">What’s Deno, and how is it different from Node.js?</a> was originally published in <a href="https://medium.com/weekly-webtips">Webtips</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>