<?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"><channel><title><![CDATA[Prateek Gogia - Javascript Developer - React.js, Node.js, GraphQL]]></title><description><![CDATA[Hey World! I am Prateek Gogia based in Bangalore, India working as a frontend engineer. I hold expertise in web development with technologies like React.js, Node.js, GraphQL, and Javascript.]]></description><link>https://blog.reeversedev.com</link><generator>RSS for Node</generator><lastBuildDate>Thu, 21 May 2026 17:30:46 GMT</lastBuildDate><atom:link href="https://blog.reeversedev.com/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Enumeration in JavaScript]]></title><description><![CDATA[Enumerable in Javascript is basically an ability of a particular property of an object to exist and visible at the same time. Very subtle, what does that it even? Let's dive a bit more.
While I was going through the official spec of EcmaScript to und...]]></description><link>https://blog.reeversedev.com/enumeration-in-javascript</link><guid isPermaLink="true">https://blog.reeversedev.com/enumeration-in-javascript</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Objects]]></category><category><![CDATA[vanilla-js]]></category><dc:creator><![CDATA[Prateek Gogia]]></dc:creator><pubDate>Tue, 18 May 2021 16:03:18 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1621353540553/uMFHN2fYa.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Enumerable in Javascript is basically an ability of a particular property of an object to exist and visible at the same time. Very subtle, what does that it even? Let's dive a bit more.</p>
<p>While I was going through the official spec of <strong>EcmaScript</strong> to understand how the <strong>Polyfills</strong> should be written and have been written so far according to standards, I came across this word called, 'Enumerable' many times and I would be lying if I say that I understood everything in the first glance. This word itself was so confusing for me, so I did some more research about this and will share my findings, understanding so far that further made me understand other concepts better.</p>
<h2 id="objects-in-javascript">Objects in JavaScript</h2>
<p>JavaScript is full of objects and every object has a key-value pair otherwise it's just an empty object. I'll be using the below-mentioned code snippet throughout the article to discuss.</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">var</span> obj = {
    <span class="hljs-attr">first_name</span>: <span class="hljs-string">'Prateek'</span>,
    <span class="hljs-attr">last_name</span>: <span class="hljs-string">'Gogia'</span>,
    <span class="hljs-attr">profession</span>: <span class="hljs-string">'Code Gambler'</span>,
    <span class="hljs-attr">age</span>: <span class="hljs-number">25</span>,
    <span class="hljs-attr">location</span>: <span class="hljs-string">'Internet'</span>,
    <span class="hljs-attr">known_as</span>: <span class="hljs-string">'reeversedev'</span>,
    <span class="hljs-attr">prints_name</span>: <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"My name is: "</span> + <span class="hljs-built_in">this</span>.first_name + <span class="hljs-string">" "</span> + <span class="hljs-built_in">this</span>.last_name)
    }
};
</code></pre>
<p>There are various methods associated with objects. For example, <strong>Object.keys(obj)</strong> and <strong>Object.values(obj)</strong> will return array of keys and values by iterating over every key and value. The below snippet explains what will be returned while we use these methods.</p>
<pre><code class="lang-jsx"><span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">Object</span>.keys(obj)); <span class="hljs-comment">// ["first_name", "last_name", "profession", "age", "location", "known_as", "prints_name"]</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">Object</span>.values(obj)); <span class="hljs-comment">// ["Prateek", "Gogia", "Code Gambler", 25, "Internet", "reeversedev", ƒ]</span>
</code></pre>
<p>Every object in JavaScript has three attributes for its properties, writability, enumerability, and configurability. We are going to talk about Enumerability here.</p>
<h2 id="what-the-heck-is-enumerability">What the heck is Enumerability?</h2>
<p>In simple words, Enumerability allows your object to have properties to exist in the object but it provides a provision to be and not be a part of the iteration. 
Let's say my object has to be used by some other library that provides the functionality of printing name just like my object but with extra features, at the same time, I don't want the other developer whoever is using my object to change the <strong>prints_name()</strong> function to change. 
Any idea how can we do that? Yes, Enumeration is the answer. Let's see how we can do this for our object.</p>
<pre><code class="lang-jsx"><span class="hljs-built_in">Object</span>.defineProperty(obj, <span class="hljs-string">'prints_name'</span>, {
    <span class="hljs-attr">value</span>: <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"My name is: "</span> + <span class="hljs-built_in">this</span>.first_name + <span class="hljs-string">" "</span> + <span class="hljs-built_in">this</span>.last_name)
    },
    <span class="hljs-attr">enumerable</span>: <span class="hljs-literal">false</span>
});

<span class="hljs-comment">// Notice that, prints_name is not printed in console.</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">Object</span>.keys(obj)); <span class="hljs-comment">// ["first_name", "last_name", "profession", "age", "location", "known_as"]</span>

<span class="hljs-comment">// But you can still access the proper</span>
<span class="hljs-built_in">console</span>.log(obj.prints_name()); <span class="hljs-comment">// My name is: Prateek Gogia</span>
</code></pre>
<p>By default, the inbuilt properties of Objects are non-enumerable i.e., they won't be a part of the iteration, this becomes very important while you are dealing with bigger objects that include information and some methods/factory functions because while iterating, you all need access to information and not the utilities.</p>
<p>Utility functions of Array-like <strong>.pop()</strong> and <strong>.push()</strong>  are non-enumerable and therefore you can access these properties but when you will console the whole array they won't be visible. To understand better, let's take a look at the example below.</p>
<pre><code class="lang-jsx"><span class="hljs-comment">// declaring the array</span>
<span class="hljs-keyword">var</span> arr = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>];

<span class="hljs-comment">// expected behaviour</span>
<span class="hljs-built_in">console</span>.log(arr); <span class="hljs-comment">// [1, 2, 3]</span>

<span class="hljs-comment">// Notice that JS won't throw an error when you use array as an Object, thanks to protype chain in JS</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">Object</span>.keys(arr)); <span class="hljs-comment">// ["0", "1", "2"]</span>

