<?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 Kishan Patel on Medium]]></title>
        <description><![CDATA[Stories by Kishan Patel on Medium]]></description>
        <link>https://medium.com/@kishanptl-kp?source=rss-cd54f0568629------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*uKcF4INculyJxI2Q40UCvA.png</url>
            <title>Stories by Kishan Patel on Medium</title>
            <link>https://medium.com/@kishanptl-kp?source=rss-cd54f0568629------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 18:50:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kishanptl-kp/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[Typescript FAQs]]></title>
            <link>https://kishanptl-kp.medium.com/typescript-faqs-7d9ca8f78d74?source=rss-cd54f0568629------2</link>
            <guid isPermaLink="false">https://medium.com/p/7d9ca8f78d74</guid>
            <dc:creator><![CDATA[Kishan Patel]]></dc:creator>
            <pubDate>Thu, 22 May 2025 09:04:03 GMT</pubDate>
            <atom:updated>2025-05-22T10:44:55.690Z</atom:updated>
            <content:encoded><![CDATA[<h3>Types in Typescript</h3><pre>// Boolean<br>let isDone: boolean = false;<br><br>// Number<br>let decimal: number = 6;<br>let hex: number = 0xf00d;<br>let binary: number = 0b1010;<br>let octal: number = 0o744;<br>let big: bigint = 100n;<br><br>// String<br>let color: string = &quot;blue&quot;;<br><br>// Array<br>let list: number[] = [1, 2, 3];<br><br>// Tuple, must follow the sequence<br>let x: [string, number];<br>x = [&quot;hello&quot;, 10]; // OK<br>// Initialize it incorrectly<br>x = [10, &quot;hello&quot;]; // Error<br><br>// Enum<br>enum Color {<br>  Red = 1,<br>  Green,<br>  Blue,<br>}<br>let c: Color = Color.Green;<br>console.log(c); // 2<br><br><br>// Unknown<br>let notSure: unknown = 4;<br>notSure = &quot;maybe a string instead&quot;;<br>notSure = false;<br><br>// Any<br>let looselyTyped: any = 4;<br><br>// Void, if there is no return from a method<br>function warnUser(): void {<br>  console.log(&quot;This is my warning message&quot;);<br>}<br><br>// Null and Undefined<br>// Not much else we can assign to these variables!<br>let u: undefined = undefined;<br>let n: null = null;<br><br><br><br>// Never<br>// Function returning never must not have a reachable end point<br>function error(message: string): never {<br>  throw new Error(message);<br>}<br> <br>// Inferred return type is never<br>function fail() {<br>  return error(&quot;Something failed&quot;);<br>}<br> <br>// Function returning never must not have a reachable end point<br>function infiniteLoop(): never {<br>  while (true) {}<br>}<br><br><br>// Object<br>const car: { type: string, model: string, year: number } = {<br>  type: &quot;Toyota&quot;,<br>  model: &quot;Corolla&quot;,<br>  year: 2009<br>};</pre><h3>Interface Vs Types</h3><p>Typescript:</p><p>Example to define a type</p><pre>type UserType = {<br>  name: string,<br>  age: number<br>}</pre><p>Example to define an interface</p><pre>interface UserInter {<br>  name: string,<br>  age: number<br>}</pre><p>No way to define this in the interface, an interface must be an object.</p><pre>type IdType = string;</pre><p>We can have OR (|) and AND(&amp;) in types, but in the interface, we can’t define them.</p><pre>type SType = { name: string } | { age: number };<br>type SType = { name: string } &amp; { age: number };</pre><p>Interface can extend another interface,</p><pre>interface AgeInter { age: integer }<br>interface UserInter extends AgeInter {<br>  name: string<br>}</pre><p>A few minor advantages of the interface:</p><ul><li>Slightly faster than types. But the difference is neglisible</li><li>Can merge multiple interfaces</li></ul><pre>interface User {<br>  name: string<br>}<br>interface User {<br>  age: number<br>}<br><br>const user: User = {<br>  name: &quot;Kishan&quot;,<br>  age: 30<br>}</pre><p>In the above example, we must have to provide both name &amp; age. It can be an advantage but also can be a drawback because if you wanted to define a new type for the user through the interface it would merge both types.</p><blockquote>In most cases, we use an interface if the types are not going to change and are fixed.</blockquote><p>In the case of type if you are defining it twice it will through an error</p><pre>type User = {<br>  name: string<br>}<br>// Error: Duplicate identifier &#39;User&#39;<br>type User = {<br>  age: integer<br>}</pre><h3>Use Typescript efficiently</h3><p>Let’s say the is a situation where one key is required only on a particular condition. Let’s look at the example below,</p><pre>type LocationState = {<br>  state: &quot;Loading&quot; | &quot;Success&quot; | &quot;Error&quot;,<br>  coords?: { lat: number, lon: number },<br>  error?: { message: string }<br>}<br><br>function printLoaction(location: LocationState) {<br>  switch (location.state) {<br>    case &quot;Loading&quot;:<br>      console.log(location.state);<br>      break;<br>    case &quot;Success&quot;:<br>      console.log(location.coords.lat, location.coords.lon);<br>    break;<br>    case &quot;Error&quot;:<br>      console.log(location.error.message);<br>      break;<br>    }<br>  }</pre><p>In the above example for the</p><ul><li>Loading state =&gt; coords and error are optional</li><li>Success state =&gt; error is optional</li><li>Error state =&gt; coords is optional</li></ul><p>Instead of doing this, we should use discriminating unions, it makes it much more useful to work on.</p><p>Let’s use discriminating union types</p><pre><br>type LoadingLocationState = {<br>  state: &quot;Loading&quot;<br>}<br><br>type SuccessLocationState = {<br>  state: &quot;Success&quot;,<br>  coords: { lon: string, lat: string }<br>}<br><br>type ErrorLocationState = {<br>  state: &quot;Error&quot;,<br>  error: { message: string } <br>}<br><br>type LocationState = LoadingLocationState | SuccessLocationState | ErrorLocationState;</pre><h3>Pick and Omit</h3><p>Essentially, these are the utility types that construct a type by picking (or omitting) the set of properties Keys (string literal or union of string literals) from Type , which already exists.</p><p>Here’s the basic structure of these utility types:</p><p>Pick&lt;Type, Keys&gt; Omit&lt;Type, Keys&gt;</p><pre>type User = {<br>  id: string;<br>  name: string;<br>  email: string;<br>  age: string;<br>};<br><br>// types of id and email are matched with User type.<br>export type EmpInfoA = {<br>  id: string;<br>  email: string;<br>}<br><br>// Pick the id and email fields from the User type<br>export type EmpInfoB = Pick&lt;User, &#39;id&#39; | &#39;email&#39;&gt;<br><br>// all key and types are required except few<br>export type EmpInfoC = {<br>  name: string;<br>  email: string;<br>  age: string;<br>}<br><br>// Just omit id from the User type<br>export type EmpInfoD = Omit&lt;User, &#39;id&#39;&gt;<br><br>// types of name and age are matched with User type.<br>export type TechTeamA = {<br>  id: string;<br>  members: { name: string, age: string }[]<br>};<br><br>// Pick the name and age fields from the User type<br>export type TechTeamB = {<br>  id: string;<br>  members: Pick&lt;User, &#39;name&#39; | &#39;age&#39;&gt;[]<br>}</pre><h4>Extract and Exclude for union</h4><p>Example of extract</p><pre>// a set of four specific things<br>type FavoriteColors =<br>  | &quot;dark sienna&quot;<br>  | &quot;van dyke brown&quot;<br>  | &quot;yellow ochre&quot;<br>  | &quot;sap green&quot;<br>  | &quot;titanium white&quot;<br>  | &quot;phthalo green&quot;<br>  | &quot;prussian blue&quot;<br>  | &quot;cadium yellow&quot;<br>  | [number, number, number]<br>  | { red: number; green: number; blue: number }<br> <br>// Example 1, to extrace all strings<br>type StringColors =<br>  | &quot;dark sienna&quot;<br>  | &quot;van dyke brown&quot;<br>  | &quot;yellow ochre&quot;<br>  | &quot;sap green&quot;<br>  | &quot;titanium white&quot;<br>  | &quot;phthalo green&quot;<br>  | &quot;prussian blue&quot;<br>  | &quot;cadium yellow&quot;<br><br>type StringColors = Extract&lt;FavoriteColors, string&gt;<br><br>// Example 2, to extract all object with { red: number }<br>type ObjectColors = {<br>    red: number;<br>    green: number;<br>    blue: number;<br>}<br><br>type ObjectColors = Extract&lt;FavoriteColors, { red: number }&gt;<br><br>// Example 3<br>type TupleColors = [number, number, number]<br><br>type TupleColors<br>  = Extract&lt;FavoriteColors, [number, number, number]&gt;<br><br>// Example 4<br>type ObjectColors = Extract&lt;FavoriteColors, object&gt;;<br><br>type ObjectColors = [number, number, number] | {<br>    red: number;<br>    green: number;<br>    blue: number;<br>}</pre><p>Example of Exclude</p><pre>// a set of four specific things<br>type FavoriteColors =<br>  | &quot;dark sienna&quot;<br>  | &quot;van dyke brown&quot;<br>  | &quot;yellow ochre&quot;<br>  | &quot;sap green&quot;<br>  | &quot;titanium white&quot;<br>  | &quot;phthalo green&quot;<br>  | &quot;prussian blue&quot;<br>  | &quot;cadium yellow&quot;<br>  | [number, number, number]<br>  | { red: number; green: number; blue: number }<br> <br>type NonStringColors = Exclude&lt;FavoriteColors, string&gt;<br>           <br>type NonStringColors = [number, number, number] | {<br>    red: number;<br>    green: number;<br>    blue: number;<br>}</pre><h4>Prettify Type</h4><p>When we are using complex type where we have used Omit, Pick Exclude in that case we can’t know all types just by hovering on the object. We can use a customised Prettify type which will give us proper visualition of the object by hovering on it</p><pre>type Prettify&lt;T&gt; = {<br>  [K in type of T]: T[K]<br>} &amp; {}</pre><p>Example:</p><pre>type Other = {<br>  d: string;<br>  f: string;<br>  e: string;<br>}<br><br>type showMe = {<br>  a: string;<br>  b: string;<br>} &amp; {<br>  c: string;<br>} &amp; Pick&lt;Other, &#39;d&#39; | &#39;e&#39;&gt;<br><br>type Prettify&lt;T&gt; = {<br>  [K in keyof T]: T[K]<br>};<br><br>type showMeNow = Prettify&lt;showMe&gt;;<br><br>/*<br>After prettify you can the type like this on hover<br>type showMeNow = {<br>    a: string;<br>    b: string;<br>    c: string;<br>    d: string;<br>    e: string;<br>}<br>*/<br></pre><h4>Autocomplete</h4><p>If we have defined few values to the type then we will get autocomplete and it will not except except defined values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1016/1*aqvde_Pk3sSKyrM7HLKNWw.png" /></figure><p>We will loose autocomplete when we want to allow any values with defined values, in below example autocomplete will not work as expected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*BOaEz1vozqdpdAmhakFt_w.png" /></figure><p>Let’s fix the problem</p><pre>type Fruit =<br>  | &#39;Apple&#39;<br>  | &#39;Banana&#39;<br>  | &#39;Pineaaple&#39;<br>  | &#39;Mango&#39;<br>  | (string &amp; Record&lt;string, never&gt;);<br><br>const fruit: Fruit = &#39;&#39;;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LwNO6ZYAmgmmX1jiI8z7xg.png" /></figure><h4>Key Mapping: Capatilise all keys</h4><pre>type User = {<br>  id: string;<br>  name: string;<br>  age: number<br>}<br><br>type UserTransformed = {<br>  [K in keyof User as Capitalize&lt;K&gt;]: User[K]<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/823/1*jAuqI8ZZTC_H7Asn_JjINw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7d9ca8f78d74" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Javascript Promise & Promise APIs]]></title>
            <link>https://kishanptl-kp.medium.com/javascript-promise-promise-apis-72a2702147ea?source=rss-cd54f0568629------2</link>
            <guid isPermaLink="false">https://medium.com/p/72a2702147ea</guid>
            <category><![CDATA[promises-in-javascript]]></category>
            <category><![CDATA[promises]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Kishan Patel]]></dc:creator>
            <pubDate>Thu, 23 Nov 2023 09:29:31 GMT</pubDate>
            <atom:updated>2023-11-23T11:47:21.903Z</atom:updated>
            <content:encoded><![CDATA[<p>A Promise is an object representing the eventual completion or failure of an asynchronous operation.</p><p>Promises are used to handle asynchronous operations in JavaScript. They are easy to manage when dealing with multiple asynchronous operations where callbacks can create callback hell leading to unmanageable code.</p><p>Components of Promise</p><ul><li><strong>State</strong></li><li><strong>Result</strong> (the result of promise is immutable)</li></ul><p>A promise has three states:</p><ul><li><strong>pending</strong>: the promise is still in the works</li><li><strong>fulfilled</strong>: the promise resolves successfully and returns a value</li><li><strong>rejected</strong>: the promise fails with an error</li></ul><p>What does promise look like,</p><pre>createOrder(cart)<br>  .then((orderId) =&gt; {<br>    return fetchPaymentDetails(orderId);<br>  })<br>  .then((paymentDetails) =&gt; {<br>    return processPayment(paymentDetails);<br>  })<br>  .then((result) =&gt; {<br>    return showSuccessMessage(result);<br>  })</pre><p>Example 1:</p><pre>// producer<br>const examResult = new Promise((resolve, reject) =&gt; {<br>  const res = Math.floor((Math.random() * 100) + 1);<br>  if(res &gt;= 50 ) {<br>    resolve(`Pass: ${res}`)<br>  } else {<br>    const err = new Error(`Failed: ${res}`);<br>    reject(err); // rejection should be an error<br>  }<br>})<br><br>// consumer<br>examResult<br>  .then(res =&gt; console.log(res))<br>  .catch(err =&gt; console.error(err.message))<br>  .finally(() =&gt; console.log(&#39;Done!&#39;))</pre><p>Example of promise</p><pre>const cart = [&#39;Shoes&#39;, &#39;Shirt&#39;, &#39;Pant&#39;];<br><br>createOrder(cart)<br>  .then((orderId) =&gt; {<br>    return proceedToPayment(orderId); // keep returning promise to chain<br>  })<br>  .then((paymentId) =&gt; {<br>    console.log(&#39;Payment Successfull with paymentId:&#39;, paymentId);<br>  })<br>  .catch((err) =&gt; { // catch error from any of the above promise<br>    console.log(err.message);<br>  })<br>  .finally(() =&gt; { // finally block will always execute<br>    console.log(&#39;End of order!&#39;);<br>  });<br><br>function createOrder(cart) {<br>  return new Promise((resolve, reject) =&gt; {<br>    // Validate cart<br>    if(cart.length &gt;= 3) { // modify this to test error<br>      const orderId = &#39;12345&#39;;<br>      resolve(orderId);<br>    } else {<br>      const err = new Error(&#39;Invalid cart, Order not created!&#39;);<br>      reject(err);<br>    }<br>  })<br>};<br><br>function proceedToPayment(orderId) {<br>  return new Promise((resolve, reject) =&gt; {<br>    // Validate orderId<br>    if(orderId === &#39;12345&#39;) { // modify this to test error<br>      const paymentId = &#39;67890&#39;;<br>      resolve(paymentId);<br>    } else {<br>      const err = new Error(&#39;Invalid orderId, Payment not processed!&#39;);<br>      reject(err);<br>    }<br>  })<br>};</pre><h4>There are 4 types of promise APIs</h4><ul><li>Promise.all</li><li>Promise.allSatteled</li><li>Promise.race</li><li>Promise.any</li></ul><h3>Promise.all</h3><p>The Promise.all() static method takes an iterable of promises as input and returns a single Promise.</p><ul><li>It will wait for all of them to finish.</li><li>As soon as any promise gets rejected, Promise.all will throw the same error received from the rejected promise (p2). It will not wait for other promises to get successful/rejected.</li><li>That means you will get all data(if all are succeed) or error (if anyone is rejected)</li></ul><p>Let’s understand it through example.</p><ul><li>All promise succeeds</li></ul><pre>const p1 = new Promise((success, reject) =&gt; {<br>    setTimeout(() =&gt; {<br>        success(&#39;P1 Success.&#39;);<br>    }, 3000)<br>})<br><br>const p2 = new Promise((success, reject) =&gt; {<br>    setTimeout(() =&gt; {<br>        success(&#39;P2 Success.&#39;);<br>    }, 1000)<br>})<br><br>const p3 = new Promise((success, reject) =&gt; {<br>    setTimeout(() =&gt; {<br>        success(&#39;P3 Success.&#39;);<br>    }, 2000)<br>})<br><br><br>const allPromise = Promise.all([p1, p2, p3]);<br><br>allPromise.then(res =&gt; console.log(JSON.stringify(res, null, 2)))<br><br>// Output<br>/*<br>[<br>  &quot;P1 Success.&quot;,<br>  &quot;P2 Success.&quot;,<br>  &quot;P3 Success.&quot;<br>]<br>*/</pre><ul><li>Any promise rejected</li></ul><pre>const p1 = new Promise((success, reject) =&gt; {<br>    setTimeout(() =&gt; {<br>        success(&#39;P1 Success.&#39;);<br>    }, 3000)<br>})<br><br>const p2 = new Promise((success, reject) =&gt; {<br>    setTimeout(() =&gt; {<br>        success(&#39;P2 Success.&#39;);<br>    }, 1000)<br>})<br><br>const p3 = new Promise((success, reject) =&gt; {<br>    setTimeout(() =&gt; {<br>        reject(&#39;P3 Rejected.&#39;);<br>    }, 2000)<br>})<br><br><br>const allPromise = Promise.all([p1, p2, p3]);<br><br>allPromise<br>.then(res =&gt; console.log(JSON.stringify(res, null, 2)))<br>.catch(err =&gt; console.error(err))<br><br>// P3 Rejected.</pre><h3>Promise.allSatteled</h3><p>Promise.allSettled() also takes an iterable of promises as input and returns a single Promise.</p><p>We can use Promise.allSettled() when we want to get results from all promises even if few/all promises are rejected.</p><p>Here, after 1s p2 gets rejected but Promise.allSetteled will still wait for other promises to be completed and it will give us a result from all promises</p><p>In case of success of all promises, the result will be [val1, val2, val3]</p><p>In case of failure of any promise, the result will be: [val1, error2, val3].</p><ul><li>All succeed</li></ul><pre>const p1 = new Promise((success, reject) =&gt; {<br>    setTimeout(() =&gt; {<br>        success(&#39;P1 Success.&#39;);<br>    }, 3000)<br>})<br><br>const p2 = new Promise((success, reject) =&gt; {<br>    setTimeout(() =&gt; {<br>        success(&#39;P2 Success.&#39;);<br>    }, 1000)<br>})<br><br>const p3 = new Promise((success, reject) =&gt; {<br>    setTimeout(() =&gt; {<br>        success(&#39;P3 Success.&#39;);<br>    }, 2000)<br>})<br><br>const allPromise = Promise.allSettled([p1, p2, p3]);<br><br>allPromise.then(res =&gt; console.log(JSON.stringify(res, null, 2)))<br><br><br><br>// Output<br><br>/*<br>[<br>  {<br>    &quot;status&quot;: &quot;fulfilled&quot;,<br>    &quot;value&quot;: &quot;P1 Success.&quot;<br>  },<br>  {<br>    &quot;status&quot;: &quot;fulfilled&quot;,<br>    &quot;value&quot;: &quot;P2 Success.&quot;<br>  },<br>  {<br>    &quot;status&quot;: &quot;fulfilled&quot;,<br>    &quot;value&quot;: &quot;P3 Success.&quot;<br>  }<br>]<br>*/</pre><ul><li>Few rejected</li></ul><pre>const p1 = new Promise((success, reject) =&gt; {<br>    setTimeout(() =&gt; {<br>        success(&#39;P1 Success.&#39;);<br>    }, 3000)<br>})<br><br>const p2 = new Promise((success, reject) =&gt; {<br>    setTimeout(() =&gt; {<br>        success(&#39;P2 Success.&#39;);<br>    }, 1000)<br>})<br><br>const p3 = new Promise((success, reject) =&gt; {<br>    setTimeout(() =&gt; {<br>        reject(&#39;P3 Rejected.&#39;);<br>    }, 2000)<br>})<br><br>const allPromise = Promise.allSettled([p1, p2, p3]);<br><br>allPromise.then(res =&gt; console.log(JSON.stringify(res, null, 2)))<br><br><br><br>// Output<br><br>/*<br>[<br>  {<br>    &quot;status&quot;: &quot;fulfilled&quot;,<br>    &quot;value&quot;: &quot;P1 Success.&quot;<br>  },<br>  {<br>    &quot;status&quot;: &quot;fulfilled&quot;,<br>    &quot;value&quot;: &quot;P2 Success.&quot;<br>  },<br>  {<br>    &quot;status&quot;: &quot;rejected&quot;,<br>    &quot;reason&quot;: &quot;P3 Rejected.&quot;<br>  }<br>]<br>*/</pre><h3>Promise.race</h3><p>The Promise.race() takes an iterable of promises as input and returns a single Promise. This returned promise settles with the eventual state of the first promise that settles.</p><p>This means, the first finisher will be returned, it does not matter if it succeeds or is rejected.</p><ul><li>The first finisher succeed</li></ul><pre>const p1 = new Promise((success, reject) =&gt; {<br>    setTimeout(() =&gt; {<br>        success(&#39;P1 Success.&#39;);<br>    }, 3000)<br>})<br><br>const p2 = new Promise((success, reject) =&gt; {<br>    setTimeout(() =&gt; {<br>        success(&#39;P2 Success.&#39;);<br>    }, 1000)<br>})<br><br>const p3 = new Promise((success, reject) =&gt; {<br>    setTimeout(() =&gt; {<br>        success(&#39;P3 Success.&#39;);<br>    }, 2000)<br>})<br><br><br>const allPromise = Promise.race([p1, p2, p3]);<br><br>allPromise<br>.then(res =&gt; console.log(res))<br>.catch(err =&gt; console.error(err))<br><br>// Will get result after 1 second<br>// P2 Success.</pre><ul><li>The first finisher gets rejected</li></ul><pre>const p1 = new Promise((success, reject) =&gt; {<br>    setTimeout(() =&gt; {<br>        success(&#39;P1 Success.&#39;);<br>    }, 3000)<br>})<br><br>const p2 = new Promise((success, reject) =&gt; {<br>    setTimeout(() =&gt; {<br>        reject(&#39;P2 Rejected.&#39;);<br>    }, 1000)<br>})<br><br>const p3 = new Promise((success, reject) =&gt; {<br>    setTimeout(() =&gt; {<br>        success(&#39;P3 Success.&#39;);<br>    }, 2000)<br>})<br><br><br>const allPromise = Promise.race([p1, p2, p3]);<br><br>allPromise<br>.then(res =&gt; console.log(res))<br>.catch(err =&gt; console.error(err))<br><br>// Will get result after 1 second<br>// P2 Rejected.</pre><h3>Promise.any</h3><p>Similar to Promise.race but it will wait to get any first success result.</p><p><strong>What if everything fails?</strong></p><p>It rejects when all of the input&#39;s promises are rejected (including when an empty iterable is passed), with an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/AggregateError">AggregateError</a> containing an array of rejection reasons.</p><ul><li>The first finisher succeed</li></ul><pre>const p1 = new Promise((success, reject) =&gt; {<br>    setTimeout(() =&gt; {<br>        success(&#39;P1 Success.&#39;);<br>    }, 3000)<br>})<br><br>const p2 = new Promise((success, reject) =&gt; {<br>    setTimeout(() =&gt; {<br>        success(&#39;P2 Success.&#39;);<br>    }, 1000)<br>})<br><br>const p3 = new Promise((success, reject) =&gt; {<br>    setTimeout(() =&gt; {<br>        success(&#39;P3 Success.&#39;);<br>    }, 2000)<br>})<br><br>const allPromise = Promise.any([p1, p2, p3]);<br>allPromise<br>.then(res =&gt; console.log(res))<br>.catch(err =&gt; console.error(err))<br>// Will get result after 1 second from p2<br>// P2 Success.</pre><ul><li>The first finisher gets rejected</li></ul><pre>const p1 = new Promise((success, reject) =&gt; {<br>    setTimeout(() =&gt; {<br>        success(&#39;P1 Success.&#39;);<br>    }, 3000)<br>})<br><br>const p2 = new Promise((success, reject) =&gt; {<br>    setTimeout(() =&gt; {<br>        reject(&#39;P2 Rejected.&#39;);<br>    }, 1000)<br>})<br>const p3 = new Promise((success, reject) =&gt; {<br>    setTimeout(() =&gt; {<br>        success(&#39;P3 Success.&#39;);<br>    }, 2000)<br>})<br><br>const allPromise = Promise.any([p1, p2, p3]);<br>allPromise<br>.then(res =&gt; console.log(res))<br>.catch(err =&gt; console.error(err))<br><br>// Will get result after 2second from p3<br>// P3 Succeed.</pre><ul><li>All Promise gets rejected</li></ul><pre>const p1 = new Promise((success, reject) =&gt; {<br>    setTimeout(() =&gt; {<br>        reject(&#39;P1 Rejected.&#39;);<br>    }, 3000)<br>})<br><br>const p2 = new Promise((success, reject) =&gt; {<br>    setTimeout(() =&gt; {<br>        reject(&#39;P2 Rejected.&#39;);<br>    }, 1000)<br>})<br><br>const p3 = new Promise((success, reject) =&gt; {<br>    setTimeout(() =&gt; {<br>        reject(&#39;P3 Rejected.&#39;);<br>    }, 2000)<br>})<br><br>const allPromise = Promise.any([p1, p2, p3]);<br>allPromise<br>.then(res =&gt; console.log(res))<br>.catch(err =&gt; console.error(err))<br><br>// Will get output after 3s<br>/*<br>ERROR!<br>[AggregateError: All promises were rejected] {<br>  [errors]: [ &#39;P1 Rejected.&#39;, &#39;P2 Rejected.&#39;, &#39;P3 Rejected.&#39; ]<br>}<br>*/<br><br>// We can get all errors through the err object like this `err.errors`<br>allPromise<br>.then(res =&gt; console.log(res))<br>.catch(err =&gt; console.log(err.errors));<br><br>// Output will be: [ &#39;P1 Rejected.&#39;, &#39;P2 Rejected.&#39;, &#39;P3 Rejected.&#39; ]</pre><p>Checkout my articles on Javascript:</p><ul><li><a href="https://kishanptl-kp.medium.com/javascript-faqs-eb2e828a0593">FAQs on Javascript</a></li><li><a href="https://kishanptl-kp.medium.com/deep-dive-into-javascript-70ae7735670">Deep dive into Javascript</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=72a2702147ea" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[FAQs on React JS]]></title>
            <link>https://kishanptl-kp.medium.com/react-js-52b1b1b094c8?source=rss-cd54f0568629------2</link>
            <guid isPermaLink="false">https://medium.com/p/52b1b1b094c8</guid>
            <category><![CDATA[interview-questions]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[react-js-tutorials]]></category>
            <dc:creator><![CDATA[Kishan Patel]]></dc:creator>
            <pubDate>Fri, 02 Jun 2023 05:45:44 GMT</pubDate>
            <atom:updated>2026-02-26T10:47:48.619Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>A Javascript library for building user interface</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A5FQ5qocIUVjyBSMjJYDlA.png" /></figure><h3>How to create React app</h3><p>Note: React doesn’t support camelCase while creating an application</p><pre>$ npx create-react-app burger-builder</pre><blockquote>Nowadays <a href="https://vitejs.dev/">VITE</a> is getting more popular over create-react-app, check out their <a href="https://vitejs.dev/">official website</a> to learn more.</blockquote><h4>A simple React example:</h4><pre>const root = ReactDOM.createRoot(document.getElementById(&#39;root&#39;));<br>root.render(&lt;h1&gt;Hello, world!&lt;/h1&gt;);</pre><p><strong>Why Babel is used in React</strong></p><p>Babel is used to transpile modern JavaScript syntax into code that can run in all environments when writing React components. This allows developers to use the latest language features when writing React components and ensures compatibility with older browsers.</p><p>In short, it is used to convert ECMAScript 2015+ code into a backward-compatible version of JavaScript in current and older browsers or environments.</p><p><strong>What is Virtual DOM?</strong></p><ul><li>The virtual DOM (VDOM) is a programming concept where an ideal, or “virtual”, representation of a UI is kept in memory and synced with the “real” DOM by a library such as ReactDOM.</li><li>Each time the underlying data changes, new virtual DOM is created, comparing differences between the previous virtual DOM, &amp; only the changes are updated in the real DOM.</li><li>So, the special thing about<em> ReactDOM.render() </em>is that it only updates DOM elements that have changed.</li></ul><h4>What is JSX?</h4><p><em>JSX</em> is a syntax extension for JavaScript that lets you write HTML-like markup inside a JavaScript file.</p><p>Rules of JSX</p><ul><li>Return a single root element</li><li>Close all the tags</li><li>JSX will use this capitalization to tell the difference between an HTML tag and a component instance. If the first letter of a name is capitalized, then JSX knows it’s a component instance; if not, then it’s an HTML element. // This is considered a component by React. // This is considered a JSX HTML tag.</li></ul><h4>React.createElement</h4><p>React.createElement accepts 3 parameter,</p><ul><li>Name of the tag (e.g. h1, div, p etc)</li><li>Attributes (e.g. {id: ‘heading’}), if attributes not required then pass null</li><li>Children (array of elements)</li></ul><p>Example of how a component looks like without JSX</p><pre>const root = ReactDOM.createRoot(document.getElementById(&#39;root&#39;));<br><br>class HelloMessage extends React.Component {<br>  render() {<br>    return React.createElement(<br>      &quot;div&quot;,<br>      null,<br>      React.createElement(<br>        &quot;h1&quot;,<br>        null,<br>        &quot;Hello &quot;,<br>        this.props.name<br>      ),<br>      React.createElement(<br>        &quot;div&quot;,<br>        null,<br>        React.createElement(<br>          &quot;p&quot;,<br>          null,<br>          &quot;Description&quot;<br>        ),<br>        React.createElement(<br>          &quot;small&quot;,<br>          null,<br>          &quot;Sub Description&quot;<br>        )<br>      )<br>    );<br>  }<br>}<br><br>root.render(React.createElement(HelloMessage, { name: &quot;Kishan&quot; }));</pre><p>With JSX</p><pre>const root = ReactDOM.createRoot(document.getElementById(&#39;root&#39;));<br><br>class HelloMessage extends React.Component {<br>  render() {<br>    return &lt;div&gt;<br>      &lt;h1&gt;Hello {this.props.name}&lt;/h1&gt;<br>        &lt;div&gt;<br>          &lt;p&gt;Description&lt;/p&gt;<br>          &lt;small&gt;Sub Description&lt;/small&gt;<br>        &lt;/div&gt;<br>    &lt;/div&gt;;<br>  }<br>}<br><br>root.render(&lt;HelloMessage name=&quot;Kishan&quot; /&gt;);</pre><h3>Props</h3><p>In ReactJS, the props or “properties” are a type of object where the value of attributes of a tag is stored. To be more simple props are like function arguments in JavaScript <em>and</em> attributes in HTML.</p><p>In the above example passing the name as a propto the HelloMessage component.</p><p>We can write components in two ways</p><ul><li>Functional based component</li></ul><pre>const root = ReactDOM.createRoot(document.getElementById(&#39;root&#39;));<br><br>function Clock(props) {<br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;Hello, world!&lt;/h1&gt;<br>      &lt;h2&gt;It is {props.date.toLocaleTimeString()}.&lt;/h2&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>function tick() {<br>  root.render(&lt;Clock date={new Date()} /&gt;);<br>}<br><br>setInterval(tick, 1000);</pre><ul><li>Class based component</li></ul><pre>class Clock extends React.Component {<br>  render() {<br>    return (<br>      &lt;div&gt;<br>        &lt;h1&gt;Hello, world!&lt;/h1&gt;<br>        &lt;h2&gt;It is {this.props.date.toLocaleTimeString()}.&lt;/h2&gt;<br>      &lt;/div&gt;<br>    );<br>  }<br>}</pre><h4>Dynamic Props</h4><pre>let dynamicProps = {&quot;name&quot;: &quot;Jhon&quot;, &quot;age&quot;: 29};<br>&lt;MyComponent {...dynamicProps} /&gt;</pre><h4><strong>What is a State?</strong></h4><ul><li>A React component can access dynamic information in two ways: props and state.</li><li>Unlike props, a component’s state is not passed in from the outside. A component decides its own state.</li><li>To make a component have state, give the component a state property. This property should be declared inside of a constructor method, like this:</li></ul><h4>Handling Events</h4><pre>// Correct way to use click event<br><br>// without argument<br>&lt;button onClick={sayHello}&gt;Say Hello&lt;/button&gt;<br><br>// With Argument<br>&lt;button onClick={() =&gt; sayHelloName(&#39;Kishan&#39;)}&gt;Say Hello Name&lt;/button&gt;<br><br>// ---<br><br>/*<br>  Don&#39;t do like below code it will execute immediately <br>  on render without clicking the button <br>*/<br><br>&lt;button onClick={testClick()}&gt;Say Hello&lt;/button&gt;<br>&lt;button onClick={sayHelloName(&#39;Kishan&#39;)}&gt;Say Hello Name&lt;/button&gt;</pre><p>Example</p><pre>class App extends React.Component {<br>  render() {<br>    const sayHello = () =&gt; {<br>      alert(&#39;Hello there!&#39;);<br>    }<br><br>    const sayHello = (name) =&gt; { <br>      alert(`Hello ${name}!`);<br>    }<br>    return ( <br>      &lt;div&gt;<br>        &lt;h1&gt;Hello React&lt;/h1&gt;<br>        &lt;button onClick={sayHello}&gt;Click Me&lt;/button&gt;<br>        &lt;button onClick={() =&gt; sayHello(&#39;Kishan&#39;)}&gt;Click Me&lt;/button&gt;<br>      &lt;/div&gt;<br>    );<br>  } <br>} <br><br>ReactDOM.render(&lt;App /&gt;, document.getElementById(&quot;app&quot;));</pre><h3>React Hooks</h3><p>Hooks allow us to “hook” into React features such as state and lifecycle methods.</p><p>Hooks allow function components to have access to state and other React features. Because of this, class components are generally no longer needed.</p><p>There are 3 rules for hooks:</p><ul><li>Hooks can only be called inside React function components.</li><li>Hooks can only be called at the top level of a component.</li><li>Hooks cannot be conditional except use hook</li></ul><h3>useState</h3><ul><li>When you update a state it will re-render the component</li><li>useState always returns an array with two values i.e a state and a method to update the stage</li></ul><pre>import React, { useState } from &#39;react&#39;;<br><br>function Example() {<br>  // Declare a new state variable, which we&#39;ll call &quot;count&quot;<br>  const [count, setCount] = useState(0);<br>  const incrementCount = () =&gt; {<br>    // Correct way<br>    setCount(prevCount =&gt; prevCount + 1); // here count value will be 1<br>    setCount(prevCount =&gt; prevCount + 1); // here count value will be 2<br>    <br>    /* Incorrect way, because if you need to execute setCounttwo time then<br>      below code will give result with just one increment due to the <br>      count value is just value of count when we render our function<br>    */<br><br>    setCount(count + 1);  // here count value will be 1<br>    setCount(count + 1);  // here count value will not update to 2 it will 1<br>  }<br><br>  return (<br>    &lt;div&gt;<br>      &lt;p&gt;You clicked {count} times&lt;/p&gt;<br>      &lt;button onClick={() =&gt; incrementCount()}&gt;<br>        Increase Count<br>      &lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><h4>A function version of useState</h4><pre>import React, { useState } from &#39;react&#39;;<br><br>function countInitial() {<br>  console.log(&#39;run function&#39;);<br>  return 4;<br>}<br><br>function Example() {<br>  // this will execute every time on change <br>  // const [count, setCount] = useState(countInitial());<br><br>  // this will execute only on first render of the component<br>  const [count, setCount] = useState(() =&gt; countInitial());<br><br>  const incrementCounter = () =&gt; {<br>    setCount(prevCount =&gt; prevCount + 1);<br>  }<br><br>  const decrementCounter = () =&gt; {<br>    setCount(prevCount =&gt; prevCount -1);<br>  }<br><br>  return (<br>    &lt;div&gt;<br>      &lt;p&gt;You clicked {count} times&lt;/p&gt;<br>      &lt;button onClick={() =&gt; setCount(count + 1)}&gt;<br>        Increase Count<br>      &lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p><strong>Example of setState with Object</strong></p><pre>import { useState } from &#39;react&#39;;<br>export default function MovingDot() {<br>  const [user, setUser] = useState({<br>    name: &#39;&#39;,<br>    age: null<br>  });<br>  const updateName = (e) =&gt; {<br>    setUser({...user, name: e.target.value})<br>  }<br>  const updateAge = (e) =&gt; {<br>    setUser({...user, age: e.target.value})<br>  }<br>  return (<br>    &lt;div style={{padding: &#39;20px&#39;}}&gt;<br>      &lt;div style={{paddingBottom: &#39;20px&#39;}}&gt;<br>        &lt;input type=&quot;text&quot; onChange={(e) =&gt; updateName(e)} value={user.name} /&gt;<br>      &lt;/div&gt;<br>      &lt;div style={{marginBottom: &#39;20px&#39;}}&gt;<br>        &lt;input type=&quot;number&quot; onChange={(e) =&gt; updateAge(e)} value={user.age} /&gt;<br>      &lt;/div&gt;<br>      &lt;div style={{marginBottom: &#39;20px&#39;}}&gt;<br>        &lt;p&gt;User Name: {user.name}&lt;/p&gt;<br>        &lt;p&gt;User Age : {user.age}&lt;/p&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><h3>useEffect</h3><p>Example 1:</p><pre>import React, { useEffect, useState } from &#39;react&#39;;<br><br>const UseEffectTest = () =&gt; {<br><br>  const [counter, setCounter] = useState(0);<br>  const [resource, setResource] = useState(&#39;users&#39;);<br>  console.log(&#39;render&#39;);<br><br>  useEffect(() =&gt; {<br>    console.log(&#39;on mount&#39;);<br>  }, [])<br><br>  useEffect(() =&gt; {<br>    console.log(&#39;resource changed&#39;);<br>    fetch(`https://jsonplaceholder.typicode.com/${resource}`)<br>      .then(response =&gt; response.json())<br>      .then(json =&gt; console.log(json));<br>  }, [resource])<br><br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;UseEffectTest&lt;/h1&gt;<br>      &lt;div&gt;<br>        &lt;h2&gt;Counter: {counter}&lt;/h2&gt;<br>      &lt;/div&gt;<br>      &lt;button onClick={() =&gt; setCounter(counter + 1)}&gt;Increment Counter&lt;/button&gt;<br>      &lt;button onClick={() =&gt; setCounter(prevCounter =&gt; prevCounter - 1)}&gt;Deccrement Counter&lt;/button&gt;<br>      &lt;button onClick={() =&gt; setCounter(0)}&gt;Reset&lt;/button&gt;<br>      &lt;br /&gt;&lt;br /&gt;&lt;br /&gt;&lt;br /&gt;<br>      &lt;div&gt;Resource: {resource}&lt;/div&gt;<br>      &lt;button onClick={() =&gt; setResource(&#39;posts&#39;)}&gt;Posts&lt;/button&gt;<br>      &lt;button onClick={() =&gt; setResource(&#39;users&#39;)}&gt;Users&lt;/button&gt;<br>      &lt;button onClick={() =&gt; setResource(&#39;comments&#39;)}&gt;Comments&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default UseEffectTest;</pre><p>Example 2:</p><pre>import React, { useEffect, useState } from &#39;react&#39;;<br><br>const UseEffectTest = () =&gt; {<br><br>  const [windowWidth, setWindowWidth] = useState(window.innerWidth);<br>  const handleResize = () =&gt; {<br>    setWindowWidth(window.innerWidth);<br>  }<br><br>  useEffect(() =&gt; {<br>    window.addEventListener(&#39;resize&#39;, handleResize);<br>    return () =&gt; {<br>      console.log(&#39;removeEventListener on unmount&#39;);<br>      window.removeEventListener(&#39;resize&#39;, handleResize);<br>    }<br>  }, [])<br><br>  return (<br>    &lt;div&gt;<br>      &lt;h1&gt;UseEffectTest2&lt;/h1&gt;<br>      &lt;div&gt;Window width: {windowWidth}&lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default UseEffectTest;</pre><h3>useMemo</h3><p>The React useMemo hook returns a memoized value. The useMemo Hook only runs when one of its dependencies updates.</p><pre>import React, { useEffect, useState, useMemo } from &quot;react&quot;;<br>const UseMemoTest = () =&gt; {<br>  const [counter, setCounter] = useState(0);<br>  const [input, setInput] = useState(&quot;&quot;);<br><br>  useEffect(() =&gt; {}, []);<br><br>  const incrementCounter = () =&gt; {<br>    setCounter(counter + 1);<br>  };<br><br>  const counterMemo = useMemo(() =&gt; {<br>    console.log(&quot;counterMemo&quot;);<br>    return `Current counter: ${counter}`;<br>  }, [counter]);<br><br>  // get called every time when there is any state change (here on input change)<br>  // const counterMemo = () =&gt; {<br>  //   console.log(&#39;counterMemo&#39;);<br>  //   return `Current counter: ${counter}`;<br>  // };<br><br>  return (<br>    &lt;div&gt;<br>      &lt;h2&gt;Counter {counter}&lt;/h2&gt;<br>      &lt;div&gt;{counterMemo}&lt;/div&gt;<br>      {/* &lt;div&gt;{counterMemo()}&lt;/div&gt; */}<br>      &lt;button className=&quot;btn btn-primary&quot; onClick={incrementCounter}&gt;<br>        Increment<br>      &lt;/button&gt;<br>      &lt;div className=&quot;mt-3&quot;&gt;<br>        &lt;input<br>          type=&quot;text&quot;<br>          value={input}<br>          onChange={(e) =&gt; setInput(e.target.value)}<br>        /&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default UseMemoTest;</pre><h3>useCallback</h3><p>The useMemo and useCallback Hooks are similar. The main difference is that useMemo returns a memoized value and useCallback returns a memoized function.</p><pre>import React, { useState, useCallback } from &quot;react&quot;;<br>import Child from &quot;../components/UseMemoChild&quot;;<br>const UseCallbackTest = () =&gt; {<br>  const [todos, setTodos] = useState([]);<br>  const [input, setInput] = useState(&quot;&quot;);<br><br>  /* if you are passing a method as props without useCallback then it will re-render the<br>   component every time when there is any state change in the parent component. */<br>  /* means non related state change will also re-render the child component.<br>    const addTodo = () =&gt; {<br>      setTodos([...todos, `New Todo - ${todos.length + 1}`]);<br>    };<br>  */<br><br>  const addTodo = useCallback(() =&gt; {<br>    setTodos([...todos, `New Todo - ${todos.length + 1}`]);<br>  }, [todos]);<br><br>  const todoTypes = [&quot;Work&quot;, &quot;Personal&quot;, &quot;Shopping&quot;, &quot;Others&quot;];<br><br>  return (<br>    &lt;div&gt;<br>      &lt;h2&gt;useCallback&lt;/h2&gt;<br>      &lt;div className=&quot;mt-3&quot;&gt;<br>        &lt;input<br>          type=&quot;text&quot;<br>          value={input}<br>          onChange={(e) =&gt; setInput(e.target.value)}<br>        /&gt;<br>      &lt;/div&gt;<br>      &lt;Child todoTypes={todoTypes} todos={todos} addTodo={addTodo} /&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default UseCallbackTest;</pre><h4>memo()</h4><p>Using memo will cause React to skip rendering a component if its props have not changed.</p><pre>import React, { useEffect, memo } from &quot;react&quot;;<br>import { isEqual } from &quot;lodash&quot;;<br><br>// const customCheck = (prevProps, nextProps) =&gt; {<br>//   return JSON.stringify(prevProps) === JSON.stringify(nextProps);<br>// }<br><br>const Child = ({ todos, addTodo, counter, todoTypes }) =&gt; {<br>  useEffect(() =&gt; {<br>    console.log(&quot;Child called&quot;);<br>  });<br><br>  return (<br>    &lt;div&gt;<br>      &lt;h2&gt;My Todos&lt;/h2&gt;<br>      &lt;div&gt;<br>        &lt;button onClick={addTodo}&gt;Add Todo&lt;/button&gt;<br>        &lt;span&gt;Counter: {counter}&lt;/span&gt;<br>      &lt;/div&gt;<br>      &lt;div&gt;<br>        &lt;div&gt;<br>          {todos.map((todo, index) =&gt; {<br>            return &lt;span key={index}&gt;{todo}, &lt;/span&gt;;<br>          })}<br>        &lt;/div&gt;<br>      &lt;/div&gt;<br>      &lt;div&gt;todoTypes: {JSON.stringify(todoTypes)}&lt;/div&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>// if there is no memo then it will re-render the child component every time when there is any state change in the parent component.<br>// export default Child;<br>// export default memo(Child); // to prevent re-render for non premitive type props<br>// export default memo(Child, customCheck);<br>export default memo(Child, isEqual);  // to prevent re-render for premitive data as well but in parent component we need to use useCallback for functions and useMemo for non premitive data</pre><h3>Pure Component</h3><p>In React, a pure component is a class component that extends the React.PureComponent class, or a function component that utilizes the React.memo higher-order component. The purpose of a pure component is to optimize performance by reducing unnecessary re-renders.</p><pre>import React from &#39;react&#39;;<br><br>class MyComponent extends React.PureComponent {<br>  render() {<br>    return &lt;div&gt;{this.props.name}&lt;/div&gt;;<br>  }<br>}<br><br>// Function component with React.memo<br>const MyFunctionalComponent = React.memo(({ name }) =&gt; {<br>  return &lt;div&gt;{name}&lt;/div&gt;;<br>});</pre><p>In the above examples, both MyComponent and MyFunctionalComponent are pure components. They will only re-render if the name prop changes.</p><h4>useReducer</h4><p>The useReducer hook is similar to the useState hook. The reducer function contains your custom state logic and the initialStatecan be a simple value but generally will contain an object.</p><p>The useReducer hook returns the current stateand a dispatchmethod.</p><pre>import React, { useReducer } from &quot;react&quot;;<br><br>const ACTIONS = {<br>  INCREMENT: &#39;increment&#39;,<br>  DECREMENT: &#39;decrement&#39;<br>}<br><br>const UseReducerTest = () =&gt; {<br>  const reducer = (st, action) =&gt; {<br>    switch (action.type) {<br>      case ACTIONS.INCREMENT:<br>        return { count: st.count + 1 }<br>      case ACTIONS.DECREMENT:<br>        return { count: st.count - 1 }<br>      default:<br>        throw new Error()<br>    }<br>  }<br><br>  const [state, dispatch] = useReducer(reducer, { count: 0 })<br><br>  return (<br>    &lt;div&gt;<br>      &lt;button onClick={() =&gt; dispatch({ type: ACTIONS.DECREMENT })}&gt;Decrement Counter&lt;/button&gt;<br>      &lt;b style={{ fontSize: &#39;20px&#39;, margin: &#39;0 20px&#39; }}&gt;{state.count}&lt;/b&gt;<br>      &lt;button onClick={() =&gt; dispatch({ type: ACTIONS.INCREMENT })}&gt;Increment Counter&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default UseReducerTest;</pre><h4>useRef</h4><p>The useRef hook allows you to persist values between renders.</p><p>It can be used to store a mutable value that does not cause a re-render when updated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UgJ4km_HLj05ExVg1H3eiA.png" /></figure><p>useRef can be used to access a DOM element directly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*omGdTDw4godhZUN0NbmzbA.png" /></figure><h4>useContext</h4><p>React Context is a way to manage state globally.</p><p>It can be used together with the useState Hook to share state between deeply nested components more easily than with useState alone.</p><pre>const UserContext = React.createContext();<br><br>const FirstChild = () =&gt; {<br>  return(<br>    &lt;UserContext.Provider value={&#39;Kishan&#39;}&gt;<br>      Hello first child &lt;br /&gt;<br>      &lt;SecondChild /&gt;<br>    &lt;/UserContext.Provider&gt;<br>  )<br>}<br><br>const SecondChild = () =&gt; {<br>  return (<br>    &lt;div&gt;<br>      Hello second child. &lt;br /&gt;<br>      &lt;ThirdChild /&gt;<br>    &lt;/div&gt;<br>  )<br>}<br><br>const ThirdChild = () =&gt; {<br>  userName = React.useContext(UserContext);<br>  return (<br>    &lt;div&gt;<br>      Hello third child. &lt;br /&gt;<br>      Name: {userName}<br>    &lt;/div&gt;<br>  )<br>}<br> <br>const App = () =&gt; {<br>  return (<br>    &lt;div&gt;<br>      Hello App<br>      &lt;FirstChild /&gt;<br>    &lt;/div&gt;<br>  )<br>}<br><br><br>ReactDOM.render(&lt;App /&gt;, document.getElementById(&#39;root&#39;));</pre><h4>Custom Hooks</h4><p>When you have component logic that needs to be used by multiple components, we can extract that logic to a custom Hook.</p><p>It allows us to use a hook inside a function.</p><p>Custom Hooks start with “use”. Example: useFetch.</p><p>Let’s create a custom hook</p><pre>// useFetch.js:<br><br>import { useState, useEffect } from &quot;react&quot;;<br><br>const useFetch = (url) =&gt; {<br>  const [data, setData] = useState(null);<br><br>  useEffect(() =&gt; {<br>    fetch(url)<br>      .then((res) =&gt; res.json())<br>      .then((data) =&gt; setData(data));<br>  }, [url]);<br><br>  return [data];<br>};<br><br>export default useFetch;</pre><p>Now we can use it in any component</p><pre>import useFetch from &quot;./useFetch&quot;;<br><br>const Home = () =&gt; {<br>  const [data] = useFetch(&quot;https://jsonplaceholder.typicode.com/todos&quot;);<br><br>  return (<br>    &lt;&gt;<br>      {data &amp;&amp;<br>        data.map((item) =&gt; {<br>          return &lt;p key={item.id}&gt;{item.title}&lt;/p&gt;;<br>        })}<br>    &lt;/&gt;<br>  );<br>};<br><br>const root = ReactDOM.createRoot(document.getElementById(&#39;root&#39;));<br>root.render(&lt;Home /&gt;);</pre><h3>Render HTML string to dom</h3><p>Use <strong>dangerouslySetInnerHTML</strong></p><ul><li>It can be used if HTML elements are defined within the app. If an HTML string is provided by a user through the WYSIWYG editor better to use html-react-parser library to avoid <a href="https://en.wikipedia.org/wiki/Cross-site_scripting">cross-site scripting (XSS)</a> attacks.</li></ul><pre>&lt;div<br>  dangerouslySetInnerHTML={{ __html: &quot;&lt;strong&gt;strong text&lt;/strong&gt;&quot; }}<br>/&gt;</pre><p>Use html-react-parser library</p><pre>import parse from &#39;html-react-parser&#39;;</pre><pre>parse(&#39;&lt;div&gt;Hello there!&lt;/div&gt;&#39;);</pre><h3>Redux</h3><p>Redux is a state management system for cross-component or app-wide states.</p><p>States can be categorized into below types,</p><ul><li><strong>Local state</strong><br>| State management belongs to a single component. Generally, the local state can be managed by useState or if it’s complex can be managed by useReducer.</li><li><strong>Cross-component state</strong><br>| State that affects multiple components, but needs to pass props to child component.</li><li><strong>app-wide state</strong><br>| States that affect the entire app or multiple independent components. React Context and React Redux both can be used to manage state <strong>app-wide</strong>.</li></ul><h4>Why we need <strong>Redux Context</strong> instead of React Context:</h4><p>There are some potential disadvantages of React Context</p><ul><li><strong>Complex Setup</strong></li><li><strong>Management</strong></li><li><strong>Performance<br></strong>React context is not optimized for the high-frequency state change.</li></ul><p>It may not be a problem for small or medium size apps. But can be a problem for large apps.</p><p>In large apps, if you use context it can end up coding like this, with lots of different pieces of context and states.</p><p>Or if you want to use one large context it will be difficult to manage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/0*a9jLvEQ7SI4lu3o3" /></figure><h4>How does the Redux work?</h4><p>Redux is all about having a central store in your application. We can use this to store auth info, theming or form inputs.</p><p>We can summarize the flow of data through a Redux app with this diagram. It represents how:</p><ul><li>actions are dispatched in response to a user interaction like a click</li><li>the store runs the reducer function to calculate a new state</li><li>the UI reads the new state to display the new values</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MplnbJJag1XgBGb2.gif" /></figure><p>createStore() is deprecated instead of this React team suggesting to use of a new library react-toolkit.</p><p>Let’s go through the createStore() method first.</p><p>We need to install redux &amp; react-redux ( <em>react-redux </em>to connect redux to react app) package.</p><p>Let’s see the overall config of redux and how we can use it</p><ul><li>Create store</li></ul><pre>// store/index.js<br>import { createStore } &#39;redux&#39;;<br><br>const initalState = { counter: 0 }<br><br>const counterReducer(state = initalState, action ) {<br>  if(action.type === &#39;increment&#39;) {<br>    //. always return a brand new state<br>    return {...state, counter: state.counter + 1}<br>  } else<br>  if (action.type === &#39;decrement&#39;){<br>    return {...state, counter: state.counter + 1}<br>  } else {<br>    return {...state, counter: 0}<br>  }<br>}<br><br>export default createStore(counterReducer);</pre><ul><li>Provide the store to the highest level of the React app where we render the root component.</li></ul><pre>// src/index.js<br>import React from &#39;react&#39;;<br>import ReactDOM from &#39;react-dom/client&#39;;<br>import { Provider } from &#39;react-redux&#39;; // to connect redux to react app.<br>import store from &#39;./store/index&#39;;<br><br>import App from &#39;./App&#39;;<br>const root = ReactDOM.createRoot(document.getElementById(&#39;root&#39;));<br><br>// wrap the root component with Provider and link the store<br>root.render(&lt;Provider store={store}&gt;&lt;App /&gt;&lt;/Provider&gt;);</pre><ul><li>Now we can access the store from any component through useSelector in the app and update it through useDispatch.</li></ul><pre>// Counter.js<br>import { useSelector, useDispatch } from &#39;react-redux&#39;;<br><br>const Counter = () =&gt; {<br>  const counter = useSelector(state =&gt; state.counter);<br>  const dispatch = useDispatch();<br>  const incrementHandler = () =&gt; {<br>    dispatch({ type: &#39;increment&#39; });<br>  };<br><br>  const decrementHandler = () =&gt; {<br>    dispatch({ type: &#39;decrement&#39; });<br>  }<br><br>  return (<br>    &lt;div&gt;<br>      &lt;div&gt;Counter value: {counter}&lt;/div&gt;<br>      &lt;button onClick={incrementHandler}&gt;Increment&lt;/button&gt;<br>      &lt;button onClick={decrementHandler}&gt;Decrement&lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><h4>Pass argument to dispatch method</h4><ul><li>Let’s modify the counterReducer from the store to accept the payload</li></ul><pre>// store/index.js<br>// ...<br><br>const counterReducer(state = initalState, action ) {<br>  if(action.type === &#39;increment&#39;) {<br>    // increment by provided anount, if amount not present increment by 1<br>    const incrementAmount = action.amount || 1;<br>    return {...state, counter: state.counter + incrementAmount}<br>  }<br>  // ...<br>}</pre><ul><li>Now let’s update the component</li></ul><pre>// Counter.js<br>const incrementHandler = () =&gt; {<br>  dispatch({ type: &#39;increment&#39;, amount: 5 });<br>};</pre><p>There are some problems with this approach</p><ul><li>Managing all states in one reducer</li><li>Object immutability<br>return {…state, counter: state.counter + incrementAmount}</li></ul><h3>Use of @reduxjs/toolkit</h3><p>We can use @reduxjs/toolkit to manage the state efficiently and we no longer redux package to add explicitly because reduxjs/toolkit includes redux .</p><pre>// store/index.js<br>import { configureStore } from &quot;@reduxjs/toolkit&quot;;<br>import usersReducer from &quot;./users&quot;;<br><br>export const store = configureStore({<br>  reducer: {<br>    usersData: usersReducer,<br>  },<br>});<br><br>// --- end of store/index.js<br><br>// store/users.js<br>import { createSlice } from &quot;@reduxjs/toolkit&quot;;<br><br>const initialState = {<br>  users: [],<br>};<br><br>const usersSlice = createSlice({<br>  name: &quot;users&quot;,<br>  initialState,<br>  reducers: {<br>    setUsers: (state, action) =&gt; {<br>      state.users = action.payload;<br>    },<br>  }<br>})<br><br>export default usersSlice.reducer;<br>export const usersAction = usersSlice.actions;<br><br>// --- end of store/users.js<br><br>// srs/main.jsx<br>import React from &#39;react&#39;<br>import ReactDOM from &#39;react-dom/client&#39;<br>import { Provider } from &#39;react-redux&#39;;<br>import App from &#39;./App.jsx&#39;<br><br>import { store } from &#39;./store/index&#39;;<br><br>ReactDOM.createRoot(document.getElementById(&#39;root&#39;)).render(<br>  &lt;Provider store={store}&gt;<br>    &lt;App /&gt;<br>  &lt;/Provider&gt;,<br>)<br><br>// end of srs/main.jsx<br><br>// src/pages/users/index.js<br>import React, { useEffect} from &quot;react&quot;;<br>import { useSelector, useDispatch } from &quot;react-redux&quot;;<br>import { usersAction } from &#39;../store/users&#39;;<br>import UserList from &quot;@/components/userList&quot;;<br>const usersData = [<br>  { id: 1, name: &quot;John Doe&quot;, email: &quot;jhon@mail.com&quot; },<br>  { id: 2, name: &quot;Jane Doe&quot;, email: &quot;jane@mail.com&quot; },<br>]<br><br>export default function Home() {<br>  // usersData is reducer from store/index<br>  const { users } = useSelector(<br>    (state) =&gt; state.usersData.users;<br>  );<br><br>  const dispatch = useDispatch&lt;AppDispatch&gt;();<br><br>  useEffect(() =&gt; {<br>    // setting users data from component<br>    dispatch(usersAction.setUsers(usersData));<br>  }, []);<br><br>  return (<br>    &lt;div&gt;<br>      &lt;UserList users={users} /&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><h4>Is it okay to use useRef everywhere instead of useState in react</h4><p>No, it’s not recommended to use useRef everywhere instead of useState in React. While both useRef and useState are hooks in React, they serve different purposes and are designed for different use cases.</p><p><strong>useState:</strong></p><ul><li>useState is used to manage and update stateful data that affects the rendering of components.</li><li>When the state changes, React re-renders the component and updates the UI to reflect the new state.</li><li>The state updates trigger the component lifecycle methods and can cause re-renders.</li><li>State changes can be batched and optimized by React for better performance.</li></ul><p><strong>useRef:</strong></p><ul><li>useRef is primarily used for accessing and interacting with DOM elements and preserving values across renders.</li><li>Changes to the value of a useRef do not trigger re-renders.</li><li>It’s often used for things like getting the current value of an input field, managing focus, or storing values that should not cause re-renders (e.g., timers).</li></ul><p>Using useRef instead of useState everywhere can lead to unexpected behavior and make your code harder to understand and maintain. State changes that should trigger UI updates would not be reflected properly, and your components might not respond to changes as expected.</p><p>Here are some general guidelines:</p><p><strong>Use useState:</strong></p><ul><li>When you need to manage state that affects your component’s UI.</li><li>When you want your component to re-render when the state changes.</li><li>When you want to perform actions that depend on the current state and cause re-renders.</li></ul><p><strong>Use useRef:</strong></p><ul><li>When you need to access or interact with DOM elements.</li><li>When you want to store mutable values that don’t trigger re-renders.</li><li>When you need to store values across renders without causing re-renders.</li></ul><p>In summary, it’s important to use the appropriate hook for the specific use case you’re dealing with. Mixing up useState and useRef could lead to bugs and make your codebase harder to maintain.</p><h4><strong>New features/components</strong></h4><ul><li>Activity Component</li></ul><pre>&lt;Activity mode={isShowingSidebar ? &quot;visible&quot; : &quot;hidden&quot;}&gt;<br>  &lt;Sidebar /&gt;<br>&lt;/Activity&gt;</pre><p>Upcoming…</p><ul><li>routes</li><li>use hook</li><li>and many more…</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=52b1b1b094c8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep Dive into JavaScript]]></title>
            <link>https://kishanptl-kp.medium.com/deep-dive-into-javascript-70ae7735670?source=rss-cd54f0568629------2</link>
            <guid isPermaLink="false">https://medium.com/p/70ae7735670</guid>
            <category><![CDATA[hoisting]]></category>
            <category><![CDATA[js]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Kishan Patel]]></dc:creator>
            <pubDate>Sat, 27 May 2023 20:14:59 GMT</pubDate>
            <atom:updated>2024-02-15T11:47:44.202Z</atom:updated>
            <content:encoded><![CDATA[<p>Javascript is a synchronous single-threaded language. It means JS can execute single command at a time in a specific order.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1JgaxASQc9pcXAaq6q6BtQ.png" /></figure><h3>Highlights</h3><ul><li><a href="#2cf2">How does JS code run?</a></li><li><a href="#e69f">Hoisting</a></li><li><a href="#b44b">Lexical scope and chain scope</a></li><li><a href="#e410">Let, var &amp; const</a></li><li><a href="#a296">Block, scope, and shadowing</a></li><li><a href="#face">Closures</a></li><li><a href="#940b">Event Loops</a></li><li><a href="#d564">Web APIs</a></li><li><a href="#5f27">Callbacks</a></li><li><a href="#0cb2">Promise</a></li><li><a href="#1828">Debouncing &amp; Throttling</a></li><li><a href="#08b7">async and defer</a></li><li><a href="#3d0f">Prototype</a></li><li><a href="#bdb2">Functions in Javascript</a></li><li><a href="#03dc">Polyfills</a></li><li><a href="#46b6">Event Bubling &amp; Event Capturing(Trickling)</a></li></ul><h3>How does JS code run?</h3><p>Let’s take a simple example</p><pre>var n = 2;<br>function square (num) {<br>  var ans  = num * num;<br>  return ans;<br>}<br>var square2 = square(n);<br>var square4 = square(4);</pre><p>When we run JS code it creates a Global Execution Context(GEC) inside the call stack. The GEC was created in two-phase those are</p><ol><li>Memory creation phase</li></ol><p>In this phase, all the variables and functions are stored in memory. But the variable is stored with undefined value and functions are stored with all code copied to memory.</p><pre>|----------------------|-------------------------------|<br>|     Memory           |      Code                     |<br>|----------------------|-------------------------------|<br>| n:undefined          |                               |<br>| square: {...all code |                               |<br>|   copied to memory } |                               |<br>|                      |                               |<br>| square2: undefined   |                               |<br>| square4: undefined   |                               |<br>|----------------------|-------------------------------|</pre><p>Then, a new execution context is created for var square2 = square(n);, inside the code block, and all the new variables and functions are stored in memory inside the code creation phase.</p><pre>|----------------------|-------------------------------|<br>|     Memory           |      Code                     |<br>|----------------------|-------------------------------|<br>| n:undefined          | | Memory         | Code    |  |<br>| square: {...all code | |----------------|---------|  |<br>|   copied to memory } | | ans: undefined |         |  |<br>|                      | |                |         |  |<br>| square2: undefined   | |----------------|---------|  |<br>| square4: undefined   |                               |<br>|----------------------|-------------------------------|</pre><p>The Execution context will be deleted after the execution of the code. So the variable square2 will be stored in memory with the value 4.</p><p>And same for var square4 = square(4); a brand new execution context is created for this line again and will be deleted after the execution of the code.</p><p>And finally, the GEC will be deleted after the execution of the code.</p><h3>Hoisting</h3><p>Now we know how Javascript executes the code, so now with that let’s check what is Hoisting.</p><pre>var x = 10;<br><br>function sayHello() {<br>  console.log(&#39;Hello there!&#39;);<br>}<br><br>console.log(x); // 10<br>sayHello(); // Hello there!</pre><p>This is a simple example where we have defined a variable x and a function sayHello() and later we are executing it.</p><p>Now let’s call the function before its declaration and log the variable.</p><pre>console.log(x); // undefined<br><br>sayHello(); // Hello there!<br><br>var x = 10;<br><br>function sayHello() {<br>  console.log(&#39;Hello there!&#39;);<br>}</pre><p>As we know when a JS code is executed it creates a GEC with memory and code. And the first phase stores undefined for variables and stores the whole code block for functions inside the memory.</p><p>It means, even before the code starts executing memory is allocated to all variables and functions. that’s why even before defining the variable and function, we can get the value from memory.</p><p>In our case, we get the value of x as undefined and we got Hello there! from function.</p><pre>|----------------------|---------------|<br>|     Memory           |      Code     |<br>|----------------------|---------------|<br>| x:undefined          |               |<br>| sayName: {... stores |               |<br>|  all code of func    |               |<br>|  inside the memory } |               |<br>|                      |               |<br>|----------------------|---------------|</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C4sfEscutrxYaHCG8zCC0w.png" /></figure><p>but, it behaves differently for let and const .</p><p>let and const declarations are also hoisted to the top of their scope, but unlike var, they are not initialized inside the global object. Instead, they enter a <strong>temporal dead zone</strong> until the point of the declaration in the code. This means that if you try to access a let variable before its declaration, you will get a ReferenceError (Uncaught ReferenceError: Cannot access ‘xxx’ before initialization)</p><p>So we can say<strong>temporal dead zone</strong> is the time from when the let/const variable was hoisted until it is initialized with some value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1hIQ0rjUTjjUPbuBy4fjaA.png" /></figure><p>Another example</p><pre>var x = 1;<br>a();             // 10<br>b();             // 100       <br>console.log(x);  // 1<br><br>function a() {<br>  var x = 10;<br>  console.log(x);<br>}<br><br>function b() {<br>  var x = 100;<br>  console.log(x);<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ne-ZAvW4C0779WQV-KnMhA.png" /></figure><h3>Lexical scope and chain scope</h3><p>Lexical env is created whenever an execution context is created, and lexical env is a memory along with the reference to the lexical env of the parent.</p><p>Here function b is lexically inside function a and function b has reference to the function a’s lexical environment.</p><pre>function a() {<br>  var x = 10;<br>  function b() {<br>    console.log(x);<br>  }<br>  b();<br>}<br>a(); // 10</pre><h3>Chain scope</h3><p>The chain scope is the scope of a function along with the scope of it’s parent and grandparent and so on.</p><p>Example:</p><pre>function a() {<br>  var x = 10;<br>  function b() {<br>    function c() {<br>      console.log(x);<br>    }<br>    c();<br>  }<br>  b();<br>}<br>a(); // 10</pre><p>In this example inside function c, we have console.log(x), first, it will try to get the variable inside function c if it does not exist there then it will go to function b and then function a and then global scope. This is called the <strong><em>scope chain</em></strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0SDklk0WQ2-ayKkivuF9sw.png" /></figure><p>Let’s see it in the browser</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_giLilLYi2ix-oD6bIZadA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yYCt2_9jD64nLYq8yzQ_0w.png" /></figure><p>Another example</p><pre>let a = 10;<br>var b = 100;</pre><p>If we will run the above code, the var b is attached to the window object, but in case b it is not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rpnIWM3uo-35jFX4p6SLlQ.png" /></figure><h3>Let, var &amp; const</h3><p>let’s understand through an example</p><pre>console.log(a); // undefined -&gt; no error for var<br>var a = 10;<br>var a = 100; // no error at this line<br><br>console.log(b); // Uncaught ReferenceError: Cannot access &#39;a&#39; before initialization<br>let b = 10;<br>let b = 100; // Error: Uncaught SyntaxError: Identifier &#39;a&#39; has already been declared<br><br>// Same for const<br>const c = 10;<br>const c = 100; // Error: Uncaught SyntaxError: Identifier &#39;a&#39; has already been declared<br><br><br>// ****Difference between let and const****<br><br>// 1 &gt; We can re assign a value to a let variable but not to a const variable;<br><br>b = 100; // no error<br>c = 100; // Error: Uncaught TypeError: Assignment to constant variable.<br><br>// 2 &gt; In case of let we can define a variable and later we can assign a value<br>// but we can&#39;t do for const<br>let b2; <br>b2 = 20;<br><br>const c2; // Uncaught SyntaxError: Missing initializer in const declaration<br><br>// 3&gt; We can change the value of let but can&#39;t change value of const.<br><br>let b3 = 30;<br>b3 = 40;<br><br>const c3 = 25;<br>c3 = 35;  // Uncaught TypeError: Assignment to constant variable.</pre><h3>Block, scope, and shadowing</h3><p>A block is surrounded by { and } .</p><pre>{<br>  ....<br>}</pre><p>Let’s see how var, let and const are hoisted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Hun4WSW8fdd2zNGBv3vPxQ.png" /></figure><p>We can’t access block-scoped variables outside of the block,</p><pre>{<br>  var a = 10;<br>  let b = 20;<br>  const c = 30;<br>}<br><br>console.log(a); // 10<br>console.log(b); // Uncaught ReferenceError: b is not defined<br>console.log(c); // Uncaught ReferenceError: c is not defined</pre><h3>shadowing</h3><p>When a variable declared in a certain scope (e.g. a local variable) has the same name as a variable in an outer scope (e.g. a global variable) then it’s called shadowing.</p><p>Let’s understand this through example,</p><pre>var a = 100;<br>let b = 200;<br>const c = 300;<br>console.log(&quot;a: &quot;, a); // 100<br><br>{<br>  var a = 10; // a is shadowed in the block<br>  let b = 20;<br>  const c = 30;<br>  console.log(&quot;a: &quot;, a); // 10<br>  console.log(&quot;b: &quot;, b); // 20<br>}<br><br>console.log(&quot;a: &quot;, a); // 10 -&gt; var a is shadowed inside the block and<br>//the value is updated because, they both are pointing to same memory location<br><br>console.log(&quot;b: &quot;, b); // 200 -&gt; let b is shadowed in the block but,<br>// the value does not changed, because they both are pointing to<br>// different memory location<br><br>console.log(&quot;c: &quot;, c); // 300</pre><p>Let’s see how it looks in the browser</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vws4RwTs0DrZFqAZcEo3pw.png" /></figure><p>Other use cases</p><pre>// Use case 1<br>let a = 10;<br>{<br>  var a = 20; //Uncaught SyntaxError: Identifier &#39;a&#39; has already been declared<br>}<br><br>// Use case 2<br>var b = 10;<br>{<br>  let b = 20;<br>  console.log(b); // 20<br>}<br>console.log(b);  // 10<br><br>// Use case 3<br>let a = 10;<br>{<br>  const a = 20;<br>  console.log(a);  // 20<br>}<br>console.log(a);  // 10<br><br>// Below code is a valid shodowing<br>const c = 10;<br>{<br>  const c = 20;<br>  {<br>    const c = 30;<br>    console.log(c); // 30<br>  }<br>  console.log(c); // 20<br>}<br>console.log(c); // 10</pre><h3>Closures</h3><p>A <strong>closure</strong> is the combination of a <em>function bundled together</em> (enclosed) with references to its <em>surrounding state</em> (the lexical environment). In other words, a closure gives you access to an outer function’s scope from an inner function. In JavaScript, closures are created every time a function is created, at function creation time.</p><p><strong>Example 1:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-LMI3AWfCpxm-CHkrT4shA.png" /></figure><p><strong>Example 2:</strong></p><pre>function x() {<br>  var a = 7;<br>  function y() {<br>    console.log(a); // 7, &quot;a&quot; is a closure, will learn closure later<br>  }<br>  return y;<br>}<br>var z = x();<br><br>z();</pre><p>In this program, we are returning a function y from x. After returning the function y, the execution context (EC) of x will be popped off the call stack. But we can still access the variable a from the function y. This is called <strong>closure</strong>. Function y remembers where it came from through closure.</p><p>Let’s see it on the browser</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HyA0tuRkV9kxftsZZRi29A.png" /></figure><p><strong>Example 3:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YZ2KsehuZTeY2Nukiz7OIg.png" /></figure><p>In e.g 3, function y is inside x() and the function x is inside z(). And we are trying to access var b from z() and var a from x() , and we can access it through closures.</p><p>Even if you return the function y from line 5 and execute outside, it will still retain the value of a and b.</p><p>Usages of closures:</p><ul><li>Module design pattern</li><li><a href="#3250">Currying</a></li><li>Functions like one</li><li>Memoize</li><li>Maintaining state in async world</li><li>setTimeouts</li><li>Iterators</li><li>and many more…</li></ul><h4>Disadvantage of closures</h4><ol><li><strong>Memory Consumption:</strong> Closures can lead to increased memory consumption. When a closure is created, it retains references to its outer variables, preventing them from being garbage collected. If closures are created within a loop or in a long-running process, they can accumulate and consume significant memory.</li><li><strong>Performance Impact:</strong> Closures can have a performance impact, particularly when they are used in nested or deeply nested functions. Accessing variables from outer scopes requires traversing the scope chain, which can be slower compared to accessing variables within the same function scope.</li><li><strong>Potential Memory Leaks:</strong> Closures can inadvertently lead to memory leaks if not used carefully. If a closure retains references to objects or resources that are no longer needed, those objects will not be garbage collected, resulting in memory leaks.</li><li><strong>Readability and Maintenance:</strong> Overuse or misuse of closures can make code more difficult to read, understand, and maintain.</li></ol><h4>Closures with setTimeout</h4><p>Let’s try to print incremented counter after every 1 second,</p><pre>for (var i = 1; i &lt;= 5; i++) {<br>  setTimeout(() =&gt; {<br>    console.log(i);<br>  }, i * 1000);<br>}<br>// output after every one sec: 6, 6, 6, 6, 6, 6</pre><p>To fix the above problem we can use let instead of var in the above program, but we can also do it with var using closure .</p><pre>for(var i=1; i &lt; 6; i++) {<br>  function counter(x) {<br>      setTimeout(() =&gt; {<br>          console.log(x);<br>      }, x * 1000)<br>  }<br>  counter(i);<br>}<br>// 1, 2, 3, 4, 5</pre><h4>Example of how closure is different than lexical env</h4><p><strong>Example of lexical env</strong></p><pre>function z() {<br>  var b = 900;<br>  function x() {<br>    var a = 7;<br>    function y() {<br>      console.log(a, b);<br>    }<br>    y();<br>  }<br>  x();<br>}<br><br>z();</pre><p><strong>Example of closure</strong></p><pre>function z() {<br>  var b = 900;<br>  function x() {<br>    var a = 7;<br>    function y() {<br>      console.log(a, b);<br>    }<br>    return y;<br>  }<br>  x();<br>}<br><br>var inner = z();<br>inner();</pre><p>After returning the function y the function z and x will be removed from the call stack but we can still access through closure. (<a href="#cce4">can refer to 2nd example for more details</a>).</p><h4>Closure as data hiding</h4><p><strong>Example 1:</strong></p><pre>function counter() {<br>  var count = 0;<br>  function increment() {<br>    return count++;<br>  }<br>  increment();<br>}<br><br>console.log(count); // can&#39;t access count here<br>counter();<br>console.log(count); // can&#39;t access count here either</pre><p>We can’t access the var count outside of the function because before calling the function the EC has not been created so the var x has not hoisted and initialized. And we can’t call it after the function call because once the function execution is finished the EC of the function will be deleted and no longer available.</p><p>Example 2:</p><pre>function counter() {<br>  var count = 0;<br>  return function increment() {<br>    return count +=1;<br>  }<br>}<br><br>var counter1 = counter();<br>console.log(counter1()); // 1<br>console.log(counter1()); // 2<br><br>var counter2 = counter(); // new instance<br>console.log(counter2()); // 1<br><br>console.log(counter1()); // 3<br>console.log(counter1()); // 4<br><br>console.log(counter2()); // 2</pre><h4>Closure with constructor functions</h4><pre>function Counter() { // since it&#39;s constructure func name start with caps<br>  var count = 0;<br>  this.incrementCounter = function() {<br>    return count +=1;<br>  }<br>  this.decrementCounter = function() {<br>    return count -=1;<br>  }<br>}<br><br>var counter1 = new Counter(); //<br><br>console.log(counter1.incrementCounter()); // 1<br>console.log(counter1.incrementCounter()); // 2<br>console.log(counter1.decrementCounter()); // 1</pre><p>We can do the same thing in class</p><ul><li>The first way</li></ul><pre>class Counter {<br>  constructor() {<br>    var count = 0;<br>    this.incrementCounter = function () {<br>      return count += 1;<br>    };<br>    this.decrementCounter = function () {<br>      return count -= 1;<br>    };<br>  }<br>}<br><br>var counter1 = new Counter();<br><br>console.log(counter1.incrementCounter()); // 1<br>console.log(counter1.incrementCounter()); // 2<br>console.log(counter1.decrementCounter()); // 1</pre><ul><li>Second way</li></ul><pre>class Counter {<br>    constructor() {<br>        this.count = 0;<br>    }<br>    incrementCounter() {<br>        return this.count += 1;<br>    };<br>    decrementCounter() {<br>        return this.count -= 1;<br>    };<br>}<br><br>var counter1 = new Counter();<br><br>console.log(counter1.incrementCounter()); // 1<br>console.log(counter1.incrementCounter()); // 2<br>console.log(counter1.decrementCounter()); // 1</pre><h3>Currying</h3><p><strong>Currying</strong> in JavaScript is a process in functional programming in which you can transform a function with multiple arguments into a sequence of nesting functions.</p><p>Currying can be achieved in two ways</p><ul><li><strong>Currying through bind()</strong></li></ul><pre>function multiply(x, y) {<br>    console.log(x * y);<br>}<br><br>// multiply(2, 3);<br><br>const multiplyByTwo = multiply.bind(this, 2);<br>multiplyByTwo(3);<br><br>const multiplyByThree = multiply.bind(this, 3);<br>multiplyByThree(10);</pre><ul><li><strong>Currying through closure</strong></li></ul><pre>function mul(x) {<br>    return function(y) {<br>        console.log(x * y);<br>    }<br>}<br><br>const mulByTwo = mul(2);<br>mulByTwo(3);<br><br>const mulByThree = mul(3);<br>mulByThree(10);</pre><h3>Event Loops</h3><p>The event loop continuously checks for pending tasks in the callback queue, if there is a callback in the callback queue it moves to thecall stack if the call stack is empty.</p><p>And in case there are no pending events or callbacks, the event loop will wait for events to occur.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*4qyhpqzvK0An-ybsc6E_YQ.png" /></figure><p>Let’s understand this through an example,</p><pre>console.log(&quot;start&quot;);<br><br>setTimeout(() =&gt; {<br>  console.log(&quot;Callback called!&quot;);<br>}, 5000);<br><br>console.log(&quot;End&quot;);</pre><ol><li>The code execution starts, and “start” is logged to the console.</li><li>The setTimeout function is called. It registers the callback function inside web API env and sets a timer for 5000 milliseconds.</li><li>The event loop continues to the next line without waiting for the timer to finish.</li><li>“End” is logged to the console.</li><li>The event loop keeps running and checks if there are any pending tasks.</li><li>After 5000 milliseconds, the timer for setTimeout completes, and the callback function is added to the task queue.</li><li>The event loop checks the task queue and finds the callback function.</li><li>The callback function is then executed, and “Callback called!” is logged to the console.</li></ol><p>The Event loop has two types of task queue</p><ol><li>Microtask Queue<br>* process.nextTick()<br>* Promise callback<br>* async callback</li><li>Callback Queue (Macrotask Queue)<br>* setTimeout()<br>* setInterval()<br>* setImmediate()</li></ol><p>Microtask Queue has higher priority than Callback Queue. The Event loop executes the tasks in the following order:</p><ul><li>Executes all the tasks in the Microtask Queue.</li><li>Executes the oldest task in the Callback Queue.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/0*W6Wp4NOKluj1cA_T.gif" /></figure><p><strong>Starvation in the Event loop</strong></p><p>If the Callback Queue has a large number of tasks, then the tasks in the Microtask Queue will be executed only after the execution of all the tasks in the Callback Queue. This will cause starvation in the Event loop.</p><h4>Web APIs</h4><p>Web APIs are provided by the web browser environment. These APIs are built into the browser and enable JavaScript to interact with various aspects of the web platform, such as manipulating the DOM (Document Object Model), making HTTP requests, handling timers and events, accessing browser storage, and more.</p><p>Web APIs are not part of the core JavaScript language, but they are exposed to JavaScript through the browser environment. They provide additional functionalities and allow JavaScript to interact with the browser and its surrounding environment.</p><p>Commonly used web APIs</p><ul><li>setTimeout (timer API)</li><li>console.log (console API)</li><li>DOM API</li><li>Fetch API</li><li>Geolocation API</li><li>localstorage, sessionStorage (Web Storage API)</li><li>Web Audio API</li><li>Canvas API</li></ul><p>Check out <a href="https://developer.mozilla.org/en-US/docs/Web/API">here</a> to see all web APIs.</p><h3>Callbacks</h3><p>A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action.</p><pre>function greeting(name) {<br>  alert(`Hello, ${name}`);<br>}<br><br>function processUserInput(callback) {<br>  const name = prompt(&quot;Please enter your name.&quot;);<br>  callback(name);<br>}<br><br>processUserInput(greeting);</pre><p>Examples of predefined methods which has the callback</p><pre>setTimeout(callBackFunc, 100)<br>btn.addEventListener(&#39;click&#39;, callBackFunc);<br>array1.map(function callbackFunc(el) {} )<br>array1.filter(function callbackFunc(el) {} )<br>array1.forEach(function callbackFunc(el) {} )</pre><h4>Advantage of Callback</h4><ul><li>As we already know, Javascript is a synchronous &amp; single-threaded language, but through the callbacks, we can perform asynchronous operations.</li></ul><h4>Limitation of callback</h4><ul><li><strong>Callback hell</strong></li></ul><p>Callback hell, also known as the pyramid of doom, is a situation that arises in asynchronous programming when there are multiple nested callbacks. It occurs when callbacks are chained together, resulting in deeply nested and hard-to-read code structures. This can make the code difficult to understand, maintain, and debug.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/775/1*vrZU5nR7IfVpYxGZI0m90g.png" /></figure><ul><li><strong>Inversion of control</strong></li></ul><p>Whenever we have the callback function and we pass it to some other function we are giving control of our function to another function and we don’t know what’s happening behind the scenes now. It may not call out the callback function or may call multiple times.</p><h3>Promise</h3><p>A Promise is an object representing the eventual completion or failure of an asynchronous operation.</p><p>Promises are used to handle asynchronous operations in JavaScript. They are easy to manage when dealing with multiple asynchronous operations where callbacks can create callback hell leading to unmanageable code.</p><p>Components of Promise</p><ul><li><strong>State</strong></li><li><strong>Result</strong> (the result of promise is immutable)</li></ul><p>A promise has three states:</p><ul><li><strong>pending</strong>: the promise is still in the works</li><li><strong>fulfilled</strong>: the promise resolves successfully and returns a value</li><li><strong>rejected</strong>: the promise fails with an error</li></ul><p>How promise look like,</p><pre>createOrder(cart)<br>  .then((orderId) =&gt; {<br>    return fetchPaymentDetails(orderId);<br>  })<br>  .then((paymentDetails) =&gt; {<br>    return processPayment(paymentDetails);<br>  })<br>  .then((result) =&gt; {<br>    return showSuccessMessage(result);<br>  })</pre><p>Example 1:</p><pre>// producer<br>const examResult = new Promise((resolve, reject) =&gt; {<br>  const res = Math.floor((Math.random() * 100) + 1);<br>  if(res &gt;= 50 ) {<br>    resolve(`Pass: ${res}`)<br>  } else {<br>    const err = new Error(`Failed: ${res}`);<br>    reject(err); // rejection should be an error<br>  }<br>})<br><br>// consumer<br>examResult<br>  .then(res =&gt; console.log(res))<br>  .catch(err =&gt; console.error(err.message))<br>  .finally(() =&gt; console.log(&#39;Done!&#39;))</pre><p>Example of promise</p><pre>const cart = [&#39;Shoes&#39;, &#39;Shirt&#39;, &#39;Pant&#39;]<br><br>createOrder(cart)<br>  .then((orderId) =&gt; {<br>    return proceedToPayment(orderId); // keep returning promise to chain<br>  })<br>  .then((paymentId) =&gt; {<br>    console.log(&#39;Payment Successfull with paymentId:&#39;, paymentId);<br>  })<br>  .catch((err) =&gt; { // catch error from any of the above promise<br>    console.log(err.message);<br>  })<br>  .finally(() =&gt; { // finally block will always execute<br>    console.log(&#39;End of order!&#39;);<br>  })<br><br><br>function createOrder(cart) {<br>  return new Promise((resolve, reject) =&gt; {<br>    // Validate cart<br>    if(cart.length &gt;= 3) { // modify this to test error<br>      const orderId = &#39;12345&#39;;<br>      resolve(orderId);<br>    } else {<br>      const err = new Error(&#39;Invalid cart, Order not created!&#39;);<br>      reject(err);<br>    }<br>  })<br>}<br><br>function proceedToPayment(orderId) {<br>  return new Promise((resolve, reject) =&gt; {<br>    // Validate orderId<br>    if(orderId === &#39;12345&#39;) { // modify this to test error<br>      const paymentId = &#39;67890&#39;;<br>      resolve(paymentId);<br>    } else {<br>      const err = new Error(&#39;Invalid orderId, Payment not processed!&#39;);<br>      reject(err);<br>    }<br>  })<br>}</pre><p>You can learn more about Promise APIs in my separate article <a href="https://kishanptl-kp.medium.com/javascript-promise-promise-apis-72a2702147ea#dec2">here</a>.</p><h3>Debouncing &amp; Throttling</h3><p>Debouncing and throttling are two ways to limit the rate of function calls. They are used to improve performance and user experience.</p><p>Let’s understand them one by one.</p><h4>Debouncing</h4><p>Debouncing is a programming practice used to ensure that time-consuming tasks do not fire so often, that it stalls the performance of the web page. In other words, it limits the rate at which a function gets invoked.</p><p>Debouncing checks if the same function is being called again within a certain time frame, it cancels the previous call and starts over again.</p><p>Example:</p><pre>const getData = () =&gt; {<br>  // calls an API and gets Data<br>  searchInput = document.getElementById(&#39;search&#39;);<br>  console.log(&quot;Fetching Data ..&quot;, searchInput.value);<br>}<br><br>const debounce = function (getDataCallback, delay) {<br>  let timer;<br>  return function () {<br>    clearTimeout(timer);<br>    timer = setTimeout(() =&gt; {<br>      getDataCallback();<br>    }, delay);<br>  }<br>}<br><br>const debounceInput = debounce(getData, 300);<br><br>/* &lt;input type=&quot;text&quot; id=&quot;search&quot; onkeyup=&quot;debounceInput()&quot; /&gt; */</pre><p>In the above example, we are calling <strong>debounceInput()</strong> on every keyup event but <strong>debounceInput()</strong> will not call <strong>getData()</strong> until 300ms after the last keyup event.</p><p>That means if you are <strong>continuously typing</strong> in the input box, <strong>getData()</strong> will not be called until you stop typing for 300ms.</p><h4>Throttling</h4><p>Throttling is a technique in which, no matter how many times the user fires the event, the <strong>attached function</strong> will be <strong>executed only once in a given time interval</strong>.</p><pre>const getData = () =&gt; {<br>  // calls an API and gets Data<br>  searchInput = document.getElementById(&#39;search&#39;);<br>  console.log(&quot;Fetching Data ..&quot;, searchInput.value);<br>}<br><br>const throttle = function (getDataCallback, delay) {<br>  let flag = true;<br>  return function () {<br>    if (!flag) return;<br>    flag = false;<br>    setTimeout(() =&gt; {<br>      flag = true;<br>      getDataCallback();<br>    }, delay);<br>  }<br>}<br><br>const throttleInput = throttle(getData, 300);<br><br>/* &lt;input type=&quot;text&quot; id=&quot;search&quot; onkeyup=&quot;throttleInput()&quot; /&gt; */</pre><h4>async and defer</h4><p>In HTML, the &lt;script&gt; tag is used to include JavaScript code within an HTML document. Both the async and defer attributes can be used with the &lt;script&gt; tag to control how the script is loaded and executed.</p><ol><li>Async attribute: When you add the async attribute to the &lt;script&gt; tag, it indicates that the script should be executed asynchronously. This means that the script will not block the rendering of the HTML document while it is being loaded and executed. The browser will continue parsing the HTML and rendering the page, and when the script is fully loaded, it will be executed at the first available opportunity.</li></ol><p>&lt;script src=&quot;script.js&quot; async&gt;&lt;/script&gt;</p><ol><li>Note that the order of execution may not be guaranteed if you have multiple scripts with the async attribute. They may be executed as soon as they are loaded, without waiting for the previous scripts to finish loading or executing.</li><li>Defer attribute: When you add the defer attribute to the &lt;script&gt; tag, it indicates that the script should be deferred. This means that the script will be loaded in the background while the HTML document is being parsed, but its execution will be deferred until the HTML parsing is complete. The scripts with the defer attribute will be executed in the order they appear in the HTML document.</li></ol><p>&lt;script src=”script.js” defer&gt;&lt;/script&gt;</p><ol><li>Unlike the async attribute, the defer attribute ensures that the scripts are executed in the order they are specified in the HTML document, without blocking the rendering of the page.</li></ol><p>Both async and defer are used to improve the loading and execution of JavaScript code, especially when you have scripts that are not critical for the initial rendering of the page. They can help improve page loading speed and overall performance. The choice between async and defer depends on the specific requirements of your script and how it interacts with the rest of the page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cO-f9ycxBXHjUTdgSwN77g.png" /></figure><h3>Prototype</h3><p>All JavaScript objects inherit properties and methods from a prototype.</p><pre>Array.prototype.printData = function (data) {<br>  console.log(data);<br>}<br><br>const arr = [1, 2, 3, 4, 5];<br>const arr2 = [10, 20, 30];<br><br><br>arr.printData(&#39;Hello&#39;);<br><br>arr.__proto__.showLength = function () {<br>  console.log(`Length of array is ${this.length}.`);<br>}<br><br>arr.showLength();  // arr is able to access showLength method<br><br>arr2.showLength();  // arr2 is also able to access showLength method</pre><h4>Add a prototype of one object to another object</h4><pre>const obj = {};<br>const parent = { foo: &#39;bar&#39; };<br><br>console.log(obj.foo);<br>// Expected output: undefined<br><br>Object.setPrototypeOf(obj, parent);<br><br>console.log(obj.foo);<br>// Expected output: &quot;bar&quot;</pre><h4>Prototype Chain</h4><p>The prototype chain is used to build a chain of objects to find a property or method.</p><pre>const arr = [1, 2, 3, 4, 5];<br>arr.__proto__.__proto__.__proto__;  // this is prototype chain</pre><p>More details</p><pre>// Array proptotype<br>const arr = [1, 2, 3, 4, 5];<br><br>console.log(arr.__proto__ === Array.prototype);  // true<br>console.log(arr.__proto__.__proto__ === Object.prototype);  // true<br>console.log(arr.__proto__.__proto__.__proto__); // null<br><br><br>// Object prototype<br>const obj = {<br>  name: &#39;John&#39;,<br>  age: 32,<br>}<br><br>console.log(obj.__proto__ === Object.prototype);  // true<br>console.log(obj.__proto__.__proto__); // null<br><br><br>// Function Prototype<br>function fun() {};<br><br>// Both are same<br>console.log(fun.__proto__ === Function.prototype);<br><br>// Both are same<br>console.log(fun.__proto__.__proto__);<br>console.log(Object.prototype);<br><br>console.log(fun.__proto__.__proto__.__proto__); // null</pre><h3>Functions in Javascript</h3><h4>Higher order function</h4><p>A function that takes another function as an argument or a function that returns a function is called Higher order function.</p><pre>// Example 1<br>function a() {<br>  console.log(&#39;a&#39;);<br>}<br><br>function b(a) { // Here b is an higher order function<br>  a();<br>}<br>b();<br><br>// Example 2<br><br>function x() { // Here x is an higher order function<br>  return function y() {<br>    console.log(&#39;y&#39;);<br>  }<br>}</pre><p><strong>Real use case of higher order function</strong></p><pre>const radius = [3, 1, 2, 4];<br><br><br>const area = function (radius) {<br>  return Math.PI * radius * radius;<br>}<br><br>const circumference = function (radius) {<br>  return 2 * Math.PI * radius;<br>}<br><br>const diameter = function (radius) {<br>  return 2 * radius;<br>}<br><br>// Higher order function &amp;&amp; Polyfills for map<br>const calculate = function (radius, logic) { // Higher order function<br>  const output = [];<br>  for (let i = 0; i &lt; radius.length; i++) {<br>    output.push(logic(radius[i]));<br>  }<br>  return output;<br>}<br><br>console.log(calculate(radius, area));<br>console.log(calculate(radius, circumference));<br>console.log(calculate(radius, diameter));</pre><p>Here we just created a logic for the map, above calculate method will do the same job as the map. So we can say calculate is the polyfills for map</p><pre>console.log(radius.map(area)); //</pre><h4>Function Statement or function declaration</h4><pre>function a() {<br>  console.log(&quot;Hello!&quot;);<br>}</pre><h4>Function Expression</h4><pre>var x = function a() {<br>  console.log(&quot;Hello!&quot;);<br>}</pre><h4>Function Statement Vs Function Expression</h4><p>We can call the function statement before declaring because of hoisting (the whole function body is stored in memory).</p><p>It is not possible in function expression since variable x is hoisted as undefined.</p><pre>a();<br>x();<br><br><br>function a() {<br>  console.log(&quot;Hello!&quot;);<br>}<br><br>const x = function b() {<br>  console.log(&quot;Hello!&quot;);<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s33aWmm1U9SRBbR5RAreWg.png" /></figure><h4>Anonymous functions</h4><p>A function without a name is called an Anonymous function.</p><p>The anonymous function must be <strong>assigned to a variable</strong> to be called later otherwise it will raise an error.</p><pre>var x = function () {<br>  // ... <br>}<br><br>// or in arrow func<br><br>var y = () =&gt; {<br>  // ...<br>}</pre><h4>First-class function or First-class citizens</h4><p>The <strong>ability</strong> of a function to be <strong>used as a value</strong> and return a function is called a first-class function.</p><pre>function a() {<br>  console.log(&#39;a called.&#39;);<br>}<br><br>const b = function (funcA) {<br>  funcA();<br>  return () =&gt; {}<br>}<br><br>b(a);</pre><h4>Pure Function</h4><p>A pure function is a function that returns the same result if the same arguments(input) are passed to the function.</p><ul><li>Return value should only be dependent on the input</li><li>It should not modify any non-local state.</li><li>The function should <strong>not have any side effects</strong>, such as reassigning non-local variables, mutating the state of any part of code that is not inside the function, or calling any non-pure functions inside it.</li></ul><p>Example:</p><pre>// Below function will give same output for same input each time<br>function operationAdd(a, b){<br>    return a+b;<br>}<br><br><br>// It is a pure function because it is not modifying the original array.<br>const ary2 = [10, 20, 30];<br>function addElement(ary, element) {<br>  return [...ary, element];<br>}</pre><p>Let’s also see few example of <strong>non pure function</strong></p><pre>// It is not a pure function because it is modifying the original array.<br>const ary1 = [1, 2, 3, 4, 5];<br>function addElement(ary, element) {<br>  ary.push(element);<br>}<br><br>/* It is not a pure function because it is returning <br> different output for same input. */<br>function add(a, b) {<br>  return a + b + Math.random();<br>}</pre><h4>IIFE — Immediately Invoked Function Expression</h4><p><strong>IIFE</strong> is a function that runs the moment it is invoked or called in the JavaScript event loop. Having a function that behaves that way can be useful in certain situations. IIFEs prevent pollution of the global JS scope.</p><pre>// Example 1<br>(function () {<br>  console.log(&#39;Hello World!&#39;);<br>})();<br><br>// Example 2<br>(favNumber = function(num = 3) {<br>  console.log(`My favourite number is ${num}`);<br>})();<br><br><br>favNumber(6);</pre><h4>Constructor Function</h4><pre>var user1 = {name: &#39;Kishan&#39;, age: 30, getName: function() { return this.name }}<br>var user2 = {name: &#39;Ashish&#39;, age: 29, getName: function() { return this.name }}<br>// to create n number of use we need to create n number of independent object<br>// to avoid this we can use function constructor<br>var Person = function(firstName, lastName, age) {<br>    this.firstName = firstName;<br>    this.lastName = lastName;<br>    this.age = age;<br>    this.getName = function() {<br>        return `${this.firstName} ${this.lastName}`;<br>    },<br>    this.getAge = function() {<br>        return this.age;<br>    }<br>}<br>var p1 = new Person(&#39;Kishan&#39;, &#39;Patel&#39;, 30);<br>var p2 = new Person(&#39;Ram&#39;, &#39;Patel&#39;, 30);<br>console.log(p1);<br>console.log(p1);<br><br>console.log(p1.getName);<br>console.log(p2.getName);<br><br>console.log(p1.getAge);<br>console.log(p2.getAge);</pre><p>In the above example you might have noticed that console log of p1 and p2 both are havinggetName and getAge which are repeating. To avoid this we can use prototype.</p><pre><br>var Person = function(firstName, lastName, age) {<br>    this.firstName = firstName;<br>    this.lastName = lastName;<br>    this.age = age;<br>}<br><br>Person.prototype.getName = function() {<br>    return `${this.firstName} ${this.lastName}`;<br>};<br>    <br>Person.prototype.getAge = function() {<br>    return this.age;<br>}<br><br>var p1 = new Person(&#39;Kishan&#39;, &#39;Patel&#39;, 30);<br>var p2 = new Person(&#39;Ram&#39;, &#39;Patel&#39;, 30);<br><br>// if you want to add a method for a perticular object<br>p1.__proto__.myAge = function() {<br>    return this.age;<br>}<br><br>console.log(p1);<br>console.log(p1.getName()); // Kishan Patel<br>console.log(p1.getAge()); // 30<br>console.log(p1.myAge());  // 30</pre><h4>How to acive inheritance in constructor function</h4><pre>function Animal(name, age) {<br>    this.name = name;<br>    this.age = age;<br>    this.logDetails = function() {<br>        console.log(`${this.name} is of ${this.age} years`);<br>    }<br>}<br><br>Animal.prototype.eats = function() {<br>    console.log(`${this.name} is eating now.`);<br>}<br><br>function Dog(name, age, breed) {<br>    this.breed = breed;<br>    // inherit all attributes and methods<br>    Animal.call(this, name, age);<br>    this.logBreed = function() {<br>        console.log(this.name + &#39; is a &#39; + this.breed);<br>    }<br>}<br><br>// inherit the prototype as well.<br>Dog.prototype = Object.create(Animal.prototype);<br><br>const d1 = new Dog(&#39;Simba&#39;, 4, &#39;bulldog&#39;);<br>d1.logBreed();<br>d1.logDetails();<br>d1.eats();</pre><h4>Class</h4><pre>class Person {<br>  constructor(firstName, lastName, dob) {<br>    this.firstName = firstName;<br>    this.lastName = lastName;<br>    this.dob = dob;<br>  }<br><br>  // Public Method<br>  getFullName() {<br>    return `${this.firstName} ${this.lastName}`;<br>  }<br><br>  // Public Method<br>  getAge() {<br>    return this.#calculateAge();<br>  }<br><br>  // Private Method<br>  #calculateAge() {<br>    var dob = new Date(this.dob);<br>    var month_diff = Date.now() - dob.getTime();<br><br>    //convert the calculated difference in date format<br>    var age_dt = new Date(month_diff);<br><br>    //extract year from date<br>    var year = age_dt.getUTCFullYear();<br><br>    //now calculate the age of the user<br>    var age = Math.abs(year - 1970);<br>    return age;<br>  }<br>}<br><br>const p1 = new Person(&#39;Kishan&#39;, &#39;Patel&#39;, &#39;1993/04/26&#39;);<br>console.log(`${p1.getFullName()}&#39;s age is: ${p1.getAge()} years.`);</pre><h4>Class Inheritance</h4><pre>class Animal {<br>    constructor(name, age) {<br>        this.name = name;<br>        this.age = age;<br>    }<br>    logDetails = function() {<br>        console.log(`${this.name} is of ${this.age} years`);<br>    }<br>}<br><br>Animal.prototype.eats = function() {<br>    console.log(`${this.name} is eating now.`);<br>}<br><br>class Dog extends Animal {<br>    constructor(name, age, breed) {<br>        super(name, age);<br>      this.breed = breed;<br>    }<br>    logBreed = function() {<br>        console.log(this.name + &#39; is a &#39; + this.breed);<br>    }<br>}<br><br>Dog.prototype = Object.create(Animal.prototype);<br><br>const d1 = new Dog(&#39;Simba&#39;, 4, &#39;bulldog&#39;);<br>d1.logBreed();<br>d1.logDetails();<br>d1.eats();</pre><h4>Polyfills</h4><p>In JavaScript, a polyfill is a piece of code that provides functionality that is not natively supported by a web browser. It allows you to use new JavaScript features or APIs in older browsers that do not support them.</p><p>Polyfills are typically used to bridge the gap between older browsers and the latest web standards. They emulate the behavior of the new features or APIs by implementing them using the existing JavaScript capabilities available in the browser.</p><p>Let’s consider an example where we want to use the Array.prototype.includes() method, which was introduced in ECMAScript 2016 (ES7), but we need to support older browsers that do not have native support for this method. We can create a polyfill to emulate the functionality of includes() using existing JavaScript methods.</p><p>Here’s a simple polyfill for Array.prototype.includes():</p><pre>if (!Array.prototype.includes) {<br>  Array.prototype.includes = function(element) {<br>    for (let i = 0; i &lt; this.length; i++) {<br>      if (this[i] === element) {<br>        return true;<br>      }<br>    }<br>    return false;<br>  };<br>}</pre><h3>Event Bubling &amp; Event Capturing(Trickling)</h3><ul><li>Event Bubling</li></ul><p>A bubbling event goes from the target element straight up. Normally it goes upwards till &lt;html&gt;, and then to document object, and some events even reach window, calling all handlers on the path.</p><ul><li>Event Capturing(Trickling)</li></ul><p>Event capturing is the event starts from the top element to the target element.</p><pre>#grand-parent<br>  #parent<br>    #child</pre><p>Example 1: Child Clicked</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TU2SB3neBIl7W9cHh5HAFg.png" /></figure><p>Example 2: Child Clicked</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*czoe0lIb6W0zepfp0_Dm1A.png" /></figure><p>Example 3: Child Clicked</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i7YmUpPKtPVMxe0x7QdphQ.png" /></figure><p>Example 4: Parent Clicked</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YGMqDKgeZqBJQRYAZhXNww.png" /></figure><blockquote><a href="#25e9">Go to top</a></blockquote><p>Thanks for reading, check out my article on <a href="https://kishanptl-kp.medium.com/javascript-faqs-eb2e828a0593"><strong>Javascript FAQs</strong></a><strong> </strong>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=70ae7735670" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[S3 Doc upload using aws-sdk npm package]]></title>
            <link>https://kishanptl-kp.medium.com/s3-doc-upload-using-aws-sdk-npm-package-25bf459173f8?source=rss-cd54f0568629------2</link>
            <guid isPermaLink="false">https://medium.com/p/25bf459173f8</guid>
            <dc:creator><![CDATA[Kishan Patel]]></dc:creator>
            <pubDate>Tue, 21 Mar 2023 10:14:36 GMT</pubDate>
            <atom:updated>2023-08-31T06:53:12.410Z</atom:updated>
            <content:encoded><![CDATA[<h3>Overview</h3><ul><li>Create an AWS s3 account and sign in as <strong>IAM User</strong> at <a href="https://aws.amazon.com/s3/">https://aws.amazon.com/s3/</a></li><li>Create a bucket and add a policy to it</li><li>Edit CORS policy to the bucket so that people can get it publicly</li><li>In order to upload files from SDK create a user with programmatic access and add a policy to the user to provide the required access.</li><li>After creating the user we will get access_key and secret_access_key, through these keys we can communicate to s3 through SDK from the JS app.</li><li>Install aws-sdk npm package</li><li>Create an s3 object with these keys and bucket</li><li>Get objects(or files) from s3</li></ul><h3>Highlights</h3><ul><li>AWS</li><li>S3</li><li>IAM user</li><li>Bucket</li><li>Object</li><li>Policy</li><li>aws-sdk</li><li>list_objects</li><li>put_objects</li><li>delete_object</li></ul><p>After signing in with the IAM user let’s create an bucket where we want to upload our files</p><h4>Create Bucket</h4><ul><li>Search for S3 on the search bar and click on Bucket under S3</li><li>Click on Create bucket</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C3BmmSy1H1RsPjst1PvwnA.png" /></figure><ul><li>Provide a name for your bucket</li><li>Select</li><li>Uncheck <strong>[ ] Block all public access</strong>, so that we can add images through web-client</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YyGGuw-vbtyvYcuo4Zi6QQ.png" /></figure><h3>Edit Bucket Policy</h3><p>Now we need to edit bucket policy to allow users to get images/files directly from the URL.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SFNQKc21XH4NakXAHo-s3g.png" /></figure><p>Example:</p><pre>{<br> &quot;Version&quot;: &quot;2012-10-17&quot;,<br> &quot;Statement&quot;: [<br>  {<br>   &quot;Sid&quot;: &quot;PublicReadGetObject&quot;,<br>   &quot;Effect&quot;: &quot;Allow&quot;,<br>   &quot;Principal&quot;: &quot;*&quot;,<br>   &quot;Action&quot;: &quot;s3:GetObject&quot;,<br>   &quot;Resource&quot;: &quot;arn:aws:s3:::your-bucket-name/*&quot;<br>  }<br> ]<br>}</pre><p>You can also use <a href="https://awspolicygen.s3.amazonaws.com/policygen.html">Policy Generetor</a> to generate policy and after that you can paste it here.</p><p>After adding bucket policy you can get image/file from URL but in order to use it in your web application like show image on your web app we need to <strong>allow CORS.</strong></p><h4>Allow Cors</h4><p>On your bucket go to <strong>Permissions &gt; Cross-origin resource sharing (CORS) &gt; Edit</strong> and add cors configuration</p><p>Example:</p><pre>[<br>    {<br>        &quot;AllowedHeaders&quot;: [<br>            &quot;*&quot;<br>        ],<br>        &quot;AllowedMethods&quot;: [<br>            &quot;HEAD&quot;,<br>            &quot;GET&quot;,<br>            &quot;PUT&quot;,<br>            &quot;POST&quot;,<br>            &quot;DELETE&quot;<br>        ],<br>        &quot;AllowedOrigins&quot;: [<br>            &quot;*&quot;<br>        ],<br>        &quot;ExposeHeaders&quot;: []<br>    }<br>]</pre><p>In order to allow put object (upload file) we need to create an IAM user with requuired access.</p><h4>Create IAM user</h4><p>Here we need to create two things</p><ol><li><strong>Policy:</strong> This is required to specify what type of things a user can do</li><li><strong>User:</strong> Need to create user with above policy and we will get <strong>access_key</strong> and <strong>secret_access_key</strong> which we will use later to communicate with S3 through the aws-sdk.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*URaHKJbHgWPnB2wd9k1ONw.png" /></figure><ul><li>Select service as <strong>s3</strong></li></ul><p>Then in the action select</p><ul><li>PutObject and Delete under Write</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D35B3JlE9gRd9WMPvLdXxg.png" /></figure><ul><li>To allow these actions for a specific bucket add ARN under Resources</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HbVgcvJF4htcwmIDr20BCg.png" /></figure><p><a href="https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/clients/client-s3/index.html">https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/clients/client-s3/index.html</a></p><p>Need to create a policy that defines rules for what can be accessed by a user. Here I am going to choose 3 Actions</p><ul><li>GetObject — To get all data from the bucket</li><li>DeleteObject — To delete a file</li><li>PutObject — To upload a file from the JS app</li></ul><p>&gt; Specify the bucket that we are going to take these actions</p><p>&gt; Our bucket name =&gt; assets.cdn-mydev.com</p><p>&gt; the ARN will be</p><p>arn:aws:s3:::assets.cdn-mydev.com/*</p><p>&gt; Policy Name: mydev-s3-bucket-access</p><p>Need to create a user with the above policy</p><p>&gt; that will allow the JS app to access the AWS account and access the S3 bucket</p><p>&gt; User name: mydev-s3</p><p>&gt; Since it not going to use by a real user select checkbox</p><p>[✓] Access Key — Programmatic Access</p><p>&gt; Set Permissions &gt; Add existing policies directly &gt; Attach the policy(mydev-s3-bucket-access)</p><p>&gt; Copy the access key and secret access key</p><p>By default buckets are private</p><h3><a href="https://stackoverflow.com/questions/22492735/aws-s3-javascript-sdk-networkingerror-network-failure">AWS S3 JavaScript SDK — NetworkingError: Network Failure</a></h3><h4>This error occurs because you don’t set the CORS configuration.</h4><ol><li>Open the Amazon S3 console at <a href="https://console.aws.amazon.com/s3/">https://console.aws.amazon.com/s3/</a>.</li><li>Select the name of the bucket you are using from the bucket list.</li><li>Next, Choose the “Permission” tab.</li><li>Then in an editor titled “Cross-origin resource sharing (CORS)”, you need to make sure the S3 bucket has the following CORS configuration:</li></ol><pre>[<br>    {<br>        &quot;AllowedHeaders&quot;: [<br>            &quot;*&quot;<br>        ],<br>        &quot;AllowedMethods&quot;: [<br>            &quot;HEAD&quot;,<br>            &quot;GET&quot;,<br>            &quot;PUT&quot;,<br>            &quot;POST&quot;,<br>            &quot;DELETE&quot;<br>        ],<br>        &quot;AllowedOrigins&quot;: [<br>            &quot;*&quot;<br>        ],<br>        &quot;ExposeHeaders&quot;: [<br>            &quot;ETag&quot;<br>        ]<br>    }<br>]</pre><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F-ZiirF7ap5U%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D-ZiirF7ap5U&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F-ZiirF7ap5U%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/48d17630be57215596c355d09cb7c31c/href">https://medium.com/media/48d17630be57215596c355d09cb7c31c/href</a></iframe><pre>{<br>    &quot;Version&quot;: &quot;2012-10-17&quot;,<br>    &quot;Statement&quot;: [<br>        {<br>            &quot;Sid&quot;: &quot;PublicReadGetObject&quot;,<br>            &quot;Effect&quot;: &quot;Allow&quot;,<br>            &quot;Principal&quot;: &quot;*&quot;,<br>            &quot;Action&quot;: &quot;s3:GetObject&quot;,<br>            &quot;Resource&quot;: &quot;arn:aws:s3:::cryptokonit.com/*&quot;<br>        }<br>    ]<br>}</pre><p>Put a sample file</p><pre>putObject() {<br>  const params = {<br>    Bucket: bucketName,<br>    Key: &#39;test-2.txt&#39;,<br>    Body: &#39;Hello World!&#39;<br>  }<br>  s3.putObject(params, (error, success) =&gt; {<br>    if (error) {<br>      console.log(&#39;error: &#39;, error);<br>    } else {<br>      console.log(&#39;success: &#39;, success);<br>    }<br>  })<br>},</pre><p><strong>Enable bucket versioning</strong> to upload duplicate images s3 will by default replace the image if versioning is not enabled</p><p><a href="https://docs.aws.amazon.com/AmazonS3/latest/userguide/manage-versioning-examples.html">Enabling versioning on buckets</a></p><h4>Add file inside a folder</h4><p>Technically there is no concept of the folder in aws s3. But each and every file can be prefixed with folders name. <br>Let’s say we want to add a add a file inside two nested folder.<br>e.g. <strong>new-folder &gt; inner-folder &gt; sample-file.txt.</strong></p><p>In this case, we can just prefix folder names and the key will be new-folder/inner-folder/sample-file.txt</p><pre>putObject() {<br>  const params = {<br>    Bucket: bucketName,<br>    Key: &#39;new-folder/inner-folder/sample-file.txt&#39;,<br>    Body: &#39;Hello World!&#39;,<br>    ACL: &#39;public-read&#39; // to access the file publicly<br>  }<br>  s3.putObject(params, (error, success) =&gt; {<br>    if (error) {<br>      console.log(&#39;error: &#39;, error);<br>    } else {<br>      console.log(&#39;success: &#39;, success);<br>    }<br>  })<br>},<br><br></pre><p>Download image instead of opening on a new tab</p><pre>function downloadImage(url) {<br>  fetch(url, {<br>    mode : &#39;no-cors&#39;,<br>  })<br>    .then(response =&gt; response.blob())<br>    .then(blob =&gt; {<br>    let blobUrl = window.URL.createObjectURL(blob);<br>    let a = document.createElement(&#39;a&#39;);<br>    a.download = url.replace(/^.*[\\\/]/, &#39;&#39;);<br>    a.href = blobUrl;<br>    document.body.appendChild(a);<br>    a.click();<br>    a.remove();<br>  })<br>}</pre><p>Working with MaxKeysand StartAfter</p><p>If you list all objects from S3 in the response IsTruncated will be false.</p><p>Let’s say you have 100 objects on S3 and you are providing MaxKeys as 10 (or less than the total objects) than in response, you will get IsTruncated as true means there are some more objects are present in S3.</p><p>To get the next 10 items we can pass another param i.e StartAfter it will expect a key. We can pass the last key from the previous result and can get the next 10 items similarly we will do that to get the next set of objects.</p><pre>const params = {<br>  Bucket: bucketName,<br>  Prefix: this.objectDirectoryPath,<br>  Delimiter: &#39;documents&#39;, // opposite of Prefix<br>  MaxKeys: 10,<br>  ACL: &#39;public-read&#39;,<br>  StartAfter: this.files.at(-1)?.Key || null<br>};</pre><p>The sorting sequence in s3</p><ol><li>0–9</li><li>A-Z</li><li>_ (underscore)</li><li>a to z</li></ol><h4>Create new folder</h4><p>To create a folder we just need to use / end of the folder name without body.</p><pre>putObject() {<br>  const params = {<br>    Bucket: bucketName,<br>    Key: &#39;new-folder/&#39;,<br>    ACL: &#39;public-read&#39;<br>  }<br>  s3.putObject(params, (error, success) =&gt; {<br>    if (error) {<br>      console.log(&#39;error: &#39;, error);<br>    } else {<br>      console.log(&#39;success: &#39;, success);<br>    }<br>  })<br>},</pre><p>Creating nested folder is also very simple. As we already know technically there is no concept of the folder in aws s3 but we can prefix folder names for a key.</p><p>Let’s say there is a outer-folder and we want to create inner-folder inside it.</p><p>So the key will be outer-folder/inner-folder/ .</p><p>Thank you…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=25bf459173f8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Essential & useful gems for a Rails app]]></title>
            <link>https://kishanptl-kp.medium.com/essential-useful-gems-for-a-rails-app-513ef8bf6c68?source=rss-cd54f0568629------2</link>
            <guid isPermaLink="false">https://medium.com/p/513ef8bf6c68</guid>
            <category><![CDATA[useful]]></category>
            <category><![CDATA[rails]]></category>
            <category><![CDATA[best]]></category>
            <category><![CDATA[gem]]></category>
            <category><![CDATA[rubygems]]></category>
            <dc:creator><![CDATA[Kishan Patel]]></dc:creator>
            <pubDate>Sat, 28 Nov 2020 20:49:21 GMT</pubDate>
            <atom:updated>2021-03-30T08:37:14.856Z</atom:updated>
            <content:encoded><![CDATA[<h3>Essential &amp; useful gems and library for a Rails app</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*Kr_-pHwniG4JD5UD9AF6mg.png" /></figure><h4>For better coding</h4><ul><li><a href="https://github.com/rubocop-hq/rubocop">Rubocop</a></li><li><a href="https://github.com/brigade/overcommit">Overcommit</a></li></ul><h4>Debugging</h4><ul><li><a href="https://github.com/BetterErrors/better_errors">Better_errors</a></li><li>Pry-byebug</li><li>Pry-rails</li></ul><p><strong>Authentication &amp; Authorization</strong></p><ul><li><a href="https://github.com/plataformatec/devise">Devise</a> (deprecated)</li><li><a href="https://github.com/thoughtbot/clearance">Clearance</a></li><li><a href="https://github.com/omniauth/omniauth">OmniAuth</a> (Authentication via social networks accounts like Google or Facebook)</li><li><a href="https://github.com/CanCanCommunity/cancancan">CanCanCan</a></li><li><a href="https://github.com/varvet/pundit">Pundit</a></li><li><a href="https://github.com/RolifyCommunity/rolify">Rolify</a></li><li>Active Admin</li></ul><p><strong>Performance analyzer</strong></p><ul><li><a href="https://github.com/ankane/pghero">PGHero</a>: A performance dashboard for Postgres</li><li><a href="https://www.skylight.io/support/getting-started">Skylight</a>: To understand and act on your app’s performance data</li><li>Bullet</li><li>RubyCritic</li></ul><h4>Testing</h4><ul><li>Rspec</li><li><a href="https://github.com/DatabaseCleaner/database_cleaner">Database_cleaner</a></li><li><a href="https://github.com/thoughtbot/factory_girl">Factory_girl</a></li><li><a href="https://github.com/jnicklas/capybara">Capybara</a></li><li><a href="https://github.com/thoughtbot/shoulda-matchers">Shoulda-matchers</a></li><li>Simplecov</li></ul><p><strong>For development env</strong></p><ul><li>Letter Opener</li><li><a href="https://github.com/bkeepers/dotenv">Dotenv-Rails</a></li></ul><h4>Uploading Files</h4><ul><li><a href="https://edgeguides.rubyonrails.org/active_storage_overview.html"><em>Active Storage</em></a><em>: Facilitates uploading files to a cloud storage service.</em></li><li><a href="https://github.com/carrierwaveuploader/carrierwave">CarrierWave</a>: Provides a simple and extremely flexible way to upload files from Ruby applications</li><li><a href="https://github.com/minimagick/minimagick">Minimagick</a></li></ul><h4>Search</h4><ul><li>Elasticsearch-model , elasticsearch-rails</li></ul><h4><strong>Encryption</strong></h4><ul><li><a href="https://github.com/jwt/ruby-jwt">JWT</a></li></ul><h4>Pagination</h4><ul><li>Will_paginate</li><li><a href="https://github.com/kaminari/kaminari">Kaminari</a>: A Scope &amp; Engine based, clean, powerful, customizable and sophisticated paginator.</li></ul><p>Background Job</p><ul><li>Delayed Job</li><li>Sidekiq</li></ul><h4>Other some awesome gems and library</h4><ul><li><a href="https://github.com/ondrejbartas/sidekiq-cron">sidekiq-cron</a></li><li><a href="https://github.com/rails-api/active_model_serializers">ActiveModelSerializers</a></li><li>Jbuilder</li><li>Fast_jsonapi</li><li><a href="https://github.com/ohler55/oj">OJ</a>: A <em>fast</em> JSON parser and Object marshaller as a Ruby gem.</li><li>Haml, Slim-rails</li><li>Activerecord-import</li><li><a href="https://github.com/jcypret/hashid-rails">Hashid Rails</a></li><li>Flipper</li><li>Bulk_insert</li><li>Geocoder</li><li><a href="https://github.com/paper-trail-gem/paper_trail">PaperTrail</a>: Track changes to your models, for auditing or versioning.</li><li><a href="https://github.com/ankane/groupdate">Groupdate</a>: The simplest way to group by the hour, day, week, month, year etc.</li><li>Http, Httparty</li></ul><p>Thanks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=513ef8bf6c68" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mail Interceptor Rails]]></title>
            <link>https://blog.francium.tech/mail-interceptor-rails-ece0f48c7cef?source=rss-cd54f0568629------2</link>
            <guid isPermaLink="false">https://medium.com/p/ece0f48c7cef</guid>
            <category><![CDATA[interceptors]]></category>
            <category><![CDATA[mail]]></category>
            <category><![CDATA[whitelist]]></category>
            <category><![CDATA[actionmailer]]></category>
            <category><![CDATA[whitelisting]]></category>
            <dc:creator><![CDATA[Kishan Patel]]></dc:creator>
            <pubDate>Sat, 28 Nov 2020 20:35:18 GMT</pubDate>
            <atom:updated>2023-01-06T17:29:54.914Z</atom:updated>
            <content:encoded><![CDATA[<h3>Rails mail interceptor and whitelist emails</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*po_7Sc5cjSasmKu0.jpg" /></figure><p>In most of the application, it requires to send email through the app itself like sending email to the user after registration, forgot password, sending feedback, etc. In most cases, we used to have a development, staging, and production server.</p><p>To test email functionality in the development server we can use letter_opener gem. And to test in the staging server we really need to send an email to the user. This could be a risk because it can send a test email to a real user. To solve this problem Rails provides a mail interceptor using ActionMailer and we can whitelist email.</p><ul><li><strong>What is a mail interceptor?</strong></li></ul><p>When using ActionMailer in Rails, there is a way to hook into the outbound message after you call the “deliver” method, but before it is actually sent to the delivery agents. You can think of these interceptors a little like before action filters in the controller, or like middleware in Rack.</p><ul><li><strong>What is email whitelisting?</strong></li></ul><p>To whitelist an email address means you add them to your approved senders list. This tells your email client that you know this sender and trusts them.</p><p><strong>Overall idea</strong></p><ul><li>Create a model to store whitelist emails.</li><li>Implement mail interceptor.</li><li>Before sending a mail check if the email id is present in the whitelist emails.</li><li>If the email id is whitelisted then send an email to the user otherwise terminate the mail delivery process.</li></ul><p>Let’s quickly get started on the code sample.</p><ul><li>Generate a migration file to create WhitelistEmail model</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L2ajThIsHcSHCsjmSJSsKg.png" /></figure><ul><li>Create a file app/mailers/staging_mail_interceptor.rb and below code sample to the file.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fG_4-kbGsi14iCuL4TEMjQ.png" /></figure><ul><li>Then, place below code inside config/environments/staging.rb</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zReQRbLdIJ6C8rb_NW1c_A.png" /></figure><p>That’s all, now it will send email from the staging server to whitelisted emails only.</p><p>Thanks for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ece0f48c7cef" width="1" height="1" alt=""><hr><p><a href="https://blog.francium.tech/mail-interceptor-rails-ece0f48c7cef">Mail Interceptor Rails</a> was originally published in <a href="https://blog.francium.tech/">Francium Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[FAQs on Ruby]]></title>
            <link>https://blog.francium.tech/faqs-on-ruby-ea28736bedae?source=rss-cd54f0568629------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea28736bedae</guid>
            <category><![CDATA[rails]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[interview-questions]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[faq]]></category>
            <dc:creator><![CDATA[Kishan Patel]]></dc:creator>
            <pubDate>Sun, 31 May 2020 10:09:35 GMT</pubDate>
            <atom:updated>2023-03-23T03:46:50.419Z</atom:updated>
            <content:encoded><![CDATA[<p>Ruby is an open-source pure object-oriented programming language developed by <strong>Yukihiro Matsumoto</strong>. The first version of the language (0.95) was released in <a href="https://www.computerhope.com/history/1995.htm">1995</a>, and in 2011, version 1.9.3 was released.</p><h4>What is the difference between a class and a module?</h4><ul><li>Basically, <strong>a class can be instantiated but a module cannot</strong>. A module will never be anything other than a library of methods. A class can be so much more — it can hold its state (by keeping track of instance variables) and be duplicated as many times as you want. It’s all about <em>objects</em>.</li><li>If you need to instantiate something or otherwise have it exist over time, that’s when you need to use a class instead of a module.</li></ul><h4>How would you declare and use a constructor in Ruby?</h4><ul><li>Constructor without argument.</li></ul><pre>class Demo</pre><pre>  # constructor<br>  def initialize<br>    puts &quot;Welcome to GeeksforGeeks!&quot;<br>  end</pre><pre>end</pre><pre># Creating Obejct<br>Demo.new</pre><ul><li>Constructor with argument.</li></ul><pre>class Person</pre><pre># constructor<br>  def initialize (name)<br>    puts &quot;Person name is : #{name}.&quot;<br>  end</pre><pre>end</pre><pre># Creating Obejct<br>Person.new &#39;Kishan&#39;</pre><h4>Comment code in ruby</h4><ul><li>Single line comment</li></ul><pre># this is a commented line</pre><ul><li>Multi-line comment</li></ul><pre>=begin<br>all<br>text<br>inside the<br>block are<br>commented<br>=end</pre><h4>How would you create getter and setter methods in Ruby?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BJHCNFG8tY6eFfvCWbLTYA.png" /></figure><h4>Can you access private and protected methods outside of a class?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cz_azDEEMO82d1nPfcMVrg.png" /></figure><h4>Difference between the private and protected methods in Ruby?</h4><p><strong><em>“In ruby, private methods are not accessible by an explicit receiver.”</em></strong></p><p>To understand this statement, let&#39;s look at the next code snippet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*exh_JMVZCxB04hKN9WGFwg.png" /></figure><ul><li>Explain how (almost) everything is an object in Ruby.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/1*k86-CAdhuI63PytDHY-EGw.png" /></figure><h4>Explain what singleton methods are. What is Eigenclass in Ruby?</h4><h4>Describe the Ruby method lookup path.</h4><p>A simple question but hard to answer. Why is that hard? Because Ruby has various ways of defining a method and add it to a class:</p><ul><li>Adding it to the singleton class</li><li>Adding it to the class</li><li>Include a module</li><li>Prepend a module</li><li>Extend a module</li><li>Inherit from superclass</li></ul><h4>Include vs extend</h4><p>Modules are used</p><ul><li>To write reusable code</li><li>To provide namespacing</li></ul><p><strong>Include</strong> a module — to pull the methods as <strong>instance methods.</strong></p><p><strong>Extend</strong> a module — to pull the methods as <strong>class methods.</strong></p><h4>Include vs prepend</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uI2U7MR83o9Q7JUq12x_Xw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hMtlk6T5q_XEnUCdnQLhIw.png" /></figure><h3>Extend</h3><p>When using the extend method instead of include, you are adding the module’s methods as class methods instead of as instance methods.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YPBpZXfXAWuzyTkZpNa4Kw.png" /></figure><h4>Require vs load</h4><p><strong>require</strong> reads and parses files only once, when they were referenced for the first time. It keeps track of whether that library was already loaded or not. You also don’t need to specify the “.rb” extension of the library file name.</p><pre>require &#39;abc&#39;</pre><p><strong>load</strong> reads and parses files every time you call `load`. Using the <strong>load</strong> method you must specify the “.rb” extension of the library file name.</p><pre>load &#39;abc.rb&#39;</pre><h4>Require vs require_relative</h4><p><strong>require_relative</strong> is just like <strong>require</strong>, except that instead of searching your Ruby path, it searches relative to the current directory.</p><h4>What is the difference between block, proc, and lambda?</h4><ul><li>Proc and lambda are objects but blocks are not.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mqgWAXMabD3LpRMoXELi5w.png" /></figure><h4>Lambda vs Proc</h4><p>Before I get into the differences between procs and lambdas, it is important to mention that they are both Proc objects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OgHoD6DEuUuXCy65aYGpeA.png" /></figure><ul><li><strong>Lamdas check the number of arguments, while procs do not</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VBSbHVuL5a-g5BF9TENKEQ.png" /></figure><p>In contrast, procs don’t care if they are passed the wrong number of arguments.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ftvGKIAZ53HPzIcIjJHUjg.png" /></figure><ul><li><strong>Lamdas and procs treat the ‘return’ keyword differently</strong></li></ul><p>‘return’ inside of a lambda triggers the code right outside of the lambda code</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hjaNptynPF3nUYca_Ywm9g.png" /></figure><p>‘return’ inside of a proc triggers the code outside of the method where the proc is being executed</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1hulx9KJRlSt71C702BeCw.png" /></figure><h3>Array Methods</h3><ul><li>map || collect</li><li>each</li><li>select</li><li>find || detect</li><li>reject</li><li>inject</li></ul><h4>map</h4><p>| <strong>collect</strong> is the alias of <strong>map</strong>.</p><p>Performs an action on each array element. The original array is not modified. Returns the modified array.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*hshhufNEL8U1MIy9Ifm_wA.png" /></figure><h4>each</h4><p>Executes an action using as a parameter each element of the array. Returns the unmodified array.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/1*jg8AfnO7u42werajPsbwfQ.png" /></figure><h4>select</h4><p>Runs an expression for each array element and, if it is true, that element gets added to the output which is returned. This is called <strong>filter</strong> in other languages.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*_FME12cbur5rIkJMaAXxzQ.png" /></figure><h4>find</h4><p>|<strong>detect</strong> alias for <strong>find</strong></p><p>Take an expression and returns the first element for which the expression returns true:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*uF3c74wB7PH3kwj4cZ7Z_w.png" /></figure><h4>reject</h4><p>The opposite of <strong>select</strong>: runs an expression for each array element and includes that element in the output if the expression is false</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/862/1*4Dzxr5NXlcLYFvVAvDtE6g.png" /></figure><h4>inject</h4><p>| <strong>reduce</strong> is the alias for <strong>inject</strong></p><p>Takes an accumulator (sum) and changes it as many times as there are elements in the array. Returns the final value of the accumulator.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/924/0*woXbaKdV7JP4Sh_f" /></figure><p>You can also specify an <strong>initial value</strong> as a parameter before the block.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P7C6qp7Pg-tRQDwnwGuuqw.png" /></figure><h4>Difference between size, length, and count.</h4><ul><li><strong>count </strong>tends to refer to the number of elements in a looser collection.</li><li><strong>length or it’s alias size</strong>: tends to refer to contiguous elements — a string has a length for example.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C8xrCrKLDDYgfcB_a1gKSA.png" /></figure><h4>Difference between .blank?, .nil?, .empty?</h4><p><strong><em>.blank?</em></strong> is the opposite of <strong><em>.present?</em></strong>. Through <strong><em>.blank?</em></strong> you can check nil as well empty.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PzsJ0SsVBw2wyi79pOXAIg.png" /></figure><h4>Use of dig method.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/898/1*Zv09HVNT2YlLv-AG_V-FLQ.png" /></figure><h4>and Vs &amp;&amp;</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JHCbELtdC8Lbmrz1UGz6-Q.png" /></figure><blockquote>Operator ‘<strong>=</strong>’ has higher precedence than ‘and’ operator. So ‘true’ is assigned to variable ‘a’.</blockquote><h4>True or False</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JnenSi2QfHqXypYNFXM0VQ.png" /></figure><h3>Loops in Ruby</h3><ul><li>for loop</li><li>while loop</li><li>do..while loop</li><li>until loop</li></ul><h4>for loop</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ul2g-bvDGgD-tjmZlF5z1A.png" /></figure><h4>while loop</h4><p>| Execute as long as the condition is true .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eDtWFVrwadINBPZhzYkbSg.png" /></figure><h4>do-while loop</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SJkPl5W6YSEtKk5wWzoPqw.png" /></figure><h4>until loop</h4><p>| Executes as long as the condition is false. Or <strong>Until</strong> loop will continue to run until a certain condition is met.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aCOQpldJvNHEeOtqROeDpQ.png" /></figure><h4>while vs until</h4><p><strong>Until</strong> loop will continue to run until a certain condition is met.<br><strong>While</strong> loops run as long as the condition is true.</p><h4>Redo vs retry</h4><p><strong>Redo<br></strong>| Redo the current loop</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ffUz-CW1EgXFb4XERlNi6Q.png" /></figure><p><strong>Retry<br></strong>|Retry the loop from beginning</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cUI9ymmWP_8vc5ei3uXRUA.png" /></figure><h4>String vs symbol</h4><p>A <strong>string</strong> is a <strong>mutable</strong> instance of <strong>String</strong> class and two strings with the same contents are two different objects.</p><pre>&quot;apple&quot;.object_id<br> =&gt; 70280408292320</pre><pre>&quot;apple&quot;.object_id<br> =&gt; 70280408286140<br> <br>&quot;apple&quot;.class<br>=&gt; String</pre><p>A <strong>symbol</strong> is an <strong>immutable</strong> instance of <strong>Symbol</strong> class and two symbols with the same contents point to the same object.</p><pre>x = :aa<br>y = :aa</pre><pre>x.object_id<br> =&gt; 1525788<br>y.object_id<br> =&gt; 1525788</pre><p>Explore more on <a href="https://launchschool.com/blog/references-and-mutability-in-ruby#:~:text=Mutable%20Objects,object&#39;s%20state%20in%20some%20way.">string and symbol</a>.</p><pre>&quot;apple&quot;.object_id<br> =&gt; 70280408286140<br> <br>&quot;apple&quot;.class<br>=&gt; String</pre><h4>Mixins</h4><p>Ruby does not support multiple inheritances directly and instead uses a facility called <strong>mixin</strong>. Mixins in Ruby allows <a href="https://www.geeksforgeeks.org/ruby-module/">modules</a> to access instance methods of another one using <strong>include</strong> method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PK7zqskt0gsgqECwp-HHfw.png" /></figure><h4>Alias and alias_method</h4><p>You can only use this method at the class &amp; module level, but not inside instance methods. Click <a href="https://www.rubyguides.com/2018/11/ruby-alias-keyword/">here</a> to explore more.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4TreLAajorHtE5uPC6GW5Q.png" /></figure><h4>Tap method</h4><p>|It just allows you to do something with an object inside of a block, and always have that block return the object itself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yz805Nf8qrbN2gejZWffrw.png" /></figure><h4>Zip array method</h4><p>| Combine two array into one hash.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HpTwlHX9fQejVdIRyKnq7Q.png" /></figure><h4>Sample array method</h4><p>| Returns<strong> </strong>a random element or n random elements from the array.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FfKDtTudclu_Gr4z5v_fSg.png" /></figure><p>Thank you for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea28736bedae" width="1" height="1" alt=""><hr><p><a href="https://blog.francium.tech/faqs-on-ruby-ea28736bedae">FAQs on Ruby</a> was originally published in <a href="https://blog.francium.tech/">Francium Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Javascript FAQs]]></title>
            <link>https://kishanptl-kp.medium.com/javascript-faqs-eb2e828a0593?source=rss-cd54f0568629------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb2e828a0593</guid>
            <category><![CDATA[tips-and-tricks]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[faq]]></category>
            <category><![CDATA[es6]]></category>
            <category><![CDATA[interview-questions]]></category>
            <dc:creator><![CDATA[Kishan Patel]]></dc:creator>
            <pubDate>Fri, 24 Apr 2020 19:04:03 GMT</pubDate>
            <atom:updated>2026-02-26T10:54:11.998Z</atom:updated>
            <content:encoded><![CDATA[<p>For beginners &amp; intermediates</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aKUAg2a4sa6JXwFUvkiwTA.png" /></figure><p>Javascript is a synchronous single-threaded language. It means, JS can execute single command at a time in a specific order.</p><h4>Deep copy</h4><p>A deep copy means that all of the values of the new variable are copied and <strong>disconnected from the original </strong>variable.</p><pre>var a = 5;<br>var b = a; // 5<br>b = 6;<br>console.log(a);  // 5<br>console.log(b);  // 6</pre><h4>Shallow copy</h4><p>A shallow copy means that certain (sub-)values are <strong>still connected</strong> to the original variable.</p><pre>var user = { name: &#39;Kishan&#39;, gender: &#39;M&#39; };<br>var user2= user; <br>user2.name = &#39;Kishan Patel&#39;;<br>// Since &#39;user2&#39; is reference of &#39;user&#39;<br>console.log(user);  // { name: &#39;Kishan Patel&#39;, gender: &#39;M&#39; };<br>console.log(user2);  // { name: &#39;Kishan Patel&#39;, gender: &#39;M&#39; };<br><br>// Same applies to array<br>var a = [1]<br>var b = a;<br>b.push(2);<br>console.log(a); // [1,2]<br>console.log(b); // [1,2]</pre><h4>structuredClone</h4><pre>// Create an ArrayBuffer with a size in bytes<br>const buffer1 = new ArrayBuffer(16);<br><br>const object1 = {<br>  buffer: buffer1,<br>};<br><br>// Clone the object containing the buffer, and transfer it<br>const object2 = structuredClone(object1, { transfer: [buffer1] });</pre><h4>Use Strict</h4><p>&quot;use strict&quot;; Defines that JavaScript code should be executed in &quot;strict mode&quot;.</p><pre>&quot;use strict&quot;;<br>x = 3.14;    // This will cause an error because x is not declared<br>---<br>&quot;use strict&quot;;<br>myFunction();<br>function myFunction() {<br>  y = 3.14;   // This will also cause an error because y is not declared<br>}</pre><h3>Ways to create Object and Array</h3><ul><li>Create Array</li></ul><pre>// Array Literal:<br>const arr1 = [1,2,3,4];<br><br>// Array Constructor<br>const arr2 = new Array(1,2,3,4);<br><br>// Array.of():<br>const arr3 = Array.of(1, 2, 3, 4);<br><br>// Array.from():<br>let arr4 = Array.from(&quot;Hello&quot;); // [&#39;H&#39;, &#39;e&#39;, &#39;l&#39;, &#39;l&#39;, &#39;o&#39;]</pre><ul><li>Create Object</li></ul><pre>// Object Literal:<br>let obj1 = {a: 1, b: 2}<br><br>// Object Constructor<br>let obj2 = new Object({a: 1, b: 2})<br><br>// Object.create():<br>const obj3 = Object.create(null);<br>obj.a = 1;<br>obj.b = 2;<br><br>// Factory Function:<br>function createPerson(name, age) {<br>  return {<br>    name: name,<br>    age: age<br>  };<br>}<br>const person = createPerson(&#39;John&#39;, 25);<br><br>// ES6 Object.assign():<br>const obj1 = { name: &#39;John&#39; };<br>const obj2 = { age: 25 };<br>const obj = Object.assign(obj1, obj2);</pre><h3>What are the array detection mutation methods?</h3><p>As the name suggests, mutation methods modify the original array. Below is the list of array mutation methods that trigger view updates.</p><ul><li><strong>push() <br></strong>| Add an element at the last of an array.</li></ul><pre>let arr = [1,2,3,4];<br>arr.push(5);<br>console.log(arr) // [1, 2, 3, 4, 5]</pre><ul><li><strong>unshift()</strong><br>| Add an element at the beginning of an array.</li></ul><pre>let arr = [1,2,3,4];<br>arr.unshift(0);<br>console.log(arr) // [0, 1, 2, 3, 4]</pre><ul><li><strong>pop()</strong><br>| Remove the last element of an array.</li></ul><pre>let arr = [1,2,3,4];<br>arr.pop(0);<br>console.log(arr) // [1, 2, 3]</pre><ul><li><strong>shift()</strong><br>| Remove the first element of an array.</li></ul><pre>let arr = [1,2,3,4];<br>arr.shift(0);<br>console.log(arr) // [2, 3, 4]</pre><ul><li><strong>splice()</strong><br>| Splice is used for multiple purposes:<br>1. to insert an element at the specified index.<br>2. to replace one or multiple elements in an array.<br>3. to remove an element from the selected index.</li></ul><pre>months = [&#39;Jan&#39;, &#39;Feb&#39;, &#39;Apr&#39;, &#39;Jun&#39;, &#39;Aug&#39;];<br>months.splice(2, 0, &#39;Mar&#39;);<br>console.log(months); // [&#39;Jan&#39;, &#39;Feb&#39;, &#39;Mar&#39;, &#39;Apr&#39;, &#39;Jun&#39;, &#39;Aug&#39;]<br><br>months.splice(4, 2, &#39;May&#39;); // Replace &#39;Jun&#39;, &#39;Aug&#39; with &#39;May&#39;<br>console.log(months); // [&#39;Jan&#39;, &#39;Feb&#39;, &#39;Mar&#39;, &#39;Apr&#39;, &#39;May&#39;]<br><br>months.splice(1, 3); // Remove 3 elements starting from index 1<br>console.log(months); // [&#39;Jan&#39;, &#39;May&#39;]</pre><ul><li><strong>sort()</strong><br>| Used to sort an array with ascending order.</li></ul><pre>let numArr = [3,2,4,1,5];<br>numArr.sort();<br>console.log(numArr); // [1, 2, 3, 4, 5]</pre><ul><li><strong>reverse()</strong><br>| Used to reverse an array</li></ul><pre>let numArr = [3,2,4,1,5];<br>numArr.reverse();<br>console.log(numArr); // [5, 1, 4, 2, 3]</pre><ul><li>To sort an array in descending order you can combine sort() &amp; reverse()</li></ul><pre>let numArr = [3,2,4,1,5];<br>numArr.sort().reverse();<br>console.log(numArr); // [5, 4, 3, 2, 1]</pre><h3>What are the array detection non-mutation methods?</h3><p>The methods which do not mutate the original array but always return a new array are called non-mutation methods. Below is the list of non-mutation methods.</p><blockquote>The following methods will not modify the original array.</blockquote><ul><li><strong>filter()</strong><br>| Used to filter array with given condition</li></ul><p>Example 1:</p><pre>// Example 1:<br>let numArr = [1,2,3,4,5,6];<br>numArr.filter(num =&gt; num &gt; 2); // [3,4,5,6]<br>console.log(numArr); // [1,2,3,4,5,6]</pre><p>Example 2:</p><p>In below example .filter(Boolean) is the same as .filter(x =&gt; Boolean(x)).</p><pre>let address = &quot;foo&quot;;<br>let city;<br>let state = &quot;bar&quot;;<br>let zip;<br><br>let text = [address, city, state, zip].filter(Boolean).join(&quot;, &quot;);<br>console.log(text); // foo, bar</pre><ul><li><strong>concat()</strong><br>| Used to combine two arrays and to add an element to the last.</li></ul><pre>const array1 = [&#39;a&#39;, &#39;b&#39;, &#39;c&#39;];<br>const array2 = [&#39;d&#39;, &#39;e&#39;, &#39;f&#39;];<br><br>const array3 = array1.concat(array2);<br>console.log(array3); //  [&#39;a&#39;, &#39;b&#39;, &#39;c&#39;, &#39;d&#39;, &#39;e&#39;, &#39;f&#39;]<br><br>console.log(array3.concat(&#39;g&#39;)); // [&#39;a&#39;, &#39;b&#39;, &#39;c&#39;, &#39;d&#39;, &#39;e&#39;, &#39;f&#39;, &#39;g&#39;]</pre><ul><li><strong>slice()<br>| </strong>The <strong>slice()</strong> method returns a shallow copy of a portion of an array into a new array object selected from begin to end (end not included) where begin and end represent the index of items in that array.</li></ul><pre>const animals = [&#39;Ant&#39;, &#39;Bison&#39;, &#39;Camel&#39;, &#39;Elephant&#39;, &#39;Tiger&#39;];<br><br>console.log(animals.slice()); // [&#39;Ant&#39;, &#39;Bison&#39;, &#39;Camel&#39;, &#39;Elephant&#39;, &#39;Tiger&#39;]<br><br>console.log(animals.slice(2)); // [&#39;Camel&#39;, &#39;Elephant&#39;, &#39;Tiger&#39;]<br><br>console.log(animals.slice(2, 4)); // [&#39;Camel&#39;, &#39;Elephant&#39;]<br><br>console.log(animals.slice(1, 5)); // [&#39;Bison&#39;, &#39;Camel&#39;, &#39;Elephant&#39;, &#39;Tiger&#39;]</pre><ul><li>reduce()</li></ul><pre>const array1 = [1,2,3,4];<br><br>const reducer = (accumulator, currentValue) =&gt; accumulator + currentValue;<br><br>console.log(array1.reduce(reducer)); // 1 + 2 + 3+ 4 + 5 =&gt; 10<br><br>const array2 = [5,4,3,2,1];<br>console.log(array2.reduce(reducer)); // 5 + 4 + 3 + 2 + 1 =&gt; 15</pre><h4>Object.groupBy</h4><pre>const people = [<br>  { name: &#39;Kishan&#39;, age: 30 },<br>  { name: &#39;Rakesh&#39;, age: 32 },<br>  { name: &#39;Kedar&#39;, age: 26 },<br>  { name: &#39;Ajay&#39;, age: 26 }<br>];<br><br>const groupByAge = Object.groupBy(people, person =&gt; person.age);<br>console.log(groupByAge);<br>// Output<br>/*<br>{<br>  26: [<br>    { name: &#39;Kedar&#39;, age: 26 },<br>    { name: &#39;Ajay&#39;, age: 26 }<br>  ],<br>  30: [{ name: &#39;Kishan&#39;, age: 30 }]<br>  32: [{ name: &#39;Rakesh&#39;, age: 32 }]<br>}<br>*/</pre><h4>Array.prototype.flat()</h4><pre>const arr1 = [0, 1, 2, [3, 4]];<br><br>console.log(arr1.flat());<br>// expected output: Array [0, 1, 2, 3, 4]<br><br>const arr2 = [0, 1, [2, [3, [4, 5]]]];<br><br>console.log(arr2.flat());<br>// expected output: Array [0, 1, 2, Array [3, Array [4, 5]]]<br><br>console.log(arr2.flat(2));<br>// expected output: Array [0, 1, 2, 3, Array [4, 5]]<br><br>console.log(arr2.flat(Infinity));<br>// expected output: Array [0, 1, 2, 3, 4, 5]</pre><p>Check out <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array">here</a> for more array methods.</p><h3>Object Methods</h3><ul><li><strong>Object.keys</strong> &amp; <strong>Object.values</strong></li></ul><pre>const object1 = {<br>  name: &#39;Kishan&#39;,<br>  gender: &#39;Male&#39;<br>};<br><br>Object.keys(object1); // [&#39;name&#39;, &#39;gender&#39;]<br>Object.values(object1); // [&#39;Kishan&#39;, &#39;Male&#39;]</pre><ul><li><strong>Object.entries</strong></li></ul><pre>const object1 = {<br>  a: &#39;somestring&#39;,<br>  b: 42<br>};<br><br>for (const [key, value] of Object.entries(object1)) {<br>  console.log(`${key}: ${value}`);<br>}<br><br>// Expected output:<br>// &quot;a: somestring&quot;<br>// &quot;b: 42&quot;</pre><ul><li><strong>Object.hasOwn()</strong></li></ul><p>The Object.hasOwn() static method returns true if the specified object has the indicated property as its <em>own</em> property.</p><pre>const user = {<br>  firstName: &#39;Jhon&#39;<br>};<br><br>console.log(Object.hasOwn(user, &#39;firstName&#39;));<br>// Expected output: true<br>console.log(Object.hasOwn(user, &#39;lastName&#39;));<br>// Expected output: false</pre><p>Checkout <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object">here</a> for more Object methods</p><h3>Most commonly used string methods</h3><ul><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substr">substr()</a> → Deprecated</li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/substring">substring()</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/charAt">charAt</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/concat">concat</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes">includes</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf">indexOf</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/lastIndexOf">lastIndexOf</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace">replace</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replaceAll">replaceAll</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toLowerCase">toLowerCase()</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/toUpperCase">toUpperCase()</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/trim">trim()</a></li></ul><h3>Lexical Scope</h3><pre>var a = 10;<br>var func = function (){<br>    var b = 20;<br>    console.log(&quot;a and b is accessible (outer):&quot;, a, b);<br>    var innerFunc= function (){<br>        var c = 30;<br>        console.log(&quot;a and b and c is accessible (inner):&quot;, a, b, c);<br>    }<br>    innerFunc();<br>    return;<br>}<br>func();<br>console.log(&quot;only a is accessible (global):&quot;, a);</pre><blockquote>ES6 new features…</blockquote><p>ES stands for ECMA Script.</p><h3>let Vs var</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B5lAE2N9GNUk2LoxYwvnBw.png" /></figure><h3>What is a spread operator?</h3><p>The spread operator is a useful and quick syntax for adding items to arrays, combining arrays or objects, and spreading an array out into a function’s arguments.</p><ul><li><strong>Joining two objects</strong></li></ul><pre>const hash = {a: 1, b: 2};<br>console.log({...hash, ...{c: 3}}); // {a: 1, b: 2, c: 3}</pre><ul><li>Concat object conditionally</li></ul><pre>const a = {a: 1, b: 2}<br>const c = {c: 3, ...(true &amp;&amp; a)}</pre><ul><li><strong>Joining two arrays</strong></li></ul><pre>const fruits = [&#39;Mango&#39;, &#39;Banana&#39;, &#39;Apple&#39;]<br>console.log([&#39;Grapes&#39;, ...fruits, &#39;Goava&#39;]);<br>// [&#39;Grapes&#39;, &#39;Mango&#39;, &#39;Banana&#39;, &#39;Apple&#39;, &#39;Goava&#39;]</pre><h3>Destructuring</h3><pre>var [head, ...tail] = [1, 2, 3, 4];<br>console.log(head); // 1<br>console.log(tail); // [2, 3, 4]</pre><h3>What is the rest parameter?</h3><p>The <strong>rest parameter</strong> syntax allows us to represent an indefinite number of arguments as an array.</p><pre>function sum(...theArgs) {<br>  let total = 0;<br>  for (const arg of theArgs) {<br>    total += arg;<br>  }<br>  return total;<br>}<br><br>console.log(sum(1, 2, 3));  // 6<br><br>console.log(sum(1, 2, 3, 4)); // 10</pre><h3>Arrow function Vs. normal function</h3><ol><li><strong>Syntax</strong></li></ol><pre>let add = (x, y) =&gt; {<br>  // do some other calculation<br>  return &quot;Sum of two numbers: &quot; + (x + y)<br>}</pre><p>Return in one line:</p><pre>let add = (x, y) =&gt; x + y;</pre><p>If there’s only one argument, then the parentheses are not required either.</p><pre>let squareNum = x =&gt; x * x;</pre><p>Without argument</p><pre>let sayHi = _ =&gt; console.log(&quot;Hi&quot;);</pre><p><strong>2. Use of this keyword</strong></p><p>Unlike regular functions, arrow functions do not have their own this. The value of this inside an arrow function remains the same throughout the lifecycle of the function and is always bound to the value of this in the closest non-arrow parent function.</p><p>Example:</p><pre>const user = {<br>    id: 1,<br>    firstName: &#39;Kishan&#39;,<br>    lastName: &#39;Patel&#39;,<br>    getFullName: function() {<br>        // &#39;this&#39; binding works here<br>        return `${this.firstName} ${this.lastName}`;<br>    },<br>    getMyFullName: () =&gt; {<br>        // &#39;this&#39; binding doesn&#39;t work here<br>        return `${this.firstName} ${this.lastName}`;<br>    }<br>}<br><br>console.log(user.getFullName()); // Kishan Patel<br>console.log(user.getMyFullName()); // undefined undefined</pre><p><strong>3. Doesn’t allow duplicate named parameter</strong></p><p>Arrow functions can never have duplicate named parameters, whether in strict or non-strict mode.</p><p>It means that the following is valid JavaScript:</p><pre>function add(x, x){}</pre><p>It is not, however, when using strict mode:</p><pre>&#39;use strict&#39;;<br>function add(x, x){}<br>// SyntaxError: duplicate formal argument x</pre><p>With arrow functions, duplicate named arguments are always, regardless of strict or non-strict mode, invalid.</p><pre>(x, x) =&gt; {}<br>// SyntaxError: duplicate argument names not allowed in this context</pre><p><strong>4. new keyword</strong></p><ul><li>Regular functions created using function declarations or expressions are constructible and callable. Since regular functions are constructible, they can be called using the new keyword.</li><li>However, the arrow functions are only callable and not constructible, i.e arrow functions can never be used as constructor functions. Hence, they can never be invoked with the new keyword.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yy2-_wlSv6fXturiCgP9bw.png" /></figure><h3>Template literals ( ` )</h3><p>| Template literals are string literals allowing embedded expressions. You can use multi-line strings and string interpolation features with them.</p><p>Example:</p><pre>// 1. single line<br>console.log(`Hello there!`); // &quot;Hello there!&quot;<br><br>// 2. multi line<br>console.log(`Hello there!,<br> How are you?`); // &#39;Hello there!,\n How are you?&#39;<br><br>// 3. It is mainly used for variable<br>const name = &#39;Kishan&#39;;<br>console.log(`Hello ${name}, how are you?`); // Hello Kishan, how are you?</pre><h3>Math + Number + String + Array + Object APIs</h3><p>Many new library additions, including core Math libraries, Array conversion helpers, String helpers, and Object.assign for copying.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l42Z3WEbmtps-UyZyz_TrQ.png" /></figure><h3>Nullish coalescing operator (??)</h3><p>The nullish coalescing (??) operator is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand.</p><pre>console.log(null ?? &#39;default string&#39;);  // &quot;default string&quot;<br><br>console.log(undefined ?? 10);  // 10<br><br>console.log(0 ?? 10);  // 0<br><br>console.log(&#39;&#39; ?? 10);  // &#39;&#39;<br><br>console.log(NaN ?? 10);  // Nan</pre><h3>Logical OR || operator</h3><pre>const x = undefined || null || &#39;&#39; || &#39;hello&#39;;<br><br>console.log(x); // Output: &#39;hello&#39;</pre><h3>Bit wise OR operator (|) Vs Logical OR operator (||)</h3><ul><li>Single | is a bitwise OR operator. If you do 2 | 3, it converts to binary and performs OR operation. 01 11 Results in 11 equal to 3.</li><li>Whereas the || operator checks if the first argument is true, if it is true it returns else it goes to the other operator. 2 || 3 returns 2 since 2 is true.</li></ul><h3>JavaScript Numeric Separator (_)</h3><pre>const num1 = 1_000_000_000;<br>const num2 = 1000000000;<br>console.log(num1 === num2); // true</pre><h3>Data Types</h3><h4>Primitive Data</h4><p>A primitive data value is a single simple data value with no additional properties and methods.</p><p>The typeof operator can return one of these primitive types:</p><ul><li>string</li><li>number</li><li>boolean</li><li>undefined</li></ul><h4>Complex Data</h4><p>The typeof operator can return one of two complex types:</p><ul><li>function</li><li>object</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MHkP9xs2fr4eQ0F9NIczjQ.png" /></figure><h4>How to check if a variable is an array</h4><p>Remember typeof returns object for array and object, so we can not distinguish them through typeof keyword, instead we can use Array.isArray method.</p><pre>console.log(typeof({})); // &#39;object&#39;<br>console.log(typeof([])); // &#39;object&#39;<br>console.log(Array.isArray([])); // true</pre><h3>Operators</h3><ul><li><strong>Arithmetic Operators<br></strong>( +, -, *, **, /, %, ++, - -)</li><li><strong>Assignment Operators<br></strong>( =, +=, -=, *=, /=, %=, **= )</li><li><strong>Comparison Operators<br></strong>(==, ===, !=, !==, &gt;, &lt;, &gt;=, &lt;=, ?)</li><li><strong>Logical Operators<br></strong>(&amp;&amp;, ||, !)</li><li>Bitwise Operators<br>(&amp; AND, | OR, ~ NOT, ^ XOR, &lt;&lt; Zero fill left shift, &gt;&gt; Signed right shift, &gt;&gt;&gt; Zero fill right shift)</li></ul><h3>count++ vs ++count</h3><p>In JavaScript, both count++ and ++count are increment operators used to increase the value of a variable by 1. However, they have a slight difference in behavior.</p><ol><li>count++ is the postfix increment operator. It first returns the current value of count and then increments it. Here&#39;s an example:</li></ol><pre>let count = 5;<br>console.log(count++);  // Output: 5<br>console.log(count);    // Output: 6</pre><p>In this case, count++ returns the original value of count, which is 5, and then increments it to 6.</p><p>2. ++count is the prefix increment operator. It increments the value of count first and then returns the updated value. Here&#39;s an example:</p><pre>let count = 5;<br>console.log(++count);  // Output: 6<br>console.log(count);    // Output: 6</pre><p>In this case, ++count increments the value of count to 6 and then returns the updated value.</p><p>Another example</p><pre>let count = 0;<br>console.log(count++ + ++count); // 2<br>// 0 + 2<br><br><br>let newCount = 0;<br>console.log(++count + count++); // 2<br>// 1 + 1</pre><p>Let’s break down the 1st example, expression count++ + ++count step by step:</p><ol><li>count++ is the postfix increment operator. It returns the current value of count (which is 0) and then increments it by 1. So, after this operation, count becomes 1.</li><li>++count is the prefix increment operator. It increments the value of count by 1 (which is now 1) and then returns the updated value. So, the value of count becomes 2.</li><li>Now, we evaluate the expression 0 + 2. Since count++ returned the original value of count before incrementing (which was 0), and ++count returned the updated value of count after incrementing (which is 2), the expression simplifies to 0 + 2, resulting in the value 2.</li></ol><h3>Date Hacks</h3><pre>const date = new Date(2024, 2, 12);<br>// Tue Mar 12 2024 00:00:00<br><br>// Get start date of a given date<br>new Date(date.getFullYear(), date.getMonth()); //  Fri Mar 01 2024 00:00:00<br>// or<br>new Date(date.getFullYear(), date.getMonth(), 1);//Fri Mar 01 2024 00:00:00<br><br>// To get last day of last month put 0 for date<br>new Date(date.getFullYear(), date.getMonth(), 0);<br>// Thu Feb 29 2024 00:00:00<br><br>// So now, to get last date of a given date<br>new Date(date.getFullYear(), date.getMonth() + 1, 0);<br>// Sun Mar 31 2024 00:00:00</pre><p>If the given month is Jan, you can still get the previous month which is Dec of last year.</p><pre>const date = new Date(2024, 0, 1);<br>// Mon Jan 01 2024 00:00:00<br><br>new Date(date.getFullYear(), date.getMonth() - 1, 1);<br>// Fri Dec 01 2023 00:00:00<br><br>new Date(dt.getFullYear(), dt.getMonth(), 0)<br>// Sun Dec 31 2023 00:00:00</pre><h3>Function.prototype.call()</h3><p>| Syntax: func.call(obj)</p><p>The method <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call">Call</a> invokes the function and allows you to pass in arguments one by one using commas.</p><pre>let customer1 = { name: &#39;Leo&#39;, email: &#39;leo@gmail.com&#39; };<br>let customer2 = { name: &#39;Nat&#39;, email: &#39;nat@hotmail.com&#39; };<br>function greeting(text) {<br>    console.log(`${text} ${this.name}`);<br>}<br>greeting.call(customer1, &#39;Hello&#39;); // Hello Leo<br>greeting.call(customer2, &#39;Hello&#39;); // Hello Nat</pre><h3>Function.prototype.apply()</h3><p>The method <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply">Apply</a> invokes the function and allows you to pass in arguments as an array.</p><pre>let customer1 = { name: &#39;Leo&#39;, email: &#39;leo@gmail.com&#39; };<br>function greeting(text, text2) {<br>   console.log(`${text} ${this.name}, ${text2}`);<br>}<br>greeting.apply(customer1, [&#39;Hello&#39;, &#39;How are you?&#39;]); // output Hello Leo, How are you?</pre><h3>Function.prototype.bind()</h3><p>The <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind">Bind</a> method returns a new function, allowing you to pass in a <strong>this</strong> array and any number of arguments. Use it when you want that function to later be called with a certain context like events.</p><pre>let customer1 = { name: &#39;Leo&#39;, email: &#39;leo@gmail.com&#39; };<br>function greeting(text) {<br>   console.log(`${text} ${this.name}`);<br>}<br>let helloLeo = greeting.bind(customer1);<br>helloLeo(&#39;Hello&#39;); // Hello Leo</pre><p>The Bind implementation would be like this:</p><pre>Function.prototype.bind = function(context) {<br>    var fn = this;<br>    return function() {<br>        fn.apply(context, arguments);<br>    };<br>};</pre><p><strong>Call</strong> and <strong>Apply</strong> are interchangeable. You can decide whether it’s easier to send in an array or a comma-separated list of arguments. <strong>Bind</strong> is different. It always returns a new function.</p><p>We can use <strong>Bind </strong>to curry functions like in the example. We can take a simple hello function and turn it into a hello on or helloKelly. You can use it for events where we don’t know when they’ll be fired but know what the context is.</p><h3>Promise</h3><p>Example 1:</p><pre>const testPromise = () =&gt; {<br>    return new Promise((resolve, reject) =&gt; {<br>        let a = 2;<br>        if (a == 2) {<br>            resolve(&quot;Success!&quot;)<br>        } else {<br>            reject(&quot;Failed!&quot;)<br>        }<br>    })<br>}<br><br>testPromise()<br>.then((message) =&gt; console.log(message))<br>.catch(message =&gt; console.log(message)); // Success!<br>.finally(() =&gt; {<br>    console.log(&#39;Finally!&#39;);<br> }); // it will always run</pre><p>Example 2: Promise.all</p><pre>const promise1 = new Promise((resolve, reject) =&gt; {<br>    resolve(&#39;Resolved promise 1.&#39;)<br>})<br><br>const promise2 = new Promise((resolve, reject) =&gt; {<br>    resolve(&#39;Resolved promise 2.&#39;)<br>})<br><br>const promise3 = new Promise((resolve, reject) =&gt; {<br>    resolve(&#39;Resolved promise 3.&#39;)<br>})<br><br>Promise.all([<br>    promise1,<br>    promise2,<br>    promise3<br>]).then(message =&gt; {<br>    console.log(message);<br>})<br><br>// Output: [&#39;Resolved promise 1.&#39;, &#39;Resolved promise 2.&#39;, &#39;Resolved promise 3.&#39;]</pre><p>Example 3: Promise.race</p><pre>const promise1 = new Promise((resolve, reject) =&gt; {<br>  setTimeout(resolve, 500, &#39;one&#39;);<br>});<br><br>const promise2 = new Promise((resolve, reject) =&gt; {<br>  setTimeout(resolve, 100, &#39;two&#39;);<br>});<br><br>Promise.race([promise1, promise2]).then((value) =&gt; {<br>  console.log(value);<br>  // Both resolve, but promise2 is faster<br>});<br>// Expected output: &quot;two&quot;</pre><h4>setTimeout</h4><p>The <strong>setTimeout</strong>() method calls a function after a number of milliseconds.</p><pre>console.log(&#39;Initial&#39;);<br><br>setTimeout(() =&gt; {<br>    console.log(&#39;setTimeOut 1&#39;);<br>}, 1)<br><br>setTimeout(() =&gt; {<br>    console.log(&#39;setTimeOut 2&#39;);<br>}, 0)<br><br>setTimeout(() =&gt; {<br>    console.log(&#39;setTimeOut 3&#39;);<br>})<br><br>console.log(&#39;Last&#39;);<br><br>// Initial<br>// Last<br>// setTimeOut 2<br>// setTimeOut 3<br>// setTimeOut 1</pre><pre><br>for(var i=1; i &lt; 6; i++) {<br>  setTimeout(() =&gt; {<br>      console.log(i);<br>  }, i * 1000)<br>}<br><br>// 6, 6, 6, 6, 6, 6</pre><p>If you just change the <strong><em>var</em></strong> to <strong><em>let</em></strong> it will print 0 to 4, because let is a block scope means each time loop runs it will create a new copy of <strong><em>i</em></strong> with it.</p><pre>for(let i=1; i &lt; 6; i++) {<br>  setTimeout(() =&gt; {<br>      console.log(i);<br>  }, i * 1000)<br>}<br>// 1, 2, 3, 4, 5</pre><p>We can still do it with <strong><em>var</em></strong> using <strong>closure</strong></p><pre>for(var i=1; i &lt; 6; i++) {<br>  function close(x) {<br>      setTimeout(() =&gt; {<br>          console.log(x);<br>      }, x * 1000)<br>  }<br>  close(i);<br>}<br>// 1, 2, 3, 4, 5</pre><p>Wait using setTimeout</p><pre>await new Promise(resolve =&gt; setTimeout(resolve, 2000));</pre><h4>clearTimeout</h4><pre><br>let setTimeoutId = setTimeout(bye, 1);<br><br>console.log(&#39;Hello&#39;);<br><br>clearTimeout(setTimeoutId);<br><br>function bye() {<br>  console.log(&#39;Bye&#39;);<br>}<br><br>// it will just print Hello, it will never say goodbye because we <br>// have cleared the setTimeout</pre><h4>setInterval</h4><p>It will run the function every time after a given millisecond until we clear the interval id</p><pre>const intervalID = setInterval(myCallback, 1000, &quot;Kishan&quot;, &quot;Patel&quot;);<br><br>function welcomeUser(firstName, lastName) {<br>  console.log(`Welcome ${firstName} ${lastName}`)<br>}<br><br>clearInterval(intervalID); // to stop running the function</pre><h4>setImmediate</h4><p>This method is used to break up long-running operations and run a callback function immediately after the browser has completed other operations such as events and display updates.</p><p><strong>Syntax</strong></p><pre>setImmediate(func)<br>setImmediate(func, param0)<br>setImmediate(func, param0, param1)<br>setImmediate(func, param0, param1, /* … ,*/ paramN)</pre><h4>Clouser</h4><p>A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function’s scope from an inner function.</p><pre>function outer() {<br>    var a = 10;<br>    function inner() {<br>        console.log(a);<br>    }<br>    return inner;<br>}<br><br>outer()(); <br>// outer() it will return innter function and by outer()() we are <br>// calling inner function</pre><h3>How Is This Code Safe?</h3><p>Example 1:</p><pre>const id = 1;<br><br>sql`select * from users where id = ${id}`<br><br>function sql(strings, id) {<br>    console.log(strings);<br>    console.log(id);<br>}<br><br>// [ &#39;select * from users where id = &#39;, &#39;&#39; ]<br>// 1</pre><p>Example 2:</p><pre>const id = 1;<br><br>sql`select * from users where id = ${id} OR age &gt; ${18}`<br><br>function sql(strings, id, age) {<br>    console.log(strings);<br>    console.log(id);<br>    console.log(age);<br>}<br><br>// [ &#39;select * from users where id = &#39;, &#39; OR age &gt; &#39;, &#39;&#39; ]<br>// 1<br>// 18</pre><p>Example 3:</p><pre>const id = 1;<br><br>sql`select * from users where id = ${id} OR age &gt; ${18}`<br><br>// using rest params<br>function sql(strings, ...values) {<br>    console.log(strings);<br>    console.log(values);<br>}<br><br>// [ &#39;select * from users where id = &#39;, &#39; OR age &gt; &#39;, &#39;&#39; ]<br>// [1, 18]</pre><p>Now let’s construct the sql to prevent sql injection</p><p>| Note: in the below example the whole id(‘1; DROP TABLE users;’) is wrapped inside double quote.</p><pre>const id = &#39;1; DROP TABLE users;&#39;;<br>const age = 20;<br>const a = sql`select * from users where id = ${id} OR age &gt; ${age};`<br>console.log(a);<br>function sql(strings, ...values) {<br>    return values.reduce((finalString, value, index) =&gt; {<br>        return `${finalString}&quot;${value}&quot;${strings[index+1]}`<br>    }, strings[0])<br>}<br><br>// select * from users where id = &quot;1; DROP TABLE users;&quot; OR age &gt; &quot;20&quot;;</pre><h3>Errors and error handling</h3><p><strong>The following are the 7 types of errors in JavaScript:</strong></p><ul><li><strong>Syntax error</strong> — It occurs when you use a syntax incorrectly.</li></ul><pre>const abc = () =&gt;<br>  console.log(anything)<br>}<br><br>// Output<br>}<br>^<br>SyntaxError: Unexpected token }</pre><p>Here, an opening bracket is missing in the code, which invokes the Syntax error constructor.</p><ul><li><strong>Reference Error</strong> — In a case where a variable reference can’t be found or hasn’t been declared, then a Reference error occurs.</li></ul><pre>console.log(x);<br><br>// Output<br>ReferenceError: x is not defined</pre><ul><li><strong>Type Error</strong> — An error occurs when a value is used outside the scope of its data type.</li></ul><pre>20.split(&quot;&quot;); //converts a number to an array<br>// TypeError: num.split is not a function</pre><pre>let a = 1;<br>a.push(&#39;something&#39;); // pushing a values to non array variable<br><br>// TypeError: a.push is not a function</pre><ul><li><strong>EvalError: </strong>The EvalError object indicates an error regarding the global <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval">eval()</a> function. This exception is not thrown by JavaScript anymore, however the EvalError object remains for compatibility.</li></ul><pre>try {<br>  throw new EvalError(&quot;Hello&quot;);<br>} catch (e) {<br>  console.log(e instanceof EvalError); // true<br>  console.log(e.message); // &quot;Hello&quot;<br>  console.log(e.name); // &quot;EvalError&quot;<br>  console.log(e.stack); // Stack of the error<br>}</pre><ul><li><strong>RangeError</strong> — There is an error when a range of expected values is required, as shown below:</li></ul><pre>const checkRange = (num)=&gt; {<br>  if (num &lt; 30) throw new RangeError(&quot;Wrong number&quot;);<br>  return true<br>}<br><br>checkRange(10);<br><br>// RangeError: Wrong number</pre><ul><li><strong>URI Error</strong> — When the wrong character(s) are used in a URI function, the error is called.</li></ul><pre>console.log(decodeURI(&quot;https://www.google.com&quot;));<br>console.log(decodeURI(&quot;%sdfk&quot;));<br><br>// URIError: URI malformed</pre><ul><li><strong>Internal Error</strong></li></ul><p>Example cases are mostly when something is too large, e.g.:</p><ul><li>too many switch cases</li><li>too many parentheses in regular expression</li><li>array initializer too large</li><li>too much recursion</li></ul><h3>Other</h3><ul><li>document.designMode<br>| document.designMode controls whether the entire document is editable. Valid values are &quot;on&quot; and &quot;off&quot; .</li></ul><pre>console.log(document.designMode); // by default it&#39;s &#39;off&#39;<br>document.designMode = &#39;on&#39;;</pre><ul><li>navigator.clipboard.writeText</li></ul><pre>const copyText = (text) =&gt; navigator.clipboard.writeText(&#39;Kishan&#39;);</pre><h4>Console Hacks</h4><ul><li>console.table</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TagVL7JT5N-leB4D5bogCQ.png" /></figure><ul><li><strong>Console.time</strong></li></ul><p>The console.time() method starts a timer you can use to track how long an operation takes.</p><ul><li><strong>Console.timeLog</strong></li></ul><p>The console.timeLog() method logs the current value of a timer that was previously started by calling console.time().</p><ul><li><strong>Console.timeEnd</strong></li></ul><p>The console.timeEnd() stops a timer that was previously started by calling console.time().</p><pre>console.time(&#39;abc&#39;);<br><br>console.timeLog(&#39;abc&#39;);<br>// abc: xxxx.xxxxxxx ms - current value of a timer<br>// abc: 5487.761962890625 ms<br><br>console.timeLog(&#39;abc&#39;);<br>// abc: 7594.18603515625 ms<br><br>console.timeEnd(&#39;abc&#39;);<br>// abc: 15128.405029296875 ms</pre><h4>Record Screen</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/998/1*J5uyM9rcFIYOms2iM5USXg.jpeg" /></figure><p>Check out my article to <a href="https://medium.com/@kishanptl-kp/deep-dive-into-javascript-70ae7735670">deep dive into Javascript</a>.</p><p>Thank you for reading the article, happy coding…:)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb2e828a0593" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vue JS FAQs]]></title>
            <link>https://blog.francium.tech/vue-js-faqs-ddf744dd4093?source=rss-cd54f0568629------2</link>
            <guid isPermaLink="false">https://medium.com/p/ddf744dd4093</guid>
            <category><![CDATA[faq]]></category>
            <category><![CDATA[vuejs]]></category>
            <category><![CDATA[vuex]]></category>
            <category><![CDATA[vue]]></category>
            <category><![CDATA[interview-questions]]></category>
            <dc:creator><![CDATA[Kishan Patel]]></dc:creator>
            <pubDate>Sat, 11 Apr 2020 17:23:09 GMT</pubDate>
            <atom:updated>2023-08-09T10:03:03.345Z</atom:updated>
            <content:encoded><![CDATA[<p>A JavaScript framework for building user interfaces and single-page app</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-nDzThtUdUrV3HqhQp_LaA.png" /></figure><h3>How to create a Vue project</h3><p>Check out <a href="https://vuejs.org/v2/guide/installation.html">here</a> for more information.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*me76Ios3Mi2iwX-tyO3eYA.png" /></figure><p>Check out <a href="https://cli.vuejs.org/guide/">Vue CLI</a> docs to learn about @vue/cli.</p><h3><strong>What are the major features of VueJS?</strong></h3><p>Below are some of the major features available with VueJS</p><ol><li><strong>Virtual DOM</strong>: Virtual Dom is just simply a JavaScript object which represents the Document Object Model(DOM). This is a lightweight in-memory tree representation of the original HTML DOM and is updated without affecting the original DOM.</li><li><strong>Components</strong>: Used to create reusable custom elements in VueJS applications.</li><li><strong>Templates</strong>: VueJS provides HTML-based templates that bind the DOM with the Vue instance data.</li><li><strong>Routing:</strong> Navigation between pages is achieved through vue-router</li><li><strong>Lightweight:</strong> VueJS is a lightweight library compared to other frameworks.</li></ol><h3>What are the lifecycle methods of VueJS?</h3><p>Through lifecycle methods, you can hook into a component so that you will know when your component is created, added to the DOM, updated, or destroyed.</p><p>These are the lifecycle methods with sequence</p><ul><li>beforeCreate</li><li>data</li><li>created</li><li>beforeMount</li><li>mounted</li><li>beforeUpdate</li><li>updated</li><li>activated</li><li>deactivated</li><li>beforeDestroy</li><li>destroyed</li><li>errorCaptured</li></ul><h3>The best practice of writing code sequence.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-F1QFw9Ez2QxR7AvEG1JFw.png" /></figure><h3>What are the conditional directives?</h3><ul><li>v-if</li><li>v-else-if</li><li>v-else</li><li>v-show</li></ul><h3><strong>How to create a new Vue instance?</strong></h3><ul><li>Vue 2</li></ul><pre>import Vue from &#39;vue&#39;;<br><br>new Vue({<br>  el: &#39;#root&#39;,<br>  router: new VueRouter({<br>    mode: &#39;history&#39;,<br>    routes: [<br>      {<br>        path: &#39;/&#39;,<br>        component: someComponent<br>      }<br>    ] <br>  })<br>  data: {},<br>  ...<br>})</pre><ul><li>Vue 3</li></ul><pre>import { createApp } from &#39;vue&#39;;<br>import { createRouter, createWebHistory } from &#39;vue-router&#39;;<br><br>const router = createRouter({<br>  history: createWebHistory(),<br>  routes: [<br>    {<br>      path: &#39;/&#39;,<br>      component: someComponent<br>    }<br>  ] <br>})<br><br>const app = createApp({<br>  data() {<br>    return {}<br>  },<br>  ...<br>})<br>app.use(router);<br><br>app.mount(&quot;#root&quot;)</pre><h3>What are the components and give an example?</h3><p>Components are reusable Vue instances with a name. They accept the same options as new Vue, such as data, computed, watch, methods, and lifecycle hooks(except a few root-specific options like el)</p><p><strong>e.g.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Apd2_vp5r1UMHhfI2dzY0A.png" /></figure><h3>Created Vs mounted</h3><p>created() : since the processing of the options is finished you have access to reactive data properties and change them if you want. At this stage, DOM has not been mounted or added yet. So you cannot do any DOM manipulation here.</p><p>mounted(): called after the DOM has been mounted or rendered. Here you have access to the DOM elements and DOM manipulation can be performed for example get the innerHTML:</p><pre>console.log(element.innerHTML)</pre><h3>Why key attributes?</h3><ul><li>To track each node’s identity and to make sure each element are independent and doesn’t impact each other.</li></ul><h3>Why should not use <em>if</em> and for directives together on the same element?</h3><p>It is recommended not to use v-if on the same element as v-for. Because <strong>v-for directive has a higher priority than v-if</strong>. There are two cases where developers try to use this combination,</p><ul><li><strong>To filter items in a list For example, if you try to filter the list using a v-if tag,</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lLHihU4PX2sWVP5O80_FQQ.png" /></figure><p>This can be avoided by preparing the filtered list using the computed property on the initial list</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BsNBPIQR-0gThjcHml8dvQ.png" /></figure><ul><li><strong>To avoid rendering a list if it should be hidden For example, if you try to conditionally check if the user is to be shown or hidden</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VMFQrHdc33rLfQH8-AMeJQ.png" /></figure><ul><li>This can be solved by moving the condition to a parent by avoiding this check for each user</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3Q7zRKM1b_B0hYTV6kmdSw.png" /></figure><h3>How do you use v-for directive with a range?</h3><p>You can also use integer type(say ’n’) for a v-for directive which repeats the element many times.</p><pre>&lt;div&gt;<br>  &lt;span v-for=&quot;n in 20&quot;&gt;{{ n }} &lt;/span&gt;<br>&lt;/div&gt;</pre><h3>What are the event modifiers provided by vue?</h3><p>Normally, javascript provides event.preventDefault() or event.stopPropagation() inside event handlers. You can use methods provided by vue, but these methods are meant for data logic instead of dealing with DOM events. Vue provides below event modifiers for v-on and these modifiers are directive postfixes denoted by a dot.</p><ol><li>.stop</li><li>.prevent</li><li>.capture</li><li>.self</li><li>.once</li><li>.passive</li></ol><h3>What are key modifiers?</h3><p>Vue supports key modifiers on v-on for handling keyboard events. Let&#39;s take an example of keyup event with enter keycode.</p><pre>&lt;!-- only call `vm.show()` when the `keyCode` is 13 --&gt;<br>&lt;input v-on:keyup.13=&quot;show&quot;&gt;</pre><p>Remembering all the key codes is really difficult. It supports the full list of key codes aliases</p><ol><li>.enter</li><li>.tab</li><li>.delete (captures both “Delete” and “Backspace” keys)</li><li>.esc</li><li>.space</li><li>.up</li><li>.down</li><li>.left</li><li>.right</li></ol><p><strong>e.g.</strong></p><pre>&lt;input v-on:keyup.enter=&quot;submit&quot;&gt;<br>// (OR)<br>&lt;!-- with shorthand notation--&gt;<br>&lt;input @keyup.enter=&quot;submit&quot;&gt;</pre><h3>What is the use of $parent and $root?</h3><p>In every subcomponent of a new Vue instance, this root instance can be accessed with the $root property.</p><p>Similar to $root, the $parent property can be used to access the parent instance from a child. This can be tempting to reach for as a lazy alternative to passing data with a prop.</p><p>Check out my example on <a href="https://jsfiddle.net/6gjb7r48/">JS Fiddle</a>.</p><h3>$refs</h3><p>Refs are Vue instance properties used to register or indicate a reference to HTML elements or child elements in the template of your application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*612rJDd5oyyYre416qsVHQ.png" /></figure><h3>What are the supported System Modifier Keys?</h3><p>Vue supports below modifiers to trigger mouse or keyboard event listeners when the corresponding key is pressed,</p><ol><li>.ctrl</li><li>.alt</li><li>.shift</li><li>.meta</li></ol><p><strong>e.g.</strong></p><pre>&lt;div @click.ctrl=&quot;doSomething&quot;&gt;Do something&lt;/div&gt;</pre><h3>What are the supported Mouse Button Modifiers?</h3><p>Vue supports below mouse button modifiers</p><ol><li>.left</li><li>.right</li><li>.middle</li></ol><p><strong>e.g.</strong></p><pre>&lt;button v-if=&quot;button === &#39;right&#39;&quot; v-on:mousedown.right=&quot;increment&quot; v-on:mousedown.left=&quot;decrement&quot; /&gt;</pre><h3>One-way data binding</h3><p>In one-way databinding, the value of the Model is used in the View (HTML page) but you can’t update Model from the View</p><h3>How do you implement two-way data binding?</h3><p>You can use the v-model directive to create two-way data bindings on form input, textarea, and select elements. Let&#39;s take an example of it using input component,</p><pre>&lt;input v-model=&quot;message&quot; placeholder=&quot;Enter input here&quot;&gt;<br>&lt;p&gt;The message is: {{ message }}&lt;/p&gt;</pre><h3>What are the supported modifiers on model?</h3><p>There are three modifiers supported for v-model directive.</p><ol><li><strong>lazy</strong>: By default, v-model syncs the input with the data after each input event. You can add the lazy modifier instead of sync after change events.</li></ol><pre>&lt;!-- synced after &quot;change&quot; instead of &quot;input&quot; --&gt;<br>&lt;input v-model.lazy=&quot;msg&quot; &gt;</pre><p>2. <strong>number</strong>:</p><pre>&lt;input v-model.number=&quot;age&quot; type=&quot;number&quot;&gt;</pre><p>3. <strong>trim</strong>: Removed whitespace from user input automatically</p><pre>&lt;input v-model.trim=&quot;msg&quot;&gt;</pre><h3>How do you implement model on custom input components?</h3><p>The custom events can also be used to create custom inputs that work with v-model. The inside the component must follow below rules,</p><ol><li>Bind the value attribute to a value prop</li><li>On input, emit its own custom input event with the new value. Let’s take a custom-input component as an example,</li></ol><p>Depending on the element, Vue decides how to listen and handle the data. For input elements, you might use v-model like this:</p><pre>&lt;input v-model=&quot;email&quot; /&gt;<br>// v-model translates to this:<br>&lt;input :value=&quot;email&quot; @input=&quot;e =&gt; email = e.target.value&quot; /&gt;</pre><p>Example:</p><pre>Vue.component(&#39;custom-input&#39;, {<br>  props: [&#39;value&#39;],<br>  template: `<br>    &lt;input<br>      v-bind:value=&quot;value&quot;<br>      v-on:input=&quot;$emit(&#39;input&#39;, $event.target.value)&quot;<br>    &gt;<br>  `<br>})<br><br>// Now you can use v-model with this component,<br><br>&lt;custom-input v-model=&quot;searchInput&quot;&gt;&lt;/custom-input&gt;</pre><p>Another Example</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R6pJVmIIiD6l-qefutrLYg.png" /></figure><p>Check <a href="https://www.digitalocean.com/community/tutorials/how-to-add-v-model-support-to-custom-vue-js-components">here</a> for more examples.</p><h3>What are the possible prop types?</h3><p>You can declare props with type or without type. But it is recommended to have prop types because it provides the documentation for the component and warns the developer for any incorrect data type being assigned.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PN6BdYDFjmodyK1JjuI4rg.png" /></figure><p>Define props without type:</p><pre>props: [‘name’, ‘age’,…],</pre><p><strong>Define props with type:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/974/1*PU19Sjz7xaY9s5NatpZK_g.png" /></figure><p><strong>Props with multiple types,</strong></p><pre>props: {<br>  identityNumber: [String, Number],<br>}<br>-OR-<br>props: {<br>  identityNumber: {<br>    type: [String, Number],<br>    default: 123<br>  }<br>}</pre><h3>Props Validation</h3><p>When designing a large-scale project, it’s easy to forget exactly the exact format, type, and other conventions you used for a prop.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dvJTjynzoGHflwUGsp4zPw.png" /></figure><h3>Watch property</h3><pre>watch: {<br>    // whenever question changes, this function will run<br>    question(newQuestion, oldQuestion) {<br>      if (newQuestion.includes(&#39;?&#39;)) {<br>        this.getAnswer()<br>      }<br>    }<br>  },</pre><h4>How to know if router param changed?</h4><pre>watch: {<br>  &#39;$route&#39; (to, from) {<br>    // react to route changes...<br>  }<br>}<br>-OR-<br>beforeRouteUpdate (to, from, next) {<br> // react to route changes and then call next()<br>}</pre><p>Checkout more on <a href="https://vuejs.org/guide/essentials/watchers.html">watch</a>.</p><h3>What are the filters?</h3><p>Filters can be used to apply common text formatting. These Filters should be appended to the end of the JavaScript expression, denoted by the “pipe” symbol. You can use them in two specific cases:</p><ol><li>mustache interpolations</li><li>v-bind expressions</li></ol><p>For example, Let’s define a local filter named capitalize in a component’s options</p><pre>filters: {<br>  capitalize: function (value) {<br>    if (!value) return &#39;&#39;<br>    value = value.toString()<br>    return value.charAt(0).toUpperCase() + value.slice(1)<br>  }<br>}</pre><p>Now you can use the filter in either mustache interpolation or v-bind expression,</p><pre>&lt;!-- in mustaches --&gt;<br>{{ username | capitalize }}<br>&lt;!-- in v-bind --&gt;<br>&lt;div v-bind:id=&quot;username | capitalize&quot;&gt;&lt;/div&gt;</pre><h3>How do you chain filters?</h3><p>You can chain filters one after the other to perform multiple manipulations on the expression. The generic structure of the filter chain would be as below,</p><pre>{{ message | filterA | filterB | filterB ... }}</pre><p>In the above chain stack, you can observe that message expression applied with three filters, each separated by a pipe(|) symbol. The first filter(filterA) takes the expression as a single argument and the result of the expression becomes an argument for the second filter(filterB) and the chain continues for remaining filters.</p><h3>How to pass parameters to filters?</h3><pre>{{ message | filterA(&#39;arg1&#39;, arg2) }}</pre><h3>What are mixins?</h3><p>Mixin gives us a way to distribute reusable functionalities in Vue components. These reusable functions are merged with existing functions. A mixin object can contain any component options. Let us take an example of mixin with created lifecycle which can be shared across components,</p><pre>const myMixin = {<br>  created(){<br>    console.log(&quot;Welcome to Mixins!&quot;)<br>  }<br>}<br>var app = new Vue({<br>  el: &#39;#root&#39;,<br>  mixins: [myMixin]<br>})</pre><h3>What is the purpose of keep-alive tag?</h3><p>Keep-alive tag is an abstract component used to preserve component state or avoid re-rendering.</p><pre>&lt;!-- Inactive components will be cached! --&gt;<br>&lt;keep-alive&gt;<br>  &lt;component v-bind:is=&quot;currentTabComponent&quot;&gt;&lt;/component&gt;<br>&lt;/keep-alive&gt;</pre><h3>What is the purpose of vuejs once directive?</h3><p>If you want to render a lot of static content then you need to make sure it only evaluated once and then cached thereafter. In this case, you can use v-once directive by wrapping at the root level. The example usage of v-once directive would be as below,</p><pre>Vue.component(&#39;legal-terms&#39;, {<br>  template: `<br>    &lt;div v-once&gt;<br>      &lt;h1&gt;Legal Terms&lt;/h1&gt;<br>      ... a lot of static content goes here...<br>    &lt;/div&gt;<br>  `<br>})</pre><h3>v-memo</h3><p>It will re-render the component only if the dependency array value is changed.</p><pre>&lt;p v-memo=&quot;[msg, count]&quot;&gt;<br>  {{ msg }} | {{ count }}<br>&lt;/p&gt;</pre><pre>// If you have empty dependency array means that is equivalent to v-once<br>&lt;p v-memo=&quot;[]&quot;&gt;<br>  Some static information<br>&lt;/p&gt;<br>// same aas above one<br>&lt;p v-once&gt;<br>  Some static information<br>&lt;/p&gt;</pre><h3>slot</h3><p>Example 1:</p><pre>// Parent component<br>&lt;submit-button&gt;<br>  Save<br>&lt;/submit-button&gt;<br><br>// Child component submit-button.vue<br>&lt;button type=&quot;submit&quot;&gt;<br>  &lt;slot&gt;&lt;/slot&gt;<br>&lt;/button&gt;</pre><p>Example 2:</p><pre>// Parent component<br>&lt;submit-button&gt;&lt;/submit-button&gt;<br><br>// Child component with default fallback submit-button.vue<br>&lt;button type=&quot;submit&quot;&gt;<br>  &lt;slot&gt;Submit&lt;/slot&gt;<br>&lt;/button&gt;</pre><p>Example 3: (named slot)</p><p>Parent:</p><pre>&lt;base-layout&gt;<br>  &lt;template v-slot:header&gt;<br>    &lt;h1&gt;Here might be a page title&lt;/h1&gt;<br>  &lt;/template&gt;<br><br>  &lt;p&gt;A paragraph for the main content.&lt;/p&gt;<br>  &lt;p&gt;And another one.&lt;/p&gt;<br><br>  &lt;template v-slot:footer&gt;<br>    &lt;p&gt;Here&#39;s some contact info&lt;/p&gt;<br>  &lt;/template&gt;<br>&lt;/base-layout&gt;</pre><p>Child(base-layout.vue)</p><pre>&lt;div class=&quot;container&quot;&gt;<br>  &lt;header&gt;<br>    &lt;slot name=&quot;header&quot;&gt;&lt;/slot&gt;<br>  &lt;/header&gt;<br>  &lt;main&gt;<br>    &lt;slot&gt;&lt;/slot&gt;<br>  &lt;/main&gt;<br>  &lt;footer&gt;<br>    &lt;slot name=&quot;footer&quot;&gt;&lt;/slot&gt;<br>  &lt;/footer&gt;<br>&lt;/div&gt;</pre><h3>What is scoped CSS?</h3><p>Scoped CSS is a mechanism in VueJS Single File Components(SFC) that prevents styles from leaking out of the current component and affecting other unintended components on your page. i.e, When a &lt;style&gt; tag has the scoped attribute, its CSS will apply to elements of the current component only. It uses PostCSS to transform scoped CSS to plain CSS. Let’s take an example usage of scoped CSS.</p><pre>&lt;style scoped&gt;<br>.greeting {<br>  color: green;<br>}<br>&lt;/style&gt;<br>&lt;template&gt;<br>  &lt;div class=&quot;greeting&quot;&gt;Let&#39;s start Scoped CSS&lt;/div&gt;<br>&lt;/template&gt;</pre><p>The above code will be converted to plain CSS,</p><pre>&lt;style scoped&gt;<br> .greeting[data-v-f3f3eg9] {<br>   color: green;<br> }<br> &lt;/style&gt;<br> &lt;template&gt;<br>   &lt;div class=&quot;greeting&quot; data-v-f3f3eg9&gt;Let&#39;s start Scoped CSS&lt;/div&gt;<br> &lt;/template&gt;</pre><h4>Are parent styles leaked into child components in scoped CSS?</h4><p>The parent component’s styles will not leak into child components. But a child component’s root node will be affected by both the parent’s scoped CSS and the child’s scoped CSS. i.e, your child component’s root element has a class that also exists in the parent component, the parent component’s styles will leak to the child.<br>The scoped CSS style doesn’t impact v-html directive’s dynamically generated content.</p><h3>CSS Module</h3><p>First, CSS Modules must be enabled by passing modules: true to css-loader:</p><pre>// webpack.config.js<br>{<br>  module: {<br>    rules: [<br>      // ... other rules omitted<br>      {<br>        test: /\.css$/,<br>        use: [<br>          &#39;vue-style-loader&#39;,<br>          {<br>            loader: &#39;css-loader&#39;,<br>            options: {<br>              // enable CSS Modules<br>              modules: true,<br>              // customize generated class names<br>              localIdentName: &#39;[local]_[hash:base64:8]&#39;<br>            }<br>          }<br>        ]<br>      }<br>    ]<br>  }<br>}</pre><p>In vue template:</p><pre>&lt;template&gt;<br>  &lt;p :class=&quot;$style.red&quot;&gt;<br>    This should be red<br>  &lt;/p&gt;<br>&lt;/template&gt;<br><br>&lt;style module&gt;<br>  .red {<br>    color: red;<br>  }<br>  .bold {<br>    font-weight: bold;<br>  }<br>&lt;/style&gt;</pre><p>Learn more about <a href="https://vue-loader.vuejs.org/guide/css-modules.html#usage">CSS module</a>.</p><h3>Router link</h3><p>&lt;router-link&gt; is the component for enabling user navigation in a router-enabled app. The target location is specified with the to prop. It renders as an &lt;a&gt; tag with correct href by default.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Asf8pTQFM0hUqldHWy3ctA.png" /></figure><h3>What is dynamic route matching?</h3><p>Sometimes it may be required to map routes to the same component based on a pattern. Let’s take a user component with the mapped URLs like /user/john/post/123 and /user/jack/post/235 using dynamic segments.</p><pre>const User = {<br>  template: &#39;&lt;div&gt;User {{ $route.params.name }}, PostId: {{ route.params.postid }}&lt;/div&gt;&#39;<br>}<br>const router = new VueRouter({<br>  routes: [<br>    // dynamic segments start with a colon<br>    { path: &#39;/user/:name/post/:postid&#39;, component: User }<br>  ]<br>})</pre><h3>What is <strong>Prop drilling?</strong></h3><p><strong>Prop drilling</strong> is the idea of passing <strong>props</strong> down and down and down to child components.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4FhIc_Z5HjzGUXgvBrlfJw.png" /></figure><p>There are multiple ways to avoid prop drilling.</p><ul><li>Provide and Inject</li><li>Event Bus controller</li><li>Vuex</li></ul><h3>Provide &amp; Inject</h3><p>To provide data to a component’s descendants, use the <a href="https://vuejs.org/api/options-composition#provide">provide</a> option and to inject data provided by an ancestor component, use the <a href="https://vuejs.org/api/options-composition#inject">inject</a> option.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IqQ-t-p35CsaJOJO.png" /></figure><h4>Syntax:</h4><pre>// parent<br>export default {<br>  provide: {<br>    message: &#39;hello!&#39;<br>  }<br>}<br><br><br>// nested child<br>export default {<br>  inject: [&#39;message&#39;],<br>  created() {<br>    console.log(this.message) // injected value<br>  }<br>}</pre><p>Check out <a href="https://vuejs.org/guide/components/provide-inject.html#app-level-provide">here</a> for more details.</p><h3>What is the event bus controller?</h3><p>By default, communication between Vue components happens with the use of props. Props are properties that are passed from a parent component to a child component. To get rid out of the prop drilling you can use <strong>EventBus</strong>.</p><p>Let’s understand this from an example:</p><p>JS:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4CzPUVO83QQ5DUcoqNeUog.png" /></figure><p>HTML template:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/1*SnC0bMgIbd_X5iM7EVe3wg.png" /></figure><p>Check out for more information <a href="https://css-tricks.com/using-event-bus-to-share-props-between-vue-components/">CSS Tricks</a>.<br>Another good example of <a href="https://medium.com/@andrejsabrickis/https-medium-com-andrejsabrickis-create-simple-eventbus-to-communicate-between-vue-js-components-cdc11cd59860">Event Bus</a>.</p><h3>Dynamic Component</h3><pre>&lt;component v-bind:is=&quot;currentTabComponent&quot;&gt;&lt;/component&gt;<br><br>// - or -<br><br>&lt;component :is=&quot;currentTabComponent&quot;&gt;&lt;/component&gt;</pre><h3>keep-alive with Dynamic Components</h3><p>When switching between these components though, you’ll sometimes want to maintain their state or avoid re-rendering for performance reasons.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TWcLJ-sFoNDvIK3-wPaZQw.png" /></figure><h3><strong>Send object data as props through v-bind</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p0JwtYrz1gxXzVZgEpgF5w.png" /></figure><h3>Set dynamic routing through addRoutes</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VwFV8EuOy2iV38Yak9Fabg.png" /></figure><h3>$on(‘hook:’)</h3><p>This is another nicety which I think is still is not documented yet. Often if you are using a third-party plugin or need to add a custom event listener, you first define it in created or mounted hook and then remove it in “beforeDestroy” hook. It is very important to clear out event listeners, so your code doesn’t cause memory leaks. Sometimes plugins might have a ‘destroy’ method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pdm2MOkAfhxde8-uVBqhbg.png" /></figure><p>With the use of $on(‘hook:) you can avoid a definition of another life-cycle hook.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tUBLlLjI4BefBCX2vrdwow.png" /></figure><blockquote>Vuex..</blockquote><h3>What is vuex?</h3><p>Vuex is a state management pattern + library (Flux-inspired Application Architecture) for Vue.js applications. It serves as a centralized store for all the components in an application, with rules ensuring that the state can only be mutated in a predictable fashion.</p><p>Let’s understand this through an example,</p><p>e.g.</p><p>To get language from the store and to update data on the store there are two ways</p><ul><li>First way</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yDBAA47OyJ0BsXpoWBAB6Q.png" /></figure><ul><li>Second way</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XS8ohL4n04OsugvGb1oU7Q.png" /></figure><p>Now let’s see how the sore will look like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lIAnz9kmhkD415BpMCjUKA.png" /></figure><h3>mapState Vs. mapGetters?</h3><p>Through mapState you can directly get the data from state, through mapGetters you can return some calculated state data.</p><p>e.g.</p><p>Vue javascript</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DGJ194wPdOqhnNWlNHF4jQ.png" /></figure><p>Html template</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rvoo5BYpBG10C7dCR6bfrw.png" /></figure><h3>mapAction Vs. mapMutation?</h3><p>To update the state synchronously we should always use mapMutation instead of mapAction. We do some calculations inside mapAction after that pass the value to the mapMutation to update the state.<br>Learn more about <a href="https://vuex.vuejs.org/guide/mutations.html">mutations</a> and <a href="https://vuex.vuejs.org/guide/actions.html">actions</a>.</p><h3>What is the Vuex module?</h3><p>Vuex allows us to divide our store into modules. Each module can contain its own state, mutations, actions, getters, and even nested modules.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WVKBAaS0qW3Ih8u-NEheTQ.png" /></figure><p>Check out <a href="https://codepen.io/kishankpatel/pen/MWaKpYZ?editors=1010">here</a> to learn through an example.</p><h3>Vue 3 new features</h3><ul><li>Composition API (Now built-in)</li><li>Multiple root elements (Template syntax )</li><li>Suspense</li><li>Multiple V-models</li><li>Better reactivity</li><li>Portals (teleport)</li></ul><h4>Teleport</h4><p>&lt;Teleport&gt; is a built-in component that allows us to &quot;teleport&quot; a part of a component&#39;s template into a DOM node that exists outside the DOM hierarchy of that component.</p><pre>&lt;button @click=&quot;open = true&quot;&gt;Open Modal&lt;/button&gt;<br><br>&lt;Teleport to=&quot;body&quot;&gt;<br>  &lt;div v-if=&quot;open&quot; class=&quot;modal&quot;&gt;<br>    &lt;p&gt;Hello from the modal!&lt;/p&gt;<br>    &lt;button @click=&quot;open = false&quot;&gt;Close&lt;/button&gt;<br>  &lt;/div&gt;<br>&lt;/Teleport&gt;</pre><h4>Suspense</h4><p>&lt;Suspense&gt; is a built-in component for orchestrating async dependencies in a component tree. It can render a loading state while waiting for multiple nested async dependencies down the component tree to be resolved.</p><pre>&lt;Suspense&gt;<br>  &lt;!-- component with nested async dependencies --&gt;<br>  &lt;Dashboard /&gt;<br><br>  &lt;!-- loading state via #fallback slot --&gt;<br>  &lt;template #fallback&gt;<br>    Loading...<br>  &lt;/template&gt;<br>&lt;/Suspense&gt;</pre><blockquote>Unit test…</blockquote><h3>Mount vs shallowMount</h3><p><strong>Mount</strong> will render the current component with all children and also child of each children presents in the component. The entire rendered tree can get really big. Repeatedly rendering all child components could slow down our tests, to get rid out of this problem we can use shallowMount.<br><strong>shallowMount</strong> will render only current component.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AhO1B85f8vpHQ8M4TGfrJQ.png" /></figure><h3>Optimise page load performance</h3><ul><li><strong>Check memory leak </strong>: Memory leaks can lead to increased memory usage over time, causing degraded performance and potentially crashes. <strong>Remove event listeners</strong> on <em>beforeDestroy</em>.</li><li>Minimize Render and Update Cycles by using <strong>v-once</strong> for static sections and use <strong>v-memo</strong> if required.</li><li><strong>Use Computed Properties and Memoization</strong>: Computed properties can cache results and only recompute when their dependencies change. Utilize them to avoid redundant computations.</li><li><strong>Lazy Loading and Code Splitting</strong>: Split your application into smaller chunks and load them on demand. This technique can improve initial load times by only loading the necessary components when they are needed.</li><li><strong>Asynchronous Components:</strong> Use Vue’s built-in support for asynchronous components to load components in parallel and avoid blocking the main thread. This is particularly useful for heavy components that take longer to render.</li><li>Consider <strong>virtual scrolling</strong> or <strong>pagination</strong> for large lists.</li><li><strong>Use Webpack Bundle Analyzer:</strong> Analyze your bundle size using tools like Webpack Bundle Analyzer to identify large dependencies or unnecessary code. Eliminate unused dependencies and consider code splitting to reduce bundle size.</li><li>Use <strong>low-resolution images</strong> on the listing page.</li><li>Choosing the <strong>Right Architecture .</strong></li><li>Also, check with the API side as well if it’s taking longer.</li></ul><h3>List out top 10 organizations using Vuejs?</h3><p>Below are the top 10 organizations using VueJS for their applications or products,</p><ol><li>Facebook — Used on marketing side of its Newsfeed</li><li>Netflix — Used in two internal apps for building movie streaming interfaces</li><li>Adobe — Used for Portfolio, a custom website builder designed to help users showcase their creative work</li><li>Xiaomi — Used for products where it sells from consumer electronics to software</li><li>Alibaba — Provide their apps an excellent experience to its customers</li><li>WizzAir — A budget airline WizzAir used for their customers user interface</li><li>EuroNews</li><li>Laracasts</li><li>GitLab</li><li>Laracasts</li></ol><p>Check out my article on <a href="https://medium.com/@kishanptl.kp/javascript-faqs-eb2e828a0593">Javascript FAQs</a>.</p><p>References:</p><p><a href="https://github.com/kishankpatel/vuejs-interview-questions">https://github.com/kishankpatel/vuejs-interview-questions</a></p><p>Thank you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ddf744dd4093" width="1" height="1" alt=""><hr><p><a href="https://blog.francium.tech/vue-js-faqs-ddf744dd4093">Vue JS FAQs</a> was originally published in <a href="https://blog.francium.tech/">Francium Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>