<span class="hljs-built_in">console</span>.log(arr.hasOwnProperty(<span class="hljs-string">'push'</span>)) <span class="hljs-comment">// false</span>
</code></pre>
<p>In the above example, notice that when we check for our declared array, i.e., arr has a property such as 'push' or not, it return false. But you can still write <code>arr.push(4)</code> and it will work. This means, that the utility function of the Array class has push and pop but they are non-enumerable and will not appear in iteration.</p>
<h2 id="when-do-we-need-enumeration-though">When do we need Enumeration though?</h2>
<p>Usually, enumeration is being used when a developer tries to write polyfills of some functionality that doesn't work in incompatible browsers. As a result, he/she will try to modify the prototype object that makes the property enumerable and hence makes it risky because it will be returned in the iteration process.</p>
<p>So, instead of writing </p>
<pre><code><span class="hljs-keyword">Object</span>.prototype.prints_name = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    alert(<span class="hljs-string">"The name is bond, James Bond"</span>);
};
</code></pre><p>Using, <code>Object.defineProperty</code> by defining <code>enumerable</code> as <code>false</code> makes more sense.</p>
<pre><code><span class="hljs-keyword">Object</span>.defineProperty(<span class="hljs-keyword">Object</span>.prototype, <span class="hljs-string">'prints_name'</span>, {
    value: <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
        alert(<span class="hljs-string">"The name is bond, James Bond"</span>);
    },
    enumerable: <span class="hljs-literal">false</span>
});
</code></pre>]]></content:encoded></item><item><title><![CDATA[useReducer() hook: Demystifying the basics]]></title><description><![CDATA[If you have used hooks before in React, then you must have done local state management using useState(). While it works completely fine for basic state manipulation, it does get tricky after multiple states are involved. 
Here's a Problem
For instanc...]]></description><link>https://blog.reeversedev.com/usereducer-hook-demystifying-the-basics</link><guid isPermaLink="true">https://blog.reeversedev.com/usereducer-hook-demystifying-the-basics</guid><category><![CDATA[React]]></category><category><![CDATA[hooks]]></category><category><![CDATA[TypeScript]]></category><dc:creator><![CDATA[Prateek Gogia]]></dc:creator><pubDate>Mon, 20 Jul 2020 23:48:24 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1593951080670/4dD3WeCX8.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>If you have used hooks before in React, then you must have done local state management using <code>useState()</code>. While it works completely fine for basic state manipulation, it does get tricky after multiple states are involved. </p>
<h2 id="here-s-a-problem">Here&#39;s a Problem</h2>
<p>For instance, let&#39;s take an example of managing a state of a person.</p>
<pre><code><span class="hljs-keyword">const</span> [name, setName] = useState(<span class="hljs-string">''</span>)
<span class="hljs-keyword">const</span> [age, setAge] = useState(<span class="hljs-string">''</span>)
<span class="hljs-keyword">const</span> [gender, setGender] = useState(<span class="hljs-string">''</span>)
<span class="hljs-keyword">const</span> [profession, setProfession] = useState(<span class="hljs-string">''</span>)
</code></pre><p>In the above code, there are <strong>4</strong> different handlers for setting different instances of the local state. What if there are more than <strong>20</strong> instances of state and what if we have multiple nested instances like address fields? Have a look at this example.</p>
<pre><code><span class="hljs-keyword">const</span> [name, setName] = useState(<span class="hljs-string">''</span>)
<span class="hljs-keyword">const</span> [age, setAge] = useState(<span class="hljs-string">''</span>)
<span class="hljs-keyword">const</span> [gender, setGender] = useState(<span class="hljs-string">''</span>)
<span class="hljs-keyword">const</span> [profession, setProfession] = useState(<span class="hljs-string">''</span>)
<span class="hljs-keyword">const</span> [address, setAddress] = useState({apartment: <span class="hljs-string">''</span>, lines: {line1: <span class="hljs-string">''</span>, line2:<span class="hljs-string">''</span>}})
</code></pre><p>That will make things cumbersome for us to handle. </p>
<h2 id="introducing-usereducer-">Introducing useReducer()</h2>
<p><strong>useReducer()</strong> is a React Hook that is specifically being used to handle complex state changes. It takes three arguments, <strong>reducer</strong>, <strong>initalState</strong> and <strong>intialFunction</strong>. It returns 
two entities, <strong>state</strong> and <strong>dispatch</strong>.</p>
<pre><code><span class="hljs-keyword">const</span> [state, dispatch] = useReducer(reducer, intialState, initialFunction)
</code></pre><h2 id="brief-overview-of-things-involved-in-usereducer-">Brief overview of things involved in useReducer()</h2>
<p><strong>reducer</strong>: A reducer is a <strong>pure function</strong> that takes two arguments, <strong>previous state</strong>, and <strong>action</strong>, and returns the <strong>next state</strong>. <em>In more simple words</em>, the reducer takes action and a state and returns a new version of that state.</p>
<pre><code>(previousState, action) =&gt; newState
</code></pre><p><strong>intialState</strong>: An initial state is a state that you want to use across that component. Preferably, for a complex structure, an ideal choice would be to use a JSON object but it&#39;s not a mandatory condition, you can use any datatype for initial state.</p>
<pre><code><span class="hljs-keyword">const</span> initialState = {
    name: <span class="hljs-string">""</span>,
    age: <span class="hljs-string">""</span>,
    gender: <span class="hljs-string">""</span>,
    profession:<span class="hljs-string">""</span>
    address: {
      apartment: <span class="hljs-string">""</span>,
      line1: <span class="hljs-string">""</span>,
      line2: <span class="hljs-string">""</span>
    }
}
</code></pre><p><strong>initialFunction</strong>: The initial function is used to load the initial state lazily which also means resetting the state to its initial value.</p>
<pre><code><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">init</span>(<span class="hljs-params">initialState</span>) </span>{
  <span class="hljs-keyword">return</span> initialState;
}
</code></pre><h2 id="let-s-build-something">Let&#39;s build something</h2>
<p>Learning a programming concept is incomplete without actually building a <strong>to-do app</strong>. (Pun intended). The final Application will look like this.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1595110329813/XweI7Frr4.png" alt="Screenshot 2020-07-19 at 3.41.43 AM.png"></p>
<p>In this application, we have mainly 5 main components, <strong>heading</strong>, <strong>button</strong>, <strong>input</strong>, <strong>ordered list</strong> and <strong>form</strong> so let&#39;s code a basic react component layout quickly.</p>
<blockquote>
<p>I won&#39;t be explaining the CSS code since this post is particularly aimed to understand the hooks and not the design and it&#39;s a very basic CSS anyway.</p>
</blockquote>
<p><strong>styles.css</strong></p>
<pre><code>@<span class="hljs-keyword">import</span> url(<span class="hljs-string">'https://fonts.googleapis.com/css2?family=Nunito:wght@300;400;700&amp;display=swap'</span>);

<span class="hljs-selector-tag">body</span> {
  <span class="hljs-attribute">font-family</span>: <span class="hljs-string">'Nunito'</span>, sans-serif;
  <span class="hljs-attribute">background</span>: <span class="hljs-built_in">rgb</span>(<span class="hljs-number">8</span>, <span class="hljs-number">38</span>, <span class="hljs-number">53</span>);
}

<span class="hljs-selector-tag">form</span> {
  <span class="hljs-attribute">display</span>: flex;
  <span class="hljs-attribute">justify-content</span>: space-between;
  <span class="hljs-attribute">align-items</span>: center;
}

<span class="hljs-selector-tag">input</span><span class="hljs-selector-attr">[type='text']</span> {
  <span class="hljs-attribute">outline</span>: none;
  <span class="hljs-attribute">border</span>: <span class="hljs-number">0</span>;
  <span class="hljs-attribute">border-radius</span>: <span class="hljs-number">25px</span>;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">10px</span> <span class="hljs-number">20px</span>;
  <span class="hljs-attribute">width</span>: <span class="hljs-number">350px</span>;
}

<span class="hljs-selector-tag">button</span> {
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">10px</span>;
  <span class="hljs-attribute">background</span>: blue;
  <span class="hljs-attribute">color</span>: white;
  <span class="hljs-attribute">border</span>: <span class="hljs-number">2px</span> solid blue;
  <span class="hljs-attribute">cursor</span>: pointer;
  <span class="hljs-attribute">border-radius</span>: <span class="hljs-number">5px</span>;
}

<span class="hljs-selector-class">.app</span> {
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">0px</span> <span class="hljs-number">20px</span>;
}

<span class="hljs-selector-tag">h1</span> {
  <span class="hljs-attribute">color</span>: white;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">5px</span> <span class="hljs-number">10px</span>;
}

<span class="hljs-selector-class">.number</span> {
  <span class="hljs-attribute">display</span>: flex;
  <span class="hljs-attribute">justify-content</span>: space-between;
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">20px</span> <span class="hljs-number">0</span>;
  <span class="hljs-attribute">font-size</span>: <span class="hljs-number">20px</span>;
  <span class="hljs-attribute">color</span>: white;
}

<span class="hljs-selector-class">.list</span> {
  <span class="hljs-attribute">background</span>: <span class="hljs-built_in">rgb</span>(<span class="hljs-number">245</span>, <span class="hljs-number">235</span>, <span class="hljs-number">98</span>);
  <span class="hljs-attribute">border-radius</span>: <span class="hljs-number">10px</span>;
  <span class="hljs-attribute">height</span>: <span class="hljs-number">310px</span>;
  <span class="hljs-attribute">overflow</span>: auto;
  <span class="hljs-attribute">color</span>: brown;
}

<span class="hljs-selector-tag">ol</span> <span class="hljs-selector-tag">li</span> {
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">20px</span> <span class="hljs-number">0px</span>;
}

<span class="hljs-selector-class">.banner</span> {
  <span class="hljs-attribute">overflow</span>: auto;
  <span class="hljs-attribute">display</span>: flex;
  <span class="hljs-attribute">justify-content</span>: center;
  <span class="hljs-attribute">align-items</span>: center;
}
</code></pre><p><strong>App.tsx</strong></p>
<pre><code>
import * as React from 'react';
import './styles.css';

const App = () =&gt; {
  const [itemName, setItemName] = React.useState('');
  const onSubmit = (e: React.FormEvent) =&gt; {
    e.preventDefault();
    setItemName('');
  };
  return (
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"app"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Todo List<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">onSubmit</span>=<span class="hljs-string">{onSubmit}</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">input</span>
          <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span>
          <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Add a item name"</span>
          <span class="hljs-attr">value</span>=<span class="hljs-string">{itemName}</span>
          <span class="hljs-attr">onChange</span>=<span class="hljs-string">{(e)</span> =&gt;</span> setItemName(e.target.value)}
        /&gt;
        <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span>&gt;</span>Add item<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>

      <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"number"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">button</span>&gt;</span>
          Reset
        <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
        Total Todos:
      <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>

      <span class="hljs-tag">&lt;<span class="hljs-name">ol</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"list"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">ol</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
  );
};

export default App;
</code></pre><p>If you are familiar with hooks, then the above code is quite easy to understand. I am making use of the <strong>useState</strong> hook to capture the value of input field and name that state as itemName.</p>
<p>Let&#39;s add some more complexity to this application and try to do the basic operations like <em>adding a new todo item</em> and marking those items as either <em>complete</em> or <em>incomplete</em>. Since this will involve multiple states and their handlers, so good it&#39;s a time for adding <strong>useReducer</strong> hook.</p>
<pre><code> <span class="hljs-keyword">const</span> [{ todos, totalTodos }, dispatch] = React.useReducer(
    reducer,
    intialState,
    <span class="hljs-keyword">init</span>
  );
</code></pre><p>Let&#39;s write the <strong>reducer</strong>, <strong>initialState</strong> and <strong>init</strong> function and then try to understand what these entities really convey. But before even writing all these entities, let&#39;s first write the type definitions so that we can structure our application data well.</p>
<p><strong>Type Definitions</strong></p>
<pre><code><span class="hljs-keyword">type</span> TodoType = {
  idx?: <span class="hljs-built_in">number</span>;
  text?: <span class="hljs-built_in">string</span>;
  completed?: <span class="hljs-built_in">boolean</span>;
};

<span class="hljs-keyword">type</span> StateType = {
  todos: <span class="hljs-built_in">Array</span>&lt;<span class="hljs-built_in">any</span>&gt;;
  totalTodos: <span class="hljs-built_in">number</span>;
};

<span class="hljs-keyword">type</span> ActionType = {
  <span class="hljs-keyword">type</span>: <span class="hljs-built_in">string</span>;
  payload: <span class="hljs-built_in">any</span>;
};
</code></pre><p><strong>Action Types</strong></p>
<pre><code><span class="hljs-keyword">const</span> AddTodo = <span class="hljs-string">'add-todo'</span>;
<span class="hljs-keyword">const</span> MarkCompleted = <span class="hljs-string">'mark-completed'</span>;
<span class="hljs-keyword">const</span> MarkIncompleted = <span class="hljs-string">'mark-incompleted'</span>;
<span class="hljs-keyword">const</span> Reset = <span class="hljs-string">'reset'</span>;
</code></pre><p><strong>Initial State and Init function</strong></p>
<pre><code><span class="hljs-keyword">const</span> intialState = {
  todos: [],
  totalTodos: <span class="hljs-number">0</span>,
};

<span class="hljs-keyword">const</span> init = <span class="hljs-function">(<span class="hljs-params">initialState: StateType</span>) =&gt;</span> initialState;
</code></pre><p><strong>Reducer</strong></p>
<pre><code><span class="hljs-keyword">const</span> reducer = (state: StateType, action: ActionType): <span class="hljs-function"><span class="hljs-params">StateType</span> =&gt;</span> {
  <span class="hljs-keyword">const</span> { payload } = action;
  <span class="hljs-keyword">switch</span> (action.type) {
    <span class="hljs-keyword">case</span> AddTodo:
      <span class="hljs-keyword">return</span> {
        todos: [...state.todos, { text: payload.text, completed: <span class="hljs-literal">false</span> }],
        totalTodos: state.totalTodos + <span class="hljs-number">1</span>,
      };
    <span class="hljs-keyword">case</span> MarkCompleted:
      <span class="hljs-keyword">return</span> {
        todos: state.todos.map(<span class="hljs-function">(<span class="hljs-params">todo, idx</span>) =&gt;</span> {
          <span class="hljs-keyword">return</span> idx === payload.idx ? { ...todo, completed: <span class="hljs-literal">true</span> } : todo;
        }),
        totalTodos:
          [...state.todos.filter(<span class="hljs-function">(<span class="hljs-params">todo</span>) =&gt;</span> !todo.completed)].length - <span class="hljs-number">1</span>,
      };
    <span class="hljs-keyword">case</span> MarkIncompleted:
      <span class="hljs-keyword">return</span> {
        todos: state.todos.map(<span class="hljs-function">(<span class="hljs-params">todo, idx</span>) =&gt;</span> {
          <span class="hljs-keyword">return</span> idx === payload.idx ? { ...todo, completed: <span class="hljs-literal">false</span> } : todo;
        }),
        totalTodos:
          [...state.todos.filter(<span class="hljs-function">(<span class="hljs-params">todo</span>) =&gt;</span> !todo.completed)].length + <span class="hljs-number">1</span>,
      };
    <span class="hljs-keyword">case</span> Reset:
      <span class="hljs-keyword">return</span> init(action.payload);

    <span class="hljs-keyword">default</span>:
      <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">'Not compatible action'</span>);
  }
};
</code></pre><p>As we know, a reducer function accepts state and action and returns a new version of state.
Our application has 4 different scenarios that affects our state which I am handling using switch case inside reducer. </p>
<ol>
<li><strong>AddToDo</strong>: In this case, I am simply adding a new item inside <strong>todos array</strong> of state and iterating the <strong>totalTodos</strong> inside state.</li>
<li><strong>MarkCompleted</strong>: This a bit tricky because this involves the update operation of marking an item as done, basically making the boolean value of <strong>completed</strong> inside todo state as <strong>true</strong>. Also, need to calculate the totalTodos pending here so need to filter the whole todos array where the <strong>completed</strong> value is <strong>false</strong> which states that the number of pending items.</li>
<li><strong>MarkIncompleted</strong>: It&#39;s similar to <em>MarkCompleted</em> operation except that instead marking the value as true we are marking it as true. This comes handy when you wanna do an undo operation after marking the item as done.</li>
<li><strong>Reset</strong>: Reset/Clear the items operation come handy when you want to either delete everything or basically go to your app&#39;s initial state.</li>
</ol>
<p>Putting all these together and we have..</p>
<pre><code>import * <span class="hljs-keyword">as</span> React from <span class="hljs-string">'react'</span>;
import <span class="hljs-string">'./styles.css'</span>;

<span class="hljs-comment">// type definitions</span>
type TodoType = {
  idx?: number;
  text?: string;
  completed?: boolean;
};

type StateType = {
  todos: <span class="hljs-keyword">Array</span>&lt;any&gt;;
  totalTodos: number;
};

type ActionType = {
  type: string;
  payload: any;
};

<span class="hljs-comment">// action types</span>
<span class="hljs-keyword">const</span> AddTodo = <span class="hljs-string">'add-todo'</span>;
<span class="hljs-keyword">const</span> MarkCompleted = <span class="hljs-string">'mark-completed'</span>;
<span class="hljs-keyword">const</span> MarkIncompleted = <span class="hljs-string">'mark-incompleted'</span>;
<span class="hljs-keyword">const</span> Reset = <span class="hljs-string">'reset'</span>;

<span class="hljs-comment">// reducer</span>
<span class="hljs-keyword">const</span> reducer = (state: StateType, action: ActionType): StateType =&gt; {
  <span class="hljs-keyword">const</span> { payload } = action;
  <span class="hljs-keyword">switch</span> (action.type) {
    <span class="hljs-keyword">case</span> AddTodo:
      <span class="hljs-keyword">return</span> {
        todos: [...state.todos, { text: payload.text, completed: <span class="hljs-keyword">false</span> }],
        totalTodos: state.totalTodos + <span class="hljs-number">1</span>,
      };
    <span class="hljs-keyword">case</span> MarkCompleted:
      <span class="hljs-keyword">return</span> {
        todos: state.todos.map((todo, idx) =&gt; {
          <span class="hljs-keyword">return</span> idx === payload.idx ? { ...todo, completed: <span class="hljs-keyword">true</span> } : todo;
        }),
        totalTodos:
          [...state.todos.filter((todo) =&gt; !todo.completed)].length - <span class="hljs-number">1</span>,
      };
    <span class="hljs-keyword">case</span> MarkIncompleted:
      <span class="hljs-keyword">return</span> {
        todos: state.todos.map((todo, idx) =&gt; {
          <span class="hljs-keyword">return</span> idx === payload.idx ? { ...todo, completed: <span class="hljs-keyword">false</span> } : todo;
        }),
        totalTodos:
          [...state.todos.filter((todo) =&gt; !todo.completed)].length + <span class="hljs-number">1</span>,
      };
    <span class="hljs-keyword">case</span> Reset:
      <span class="hljs-keyword">return</span> init(action.payload);

    <span class="hljs-keyword">default</span>:
      <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> Error(<span class="hljs-string">'Not compatible action'</span>);
  }
};

<span class="hljs-comment">// initial state</span>
<span class="hljs-keyword">const</span> intialState = {
  todos: [],
  totalTodos: <span class="hljs-number">0</span>,
};

<span class="hljs-comment">// init function</span>
<span class="hljs-keyword">const</span> init = (initialState: StateType) =&gt; initialState;

<span class="hljs-keyword">const</span> App = () =&gt; {
  <span class="hljs-keyword">const</span> [{ todos, totalTodos }, dispatch] = React.useReducer(
    reducer,
    intialState,
    init
  );
  <span class="hljs-keyword">const</span> [itemName, setItemName] = React.useState(<span class="hljs-string">''</span>);
  <span class="hljs-keyword">const</span> onSubmit = (e: React.FormEvent) =&gt; {
    e.preventDefault();
    dispatch({
      type: AddTodo,
      payload: {
        text: itemName,
      },
    });
    setItemName(<span class="hljs-string">''</span>);
  };
  <span class="hljs-keyword">return</span> (
    &lt;div className=<span class="hljs-string">"app"</span>&gt;
      &lt;h1&gt;Todo <span class="hljs-keyword">List</span>&lt;/h1&gt;
      &lt;form onSubmit={onSubmit}&gt;
        &lt;input
          type=<span class="hljs-string">"text"</span>
          placeholder=<span class="hljs-string">"Add a item name"</span>
          value={itemName}
          onChange={(e) =&gt; setItemName(e.target.value)}
        /&gt;
        &lt;button type=<span class="hljs-string">"submit"</span>&gt;Add item&lt;/button&gt;
      &lt;/form&gt;

      &lt;div className=<span class="hljs-string">"number"</span>&gt;
        &lt;button onClick={() =&gt; dispatch({ type: Reset, payload: intialState })}&gt;
          Reset
        &lt;/button&gt;
        Total Todos: {totalTodos}
      &lt;/div&gt;

      &lt;ol className=<span class="hljs-string">"list"</span>&gt;
        {todos.map((todo, idx) =&gt; {
          <span class="hljs-keyword">return</span> (
            &lt;li
              key={idx}
              style={{
                textDecoration: todo.completed ? <span class="hljs-string">'line-through'</span> : <span class="hljs-string">'none'</span>,
              }}
              onClick={() =&gt;
                todo.completed
                  ? dispatch({
                      type: MarkIncompleted,
                      payload: { ...todo, idx: idx },
                    })
                  : dispatch({
                      type: MarkCompleted,
                      payload: { ...todo, idx: idx },
                    })
              }
            &gt;
              {todo.text}
            &lt;/li&gt;
          );
        })}
      &lt;/ol&gt;
    &lt;/div&gt;
  );
};

export <span class="hljs-keyword">default</span> App;
</code></pre><p>In order to make our button even handlers work, we can&#39;t just go ahead and simply call the function in this scenario where we are using the <strong>useReducer() hook</strong>. If you are familiar with  <a target='_blank' rel='noopener noreferrer'  href="https://facebook.github.io/flux/docs/in-depth-overview">Flux</a>  pattern, then you must know that we have to dispatch an action that further involves a type and a payload, and based on certain scenarios, our reducer returns the next state. Hence, to make our buttons work properly, I am dispatching the actions which involve the type and the payload and our reducer takes care of these actions and returns us the new version of the state.</p>
<p><strong>Codesandbox</strong></p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" data-card-width="600px" data-card-key="2e4d628b39a64b99917c73956a16b477" href="https://codesandbox.io/embed/usereducer-typescript-uj7vc?fontsize=14&hidenavigation=1&theme=dark" data-card-controls="0" data-card-theme="light">https://codesandbox.io/embed/usereducer-typescript-uj7vc?fontsize=14&hidenavigation=1&theme=dark</a></div>
<blockquote>
<p>useState() hook can be implemented using useReducer() because inside React, they both share the common code.</p>
</blockquote>
<h2 id="when-to-use-usereducer-and-usestate-">When to use useReducer and useState()?</h2>
<p>This itself is a long topic to understand but in short if you wanna have some ground rules for application (which I highly recommend because those will make your life easier), then here they are: </p>
<ol>
<li><p>If only 1 instance of state is involved, then definitely go with useState() hook. <em>Why make things complicated anyway?</em>.</p>
</li>
<li><p>If your instance of state is dependent on the other one, like in our example above, number of todos were depended on todos array then we should use useReducer() hook.</p>
</li>
</ol>
<p>Since, this post is particularly targetted to understand useReducer() hook, I don&#39;t wanna go in details about implementing useState() with useReducer() or explanation of the above rules in detail because if you are new to useReducer then you might get confuse a bit. </p>
<p>However, <a target='_blank' rel='noopener noreferrer'  href="https://kentcdodds.com/about/">Kent C. Dodds</a>  has written awesome stuff and he has explained all this in even more detail. So definitely check that out if you are interested to dig even more.</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" data-card-width="600px" data-card-key="2e4d628b39a64b99917c73956a16b477" href="https://kentcdodds.com/blog/should-i-usestate-or-usereducer" data-card-controls="0" data-card-theme="light">https://kentcdodds.com/blog/should-i-usestate-or-usereducer</a></div>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" data-card-width="600px" data-card-key="2e4d628b39a64b99917c73956a16b477" href="https://kentcdodds.com/blog/how-to-implement-usestate-with-usereducer" data-card-controls="0" data-card-theme="light">https://kentcdodds.com/blog/how-to-implement-usestate-with-usereducer</a></div>
]]></content:encoded></item><item><title><![CDATA[Polyfills for .map(), .filter() and .reduce() in Javascript]]></title><description><![CDATA[What is a polyfill?
Polyfill is a piece of code, that developer expects from a browser to provide natively. If it's not available in the browser, you being a developer, use your logics and implement the solution.
I'll be using Logic's albums as examp...]]></description><link>https://blog.reeversedev.com/polyfills-for-map-filter-and-reduce-in-javascript</link><guid isPermaLink="true">https://blog.reeversedev.com/polyfills-for-map-filter-and-reduce-in-javascript</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[map]]></category><category><![CDATA[Reduce]]></category><dc:creator><![CDATA[Prateek Gogia]]></dc:creator><pubDate>Sat, 07 Sep 2019 12:57:15 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1599570189944/zoGi8eyck.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3 id="what-is-a-polyfill">What is a <code>polyfill</code>?</h3>
<p>Polyfill is a piece of code, that developer expects from a browser to provide natively. If it's not available in the browser, you being a developer, use your logics and implement the solution.</p>
<p><em>I'll be using Logic's albums as examples throughout my entire post just to show extra love for Hip Hop Music and easiness.</em></p>
<h3 id="foreach">.forEach()</h3>
<p><strong><em>.forEach()</em></strong> function comes quite handy when we just need to iterate an array.</p>
<p>This function is quite useful because we don't need to implement for loop from scratch, hence saving our time and a lot of crap on the developer screen.</p>
<p>But what if we wanna implement our own polyfill for <code>.forEach()</code>?</p>
<p>We have an array of Logic's albums and want to iterate through this array and print out the album one by one.</p>
<pre><code class="lang-js"><span class="hljs-keyword">var</span> logicAlbums = [
  <span class="hljs-string">'Bobby Tarantino'</span>,
  <span class="hljs-string">'The Incredible True Story'</span>,
  <span class="hljs-string">'Supermarket'</span>,
  <span class="hljs-string">'Under Pressure'</span>,
]
</code></pre>
<p>First, let's just check how it works natively as provided by JavaScript.</p>
<pre><code class="lang-js">logicAlbums.forEach(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">word</span>) </span>{
  <span class="hljs-built_in">console</span>.log(word)
  <span class="hljs-comment">// Bobby Tarantino,</span>
  <span class="hljs-comment">// The Incredible True Story,</span>
  <span class="hljs-comment">// Supermarket,</span>
  <span class="hljs-comment">// Under Pressure;</span>
})
</code></pre>
<p>Since it's an array, it makes sense to add a prototype to <code>Array</code>.</p>
<pre><code class="lang-js"><span class="hljs-built_in">Array</span>.prototype.eachAlbum = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">callback</span>) </span>{
  <span class="hljs-comment">// callback here is the callback function</span>
  <span class="hljs-comment">// which actual .forEach() function accepts</span>
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">var</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-keyword">this</span>.length; i++) {
    callback(<span class="hljs-keyword">this</span>[i], i, <span class="hljs-keyword">this</span>) <span class="hljs-comment">// currentValue, index, array</span>
  }
}
</code></pre>
<p>Let's try to use our own <code>polyfill</code></p>
<pre><code class="lang-js">logicAlbums.eachAlbum(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">word</span>) </span>{
  <span class="hljs-built_in">console</span>.log(word)
  <span class="hljs-comment">// Bobby Tarantino,</span>
  <span class="hljs-comment">// The Incredible True Story,</span>
  <span class="hljs-comment">// Supermarket,</span>
  <span class="hljs-comment">// Under Pressure;</span>
})
</code></pre>
<h3 id="map">.map()</h3>
<p><strong><em>.map()</em></strong> is very much similar to <strong><em>.forEach()</em></strong> method, except for the fact, that instead of returning items out of the array, it returns the array itself.</p>
<p><strong>But what sense does it make if it returns the array itself?</strong></p>
<p>.map() is used to iterate over the array, and do some manipulation in it with the items and then after doing that so, returns the manipulated array.</p>
<p><strong>In Action</strong></p>
<p>Let's use the collection of Logic's Albums again</p>
<pre><code class="lang-js"><span class="hljs-keyword">var</span> logicAlbums = [
  <span class="hljs-string">'Bobby Tarantino'</span>,
  <span class="hljs-string">'The Incredible True Story'</span>,
  <span class="hljs-string">'Supermarket'</span>,
  <span class="hljs-string">'Under Pressure'</span>,
]
</code></pre>
<p>Mapping these albums now using <strong>.map()</strong></p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> mapThoseAlbums = logicAlbums.map(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">album</span>) </span>{
  <span class="hljs-keyword">return</span> album
})

<span class="hljs-built_in">console</span>.log(mapThoseAlbums)

<span class="hljs-comment">// [</span>
<span class="hljs-comment">//   'Bobby Tarantino',</span>
<span class="hljs-comment">//   'The Incredible True Story',</span>
<span class="hljs-comment">//   'Supermarket',</span>
<span class="hljs-comment">//   'Under Pressure'</span>
<span class="hljs-comment">// ];</span>
</code></pre>
<p>As we can see that, <strong><em>mapThoseAlbums</em></strong> returns an array.</p>
<p>So we are clear that we have to return an array in our own polyfill function. So let's create it then.</p>
<pre><code class="lang-js"><span class="hljs-built_in">Array</span>.prototype.ourMap = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">callback</span>) </span>{
  <span class="hljs-keyword">var</span> arr = [] <span class="hljs-comment">// since, we need to return an array</span>
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">var</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-keyword">this</span>.length; i++) {
    arr.push(callback(<span class="hljs-keyword">this</span>[i], i, <span class="hljs-keyword">this</span>)) <span class="hljs-comment">// pushing currentValue, index, array</span>
  }
  <span class="hljs-keyword">return</span> arr <span class="hljs-comment">// finally returning the array</span>
}
</code></pre>
<p><strong>In Action</strong></p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> mapThoseAlbums = logicAlbums.ourMap(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">album</span>) </span>{
  <span class="hljs-keyword">return</span> album
})

<span class="hljs-built_in">console</span>.log(mapThoseAlbums)
<span class="hljs-comment">// [</span>
<span class="hljs-comment">// 'Bobby Tarantino',</span>
<span class="hljs-comment">// 'The Incredible True Story',</span>
<span class="hljs-comment">// 'Supermarket',</span>
<span class="hljs-comment">// 'Under Pressure'</span>
<span class="hljs-comment">// ];</span>
</code></pre>
<h3 id="filter">.filter()</h3>
<p><strong>.filter()</strong> is very much similar to the <strong>map()</strong> function except for the fact, it is used based on the context, where we decide what kind of items do we want in the resulting array.</p>
<p>Let's filter out Logic's greatest albums according to ratings</p>
<pre><code class="lang-js"><span class="hljs-keyword">var</span> logicAlbums = [
  {
    name: <span class="hljs-string">'Bobby Tarantino'</span>,
    rating: <span class="hljs-number">5</span>,
  },
  { name: <span class="hljs-string">'The Incredible True Story'</span>, rating: <span class="hljs-number">4.5</span> },
  {
    name: <span class="hljs-string">'Supermarket'</span>,
    rating: <span class="hljs-number">4.9</span>,
  },
  { name: <span class="hljs-string">'Under Pressure'</span>, rating: <span class="hljs-number">5</span> },
]

logicAlbums.filter(album =&gt; {
  <span class="hljs-keyword">return</span> album.rating &gt; <span class="hljs-number">4.9</span>
})
<span class="hljs-built_in">console</span>.log(logicAlbums)

<span class="hljs-comment">// [</span>
<span class="hljs-comment">//   { name: 'Bobby Tarantino', rating: 5 },</span>
<span class="hljs-comment">//   { name: 'Under Pressure', rating: 5 }</span>
<span class="hljs-comment">// ];</span>
</code></pre>
<p>Now let's create our own polyfill for <strong>filter</strong>.</p>
<pre><code class="lang-js"><span class="hljs-built_in">Array</span>.prototype.filterAlbums = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">callback, context</span>) </span>{
  arr = []
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">var</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-keyword">this</span>.length; i++) {
    <span class="hljs-keyword">if</span> (callback.call(context, <span class="hljs-keyword">this</span>[i], i, <span class="hljs-keyword">this</span>)) {
      arr.push(<span class="hljs-keyword">this</span>[i])
    }
  }
  <span class="hljs-keyword">return</span> arr
}
logicAlbums.filterAlbums(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">album</span>) </span>{
  <span class="hljs-keyword">return</span> album.rating &gt; <span class="hljs-number">4.9</span> <span class="hljs-comment">// providing the context here</span>
})
<span class="hljs-built_in">console</span>.log(logicAlbums)

<span class="hljs-comment">// [</span>
<span class="hljs-comment">//   { name: 'Bobby Tarantino', rating: 5 },</span>
<span class="hljs-comment">//   { name: 'The Incredible True Story', rating: 4.5 },</span>
<span class="hljs-comment">//   { name: 'Supermarket', rating: 4.9 },</span>
<span class="hljs-comment">//   { name: 'Under Pressure', rating: 5 }</span>
<span class="hljs-comment">// ];</span>
</code></pre>
<p>Over here, only albums with a rating more than 4.9 will be returned which are <a target="_blank" href="https://en.wikipedia.org/wiki/Bobby_Tarantino">Bobby Tarantino</a> and <a target="_blank" href="https://en.wikipedia.org/wiki/Under_Pressure_(album">Under Pressure</a>&gt;) (By the way, these are my favorites, that's why I rated them 5).</p>
<div class="d-flex flex-lg-row flex-md-row flex-column justify-content-around">
<div class="text-xs-center mb-4">
  <img src="https://upload.wikimedia.org/wikipedia/en/d/df/Logic_Under_Pressure_9.10.14.jpg" />
  <p>Under Pressure (2014)</p>
  </div>
  <div class="text-xs-center">
  <img src="https://upload.wikimedia.org/wikipedia/en/c/c9/Logic_-_Bobby_Tarantino_%28album_cover%29.jpg" />
    <p>Bobby Tarantino (2016)</p>
</div>
</div>

<h3 id="reduce">.reduce()</h3>
<p><strong>reduce()</strong> function is used to reduce the array to a single value. We'll again take the example of Logic's best work yet and combine all of them in a single line using <strong>.reduce()</strong> function.</p>
<p>.reduce() accepts a callback function <strong>(accumulator, currentValue, index and array)</strong> and initial value</p>
<pre><code class="lang-js"><span class="hljs-keyword">var</span> logicAlbums = [
  <span class="hljs-string">'Bobby Tarantino'</span>,
  <span class="hljs-string">'The Incredible True Story'</span>,
  <span class="hljs-string">'Supermarket'</span>,
  <span class="hljs-string">'Under Pressure'</span>,
]
<span class="hljs-keyword">var</span> withReduce = logicAlbums.reduce(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">a, b</span>) </span>{
  <span class="hljs-keyword">return</span> a + <span class="hljs-string">' , '</span> + b
}, <span class="hljs-string">'Young Sinatra'</span>) <span class="hljs-comment">// Here we are initialising the array with value as 'Young Sinatra'</span>

<span class="hljs-built_in">console</span>.log(withReduce)
<span class="hljs-comment">// Young Sinatra, Bobby Tarantino, The Incredible True Story, Supermarket, Under Pressure</span>
</code></pre>
<p>Let's create our own polyfill which is very easy.</p>
<pre><code class="lang-js"><span class="hljs-built_in">Array</span>.prototype.reduceAlbums = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">callback, initialValue</span>) </span>{
  <span class="hljs-keyword">var</span> accumulator = initialValue === <span class="hljs-literal">undefined</span> ? <span class="hljs-literal">undefined</span> : initialValue

  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">var</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-keyword">this</span>.length; i++) {
    <span class="hljs-keyword">if</span> (accumulator !== <span class="hljs-literal">undefined</span>) {
      accumulator = callback.call(<span class="hljs-literal">undefined</span>, accumulator, <span class="hljs-keyword">this</span>[i], i, <span class="hljs-keyword">this</span>)
    } <span class="hljs-keyword">else</span> {
      accumulator = <span class="hljs-keyword">this</span>[i]
    }
  }
  <span class="hljs-keyword">return</span> accumulator
} <span class="hljs-comment">// our polyfill for reduce</span>

<span class="hljs-keyword">var</span> logicAlbums = [
  <span class="hljs-string">'Bobby Tarantino'</span>,
  <span class="hljs-string">'The Incredible True Story'</span>,
  <span class="hljs-string">'Supermarket'</span>,
  <span class="hljs-string">'Under Pressure'</span>,
]

<span class="hljs-keyword">var</span> combineAlbums = logicAlbums.reduceAlbums(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">a, b</span>) </span>{
  <span class="hljs-keyword">return</span> a + <span class="hljs-string">' , '</span> + b
}, <span class="hljs-string">'Young Sinatra'</span>) <span class="hljs-comment">// Initial Value is Young Sinatra</span>

<span class="hljs-built_in">console</span>.log(combineAlbums)
<span class="hljs-comment">// Young Sinatra, Bobby Tarantino, The Incredible True Story, Supermarket, Under Pressure</span>
</code></pre>
<p>This article is really special for me since I am a huge fan of Logic. I tried to portray the whole post with Logic's best work yet just to give a personal touch. If you are a Hip Hop head like me, don't forget to check his work on the Internet.</p>
<p>Here's a tribute to his turning point of life that is, his album Young Sinatra.</p>
<div>
<img src="https://upload.wikimedia.org/wikipedia/en/7/78/YoungSinatra.jpg" />
</div>]]></content:encoded></item><item><title><![CDATA[this and bind() in Javascript]]></title><description><![CDATA["When dealing with JavaScript, things can get really confusing specially when you have to deal with Object-Oriented JavaScript (OOP based). Although, in Object-Oriented JavaScript, everything is in a form of functions and objects which is much less c...]]></description><link>https://blog.reeversedev.com/this-and-bind-in-javascript</link><guid isPermaLink="true">https://blog.reeversedev.com/this-and-bind-in-javascript</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Object Oriented Programming]]></category><dc:creator><![CDATA[Prateek Gogia]]></dc:creator><pubDate>Fri, 06 Sep 2019 15:15:21 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1599578515067/QSGQf20xn.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<div class="text-center">
<img src="https://cdn.jwplayer.com/thumbs/trS42zpd-720.jpg" id="responsive" alt="this-and-bind-in-javascript" />
</div>

<blockquote>
<p>"When dealing with JavaScript, things can get really confusing specially when you have to deal with Object-Oriented JavaScript (OOP based). Although, in Object-Oriented JavaScript, everything is in a form of functions and objects which is much less complex to understand the language (Really?)".</p>
</blockquote>
<h3 id="what-is-this">What is <code>this</code>?</h3>
<p>The keyword <code>this</code> in Javascript is being used exactly like the word 'this' in the English Language which means that whenever we are using <code>this</code> somewhere, we are talking about some context.</p>
<p>Let's dig even more by taking reference to (I'll go old school here), the times when there were kingdoms in the whole world and everyone wants to rule each other. A typical conversation at the time of war would be something like:</p>
<p><strong>King</strong>: <em>"We need to capture this peak of the mountain (pointing his finger on the map), before 05:00 hrs in order to control our situation better"</em>.</p>
<p><strong>Army Chief</strong>: <em>" I'm sorry to be so dumb, my king but which peak exactly?"</em></p>
<p><strong>King</strong>: <em>"This peak. (again pointing his finger on the map)"</em></p>
<p><strong>Army Chief</strong>: <em>"But boss, without even knowing any proper context for the peak which you are you talking about, how am I supposed to command my army to take action?"</em></p>
<p><strong>King</strong>: <em>"(After realizing about the situation that he's a literal dumb) We need to capture this peak(now taking the finger of army chief and pointing it on the point of map) of Mountain XYZ"</em></p>
<p><strong>Army Chief</strong>: <em>"I'll command the army right away"</em></p>
<p>In the above conversation, things got really confusing between two people because both were talking in their own individual contexts which further created confusion.</p>
<p>Similarly, in Javascript as well, things get really confusing when we deal with <strong>objects</strong>, <strong>functions</strong>, and <code>this</code> because we often make a mistake in context.</p>
<h3 id="stuff-about-javascript">Stuff about Javascript</h3>
<p>Here's a thing about Javascript, it's not only an object-oriented programming language but also a functional programming language that makes things much easier for a developer who is writing code in it. Higher-order functions like map(), reduce() and filter() do reduce the pain of manipulating the code with loops and finally the calculation related to the result.</p>
<p>As a matter of fact, Javascript as a whole is more and more about Objects and Functions. No matter whatever we wanna build with it, we need to make use of Objects and Functions.</p>
<h3 id="using-this-in-javascript">Using <code>this</code> in Javascript</h3>
<p>For Object-Oriented Programming languages, <code>this</code> keyword is one of the most important elements of the language, without it, the language is incomplete.</p>
<p>Let's understand better with some code.</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> person = {
  name: <span class="hljs-string">'HODOR'</span>,
  dialogue: <span class="hljs-string">'HODOR!'</span>,
  talk: <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-keyword">this</span>.dialogue)
  },
}
</code></pre>
<p>We have an object named 'person' which has a name, dialogue, and talk property. Now let's call it.</p>
<pre><code class="lang-js">person.talk() <span class="hljs-comment">// "HODOR!"</span>
</code></pre>
<p>That's what was expected. Right? Now, let's call it in a different fashion.</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> talkFunction = person.talk
talkFunction() <span class="hljs-comment">// undefined</span>
</code></pre>
<p>Yikes! This is what is happening over here.</p>
<p>When we are declaring variable <em>talkFunction</em>, it's no longer a method but rather a function. But again, why does it give <code>undefined</code>? It's because,</p>
<blockquote>
<p><code>this</code> keyword refers to the context where it is <strong>called</strong> and NOT where it is <strong>assigned</strong>.</p>
</blockquote>
<h4 id="so-what-do-we-do-to-use-that-talkfunction">So what do we do to use that talkFunction?</h4>
<p>Here, <code>bind()</code> comes in action. A <code>bind()</code> is responsible for attaching an object to a function by which it has been called.</p>
<p>Let's take a look at the code again,</p>
<pre><code class="lang-js"><span class="hljs-keyword">let</span> person = {
  name: <span class="hljs-string">'Jon Snow'</span>,
  dialogue: <span class="hljs-string">'We the North!'</span>,
  talk: <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-keyword">this</span>.dialogue)
  },
}

<span class="hljs-keyword">let</span> talkFunction = person.talk
<span class="hljs-keyword">let</span> bindedFunction = talkFunction.bind(person)
bindedFunction() <span class="hljs-comment">// "We the North!"</span>
</code></pre>
<p>Here, <code>bind()</code> attaches the 'person' object to <em>talkFunction</em> and therefore, the talk function is able to get <code>this.dialogue</code> and hence prints the dialogue, <strong>"We the North!"</strong></p>
]]></content:encoded></item></channel></rss>