<?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 Shivam Bhasin on Medium]]></title>
        <description><![CDATA[Stories by Shivam Bhasin on Medium]]></description>
        <link>https://medium.com/@shivambhasin29?source=rss-5e7993f1513e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*qAWn7rTwtcdWlrKzeU3xrA.jpeg</url>
            <title>Stories by Shivam Bhasin on Medium</title>
            <link>https://medium.com/@shivambhasin29?source=rss-5e7993f1513e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 13:09:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shivambhasin29/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[Mastering Frontend System Design: Building a Dynamic Form Builder from Scratch]]></title>
            <link>https://shivambhasin29.medium.com/mastering-frontend-system-design-building-a-dynamic-form-builder-from-scratch-0dfdd78d31d6?source=rss-5e7993f1513e------2</link>
            <guid isPermaLink="false">https://medium.com/p/0dfdd78d31d6</guid>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[frontend-system-design]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[frontend]]></category>
            <dc:creator><![CDATA[Shivam Bhasin]]></dc:creator>
            <pubDate>Tue, 31 Dec 2024 03:36:03 GMT</pubDate>
            <atom:updated>2024-12-31T03:36:03.175Z</atom:updated>
            <content:encoded><![CDATA[<h3>Frontend System Design: Building a Dynamic Form Builder from Scratch</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pCFfOr5fbojA7pyaB_gcyw.png" /></figure><p>Hey everyone! I realized that many folks aren’t familiar with how frontend system design interviews work — and unfortunately, there aren’t many good resources out there either. So, I decided to tackle a common frontend system design problem and break it down into a structured solution.</p><p>Let’s dive right in!</p><h3>Problem scope</h3><p>Design a frontend system where users can create, modify, and interact with dynamic forms. The form builder should allow adding various field types (e.g., text, dropdown, date picker), validation rules, conditional logic, and submission handling.</p><h3>Key requirements</h3><p><strong>User Interface:</strong></p><ul><li>Drag-and-drop field placement.</li><li>Real-time preview of the form being built.</li><li>Configurable field properties (label, placeholder, validation, etc.).</li></ul><p><strong>Field Types:</strong></p><ul><li>Text Input, Dropdown, Radio Buttons, Checkbox, Date Picker, etc.</li></ul><p><strong>Conditional Logic:</strong></p><ul><li>Show/hide fields based on other field values.</li></ul><p><strong>Validation:</strong></p><ul><li>Required fields, regex patterns, min/max lengths, etc.</li></ul><p><strong>Preview Pane (Optional):</strong></p><ul><li>Real-time rendering of the form as users build it.</li></ul><p>Now that we have the problem statement and key requirements sorted, let’s start designing the system.</p><h3>1. Component Architecture</h3><p>Use a modular component-based architecture for scalability.</p><ul><li><strong>FormBuilder</strong> Component: Main UI to build forms.</li><li><strong>FieldPalette</strong>: Sidebar containing draggable field types.</li><li><strong>Canvas</strong>: Area to drop and arrange fields.</li><li><strong>FieldConfigurator</strong>: Config panel for selected field properties.</li><li><strong>PreviewPane</strong>(Optional): Live preview of the form.</li><li><strong>DynamicForm</strong> Component: UI to render the form. Handles form submission and validation dynamically.</li></ul><h3>2. State Management</h3><p>Centralize the state for consistency and better performance.</p><ul><li><strong>Global State:</strong> Use <strong>Redux</strong> or <strong>Context API</strong>.</li><li>Store the structure of the form ([{ id, type, label, config }]).</li><li>Track conditional logic (if field A === X, show field B).</li><li><strong>Local State:</strong> Manage UI-specific states (e.g., drag-and-drop interactions, active field selection).</li></ul><h3>3. Data Model</h3><pre>interface FormField {<br>  id: string; // Unique ID for the field<br>  type: string; // Field type (e.g., &#39;text&#39;, &#39;dropdown&#39;)<br>  label: string; // Field label<br>  config: {<br>    placeholder?: string;<br>    options?: string[]; // For dropdown, radio, etc.<br>    validation?: {<br>      required?: boolean;<br>      regex?: string; // Validation pattern<br>      minLength?: number;<br>      maxLength?: number;<br>    };<br>    conditionalLogic?: {<br>      showIfField: string; // Field ID<br>      condition: string; // E.g., &#39;equals&#39;, &#39;notEquals&#39;<br>      value: string | number;<br>    };<br>  };<br>}</pre><h3>4. Drag-and-Drop Logic</h3><p>Use libraries like <strong>react-dnd</strong>.</p><ul><li>Fields from the palette are dragged and dropped onto the canvas.</li><li>Update the global state with the new field structure and order.</li></ul><h3>5. Conditional Logic</h3><ul><li>Add a UI for users to configure conditions (e.g., “Show this field if Field A = ‘Yes’”).</li><li>Store logic in the field configuration and evaluate it during rendering.</li></ul><h3>6. Form Rendering</h3><ul><li>Iterate over the form structure and render components dynamically.</li><li>Use a <strong>Registry Pattern</strong> for field rendering:</li></ul><pre>const fieldRegistry = {<br>  text: (props) =&gt; &lt;TextField {...props} /&gt;,<br>  dropdown: (props) =&gt; &lt;DropdownField {...props} /&gt;,<br>  // Add other field types...<br>};<br><br>fields.map((field) =&gt; fieldRegistry[field.type](field.config));</pre><h3>7. Validation Handling</h3><ul><li>Generate validation rules dynamically based on the validation property of each field.</li></ul><h3>8. Optimization</h3><ul><li><strong>Virtualization:</strong> Use libraries like <strong>react-window</strong> for rendering large forms.</li><li><strong>Debouncing:</strong> Optimize user interactions (e.g., input changes, dragging).</li><li><strong>Memoization:</strong> Use React.memo or useMemo for expensive computations.</li></ul><h3>Example Workflow</h3><ol><li><strong>User Action:</strong> Drag a “Text Input” field onto the canvas.<br>- Add a new field object to the global state.<br>- Render the new field in the canvas.</li><li><strong>User Configures Field:</strong> Add a label, placeholder, and validation rules.<br>- Update the corresponding field’s config in the state.</li><li><strong>Save:</strong> Serialize the form state into JSON.</li><li><strong>Load:</strong> Deserialize JSON to recreate the form structure.</li></ol><p>This was a high-level design (HLD) for the problem, which can dive into low-level design (LLD) depending on where the interviewer wants to focus. Remember, system design interviews are always a collaborative conversation — there’s no single “right” or “wrong” approach.</p><p>I’ll keep sharing more insights about frontend system design, so stay tuned! If you’d like me to deep-dive into any topic from this blog or explore another problem, let me know. Your suggestions might shape the next post!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0dfdd78d31d6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Do we really need a partner?]]></title>
            <link>https://shivambhasin29.medium.com/do-we-really-need-a-partner-46c14a701cd?source=rss-5e7993f1513e------2</link>
            <guid isPermaLink="false">https://medium.com/p/46c14a701cd</guid>
            <category><![CDATA[millenials]]></category>
            <category><![CDATA[love]]></category>
            <category><![CDATA[relationships]]></category>
            <dc:creator><![CDATA[Shivam Bhasin]]></dc:creator>
            <pubDate>Sat, 11 Mar 2023 18:14:03 GMT</pubDate>
            <atom:updated>2023-03-11T18:14:03.403Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*629vGzXADpfAMk3KXUL1rQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@brett_jordan?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Brett Jordan</a> on <a href="https://unsplash.com/photos/O3QGr8EtXig?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Do we need a partner in our life? Is there no life without getting married or finding the right person to live our lives with? Well, at least that’s what we have been told since childhood. Movies, tv shows, novels— everything leads up to this one thing, a perfect partner!</p><p>The millennials are different from this, at least I am. I don’t need a partner to be happy. I have a life of my own and I am glad. Honestly, I miss that love part sometimes, someone I could open up my heart with but then I see my career, my family, and the routine I have in my life which I don’t want to shatter for anything.</p><p>Speaking to my friends who already are in a relationship is also too depressing. None, I repeat, none of them is in a happy relationship and they know that they will have to break up at some point to find a new one in life, the perfect one. Only if it exists!</p><p>Some people pretend to be happy but I just need one deep conversation with them to get the truth out. And anyway there is no chemistry without some exceptions.</p><p>Honestly, I wouldn’t mind meeting someone who is serious about her career but then where will she be looking for guys in the world? Tinder? Bumble? Hinge? I doubt that. She must already be living a meaningful life doing things she loves! Building a career she is proud of and eventually, I’ll be too and then maybe one day we will meet and share that happiness with each other, IF DESTINED.</p><p>My relationship status till then — not looking out for one!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=46c14a701cd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[3 Brain Exercising Habits for Writing Better Software]]></title>
            <link>https://javascript.plainenglish.io/three-brain-exercising-habits-for-writing-better-software-79ce6b3dccdc?source=rss-5e7993f1513e------2</link>
            <guid isPermaLink="false">https://medium.com/p/79ce6b3dccdc</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Shivam Bhasin]]></dc:creator>
            <pubDate>Sun, 06 Feb 2022 09:50:43 GMT</pubDate>
            <atom:updated>2022-02-08T05:04:17.356Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zv7PqdvRLTL9CU6YpAGDXQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@alisaanton?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Alisa Anton</a> on <a href="https://unsplash.com/s/photos/self-help?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Just like physical exercises are essential for our body, it&#39;s equally important to exercise our brain, which most of us, due to our busy schedules, can&#39;t afford.</p><p>We are living in an overly stimulated environment right now. Everything around us, be it social media, movies, TikTok, is filled with quick shots of dopamine. And the worst part is most of us got addicted to it without even knowing.</p><h3>Why is this bad?</h3><p>Earlier, we used to get our dopamine dose from watching a 3-hour movie, which got reduced to a 1-hour Netflix episode, then to a 10-minute Youtube video, and now to a 15 seconds Instagram reel.</p><p>Without even noticing this, we have lost our focusing abilities to these 15 seconds videos, and we have no clue what&#39;s next.</p><p>As software engineers, we sometimes have to go very deep inside a code or sit with a bug for many hours, in some cases, days. But if we are so addicted to quick dopamine hits, it just won&#39;t be possible to sit for this much time. The problem is that we will get a dopamine hit once we resolve the bug or understand a piece of code but will our brain wait for that long when it knows dopamine is just an Instagram reel away.</p><p>Now that we know the problem, fortunately, we have a solution too. Below, I&#39;ve listed the three habits that I&#39;ve been using for more than a year now, which have helped me get my focusing power back and feel more connected to the outer world.</p><h3>#1 Quit Social Media</h3><p>Quitting social media might be the most difficult one considering that being socially connected is one of the leading human motivations. While I guess there is nothing wrong with using social media to communicate with others, it has gradually become your best source of entertainment. You&#39;ll be amazed to see the time you spend daily on social media apps.</p><p>The first question that people ask me about quitting social media is how we would know what&#39;s going on in the world. Like seriously? Everything is going on in the world right now. A far better question would be what do you want to choose to focus on.</p><p>It won&#39;t be accessible once you quit social media because your brain will constantly crave dopamine. I have the following set of rules I used to get out of it based on the book Atomic Habits by James Clear. These might help you too.</p><ol><li>For the first three to four weeks, remove all the social media apps from your phone&#39;s home screen and make them not easily accessible.</li><li>Now you have seen how your brain was addicted to the location of these apps on your phone. For the next three to four weeks, delete these apps entirely and use them from your phone&#39;s browser.</li><li>The UI/UX of these apps in the browser is so bad that the dopamine levels associated with them will drop gradually.</li><li>Once you notice that there are days that you don&#39;t even open these apps, it&#39;s this time when you can finally quit social media.</li><li>Every time your brain asks for dopamine, try giving it through reading books or forming a good habit that you&#39;d wanted to do for long, but your addiction to social media didn&#39;t allow it. Eventually, your brain will associate dopamine with these good habits.</li><li>Ask all your friends to contact you either through phone calls or Whatsapp.</li><li>After a few months, when you&#39;ve finally gotten out of it, you can again start using them but this time consciously setting a limit on their usage. Phones nowadays have a screen time limit feature available. Use that wisely.</li></ol><h3>#2 Start Reading</h3><p>Reading is by far the best thing that I started last year as a replacement for social media. It will help you exercise your brain for better focus and teach you some life-changing lessons and knowledge. I have read all sorts of technical, fictional, and self-help books in the previous year.</p><p>You can start with as short as 15 minutes a day which will be sufficient for your brain exercise routine. In my opinion, reading is the most efficient way to supplement your brain with good knowledge and grow yourself. Your choice of books can depend on you, but I&#39;d recommend starting from these books if you haven&#39;t read them before.</p><ol><li>Atomic Habits by James Clear</li><li>Think and grow rich by Napolean Hill</li><li>Deep Work by Cal Newport</li></ol><h3>#3 Start Meditating</h3><p>Meditation will improve your focus heavily and allow you to know about the thoughts that cloud your brain for the majority of the day. Once you observe your thoughts, you can also change them constructively for better habits and life ahead. I&#39;ve read this somewhere — &#39;You&#39;ll become your thoughts, not gradually but eventually.&#39;</p><p>Meditation will your physical health, too, including lowering blood pressure, boosting the immune system, and increasing your ability to cope with stress.</p><p>If you haven&#39;t meditated before, you&#39;ll be amazed to know that meditation is this easy.</p><ol><li>Find someplace quiet where you won&#39;t be interrupted, and sit upright in a relaxed but alert position (a chair works well for most everyone)</li><li>You can keep your eyes open or closed, whatever helps you feel more alert and focused.</li><li>Set a timer for how long you want to meditate. I&#39;d recommend just 5–10 minutes if you are starting this.</li><li>Focus on your breath. Don&#39;t try to control or analyze your breath; observe it and the physical sensations that take place in your body as you breathe in and out.</li><li>When your mind wanders — and it will wander — bring your attention back to focus on your breath and the physical sensations. You&#39;ll have to do this repeatedly while you meditate.</li><li>While your mind wanders, observe it as a third person going out to a thought and then coming back to your breath.</li></ol><p>You know the best time to start all this is now. Yes, start from today itself and one year down when you&#39;ll benefit from this — and you will for sure — come back to this space, and I&#39;d love to hear your success story.</p><p>Happy coding till then.</p><p><em>Shivam Bhasin writes about JavaScript, software development, and self-help. He graduated in 2020 and is currently working as a senior software engineer at an IT firm in Delhi. Follow him on </em><a href="https://www.linkedin.com/in/shivam-bhasin-69a588158/"><em>Linkedin</em></a><em>.</em></p><p><em>More content at </em><a href="http://plainenglish.io/"><strong><em>plainenglish.io</em></strong></a><em>. Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. Get exclusive access to writing opportunities and advice in our </em><a href="https://discord.gg/GtDtUAvyhW"><strong><em>community Discord</em></strong></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=79ce6b3dccdc" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/three-brain-exercising-habits-for-writing-better-software-79ce6b3dccdc">3 Brain Exercising Habits for Writing Better Software</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript Keywords In-Depth: A Comprehensive Guide on ‘let’, ‘var’, and ‘const’]]></title>
            <link>https://javascript.plainenglish.io/lets-var-and-const-in-javascript-4e0319dbf463?source=rss-5e7993f1513e------2</link>
            <guid isPermaLink="false">https://medium.com/p/4e0319dbf463</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Shivam Bhasin]]></dc:creator>
            <pubDate>Sat, 05 Feb 2022 19:02:33 GMT</pubDate>
            <atom:updated>2022-02-08T05:53:54.339Z</atom:updated>
            <content:encoded><![CDATA[<h4>Explore the three most confusing keywords — &#39;let&#39;, &#39;var&#39;, and &#39;const&#39; along with their scopes, and their hoisting behaviors.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u53a6sR-SkDm1sSfMKayqg.png" /></figure><p>In the past few years, the popularity of JavaScript frameworks like React, Angular, and Vue.js has attracted many web developers to move towards them. While there is no problem with them, one thing that worries me is that I’ve seen some people completely ignoring the concepts of Vanilla JavaScript and still doing just fine with frameworks.</p><p>I was interviewing React Developer for my organization when I saw something strange. I noticed that people with more than two years of React experience and a good understanding of it didn’t know the basics of JavaScript, even the difference between let, var, and const. One funny response I got was that let is just the new version of var.</p><p>Moving on, let’s discuss the three keywords — let, var, and consttheir scopes, and their hoisting behaviors.</p><h3>Var</h3><p>Before ES6, everything was going just fine with var, but there were issues related to variables declared with the var keyword. Let’s first understand how var behaves.</p><h4>Scope</h4><p>Variables declared with var are globally scoped when declared outside a function and are function or block-scoped when the declaration is made inside. See the code below.</p><pre>var iAmGlobal = &#39;global scoped&#39;;</pre><pre>function func() {<br>  var iAmBlock = &#39;bloack scoped&#39;;<br>}</pre><pre>console.log(iAmBlock); // <strong>error: iAmBlock is not defined</strong></pre><p>In the example above, the variable iAmGlobal is declared globally and is available anywhere inside the code, even inside the function func but iAmBlock is scoped only inside the function func. So when we tried to access iAmBlock outside the function, JavaScript throws an error saying it is not defined.</p><h4>Hoisting</h4><p>All variables declared using var are hoisted to the top of their scope before executing code. In the case of functions, the complete function body is hoisted. See the code below.</p><pre>console.log(a); // undefined<br>func(); // &#39;this function can execute even before declaration&#39;</pre><pre>var a = 10;<br>var func = function () {<br>  console.log(&#39;this function can execute even before declaration&#39;);<br>};</pre><p>In the example above, both variables a and func are hosted and are hence available to use even before their declaration. However, in the case of athe value with which it is hoisted is undefined.</p><p>Before starting with let and const which were introduced in ES6, it’d be better to know the problems with var.</p><h4>Problems with var</h4><p>The issue with var is that variables can be redeclared, which leads to confusion in the code. See an example below.</p><pre>var mesg = &#39;I am this message&#39;;</pre><pre>// many lines after</pre><pre>var mesg = &#39;I am updated to this&#39;;</pre><pre>console.log(mesg); // <strong>&#39;I am updated to this&#39;</strong></pre><p>While this is not a problem if we know what we are doing but in the real world, many developers work on the same projects and sometimes on the same file, which can lead to inconsistencies in the code. With this being taken into account, let and const were introduced.</p><h3>Let</h3><p>let solved the issue we just discussed above. Variables initialized using let can be updated in their scope but can not be redeclared.</p><h4>Scope</h4><p>let is block-scoped, which means that any variable declared is accessible only inside the block it is initialized. See the code below.</p><pre>if(true){<br>   let mesg = &#39;I am inside the if block only&#39;;<br>   console.log(mesg); // <strong>I am inside the if block only<br></strong>}<br>console.log(mesg); // <strong>error: mesg is not defined</strong></pre><p>In the example above, the variable mesg is declared inside the if block, and hence when accessed outside, it will throw an error.</p><h4>Hoisting</h4><p>Variables declared with let are also hoisted to the top of the code before execution but not initialized. So, if we try to access them before their declaration, we’ll get a reference error. See the code below.</p><pre>console.lot(mesg); // <strong>error: mesg is not defined</strong><br>let mesg = &#39;You can&#39;t access me before this line&#39;;</pre><h3>Const</h3><p>const variables are similar to let variables, but they can neither be updated nor redeclared. So, they maintain constant values throughout the code execution. See the example below.</p><pre>const mesg = &#39;You can&#39;t update me&#39;;<br>mesg = &#39;This won&#39;t work&#39;; // <strong>error: Assignment to constant variable</strong></pre><p>But we can update the values inside an const object. See the example below.</p><pre>const user = { fname: &#39;shivam&#39;, lname: &#39;bhasin&#39; };<br>user.fname = &#39;updated name&#39;; // <strong>This is allowed and valid</strong></pre><h4>Scope</h4><p>Just like let, const variables are also block scoped. So they are accessible within the block of their declaration.</p><h4>Hosting</h4><p>Again, similar to let variables, const variables are also hoisted to the top but are not initialized.</p><p>If you missed something, here’s a short revision of the story.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3z7PFKw1mznhIdIjszA-sA.png" /></figure><p>If you are a JavaScript developer or want to become one someday, I highly recommend checking this space back as I’ll make sure you will fall in ❤️ with JavaScript.</p><p><em>More content at </em><a href="http://plainenglish.io/"><strong><em>plainenglish.io</em></strong></a><em>. Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. Get exclusive access to writing opportunities and advice in our </em><a href="https://discord.gg/GtDtUAvyhW"><strong><em>community Discord</em></strong></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4e0319dbf463" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/lets-var-and-const-in-javascript-4e0319dbf463">JavaScript Keywords In-Depth: A Comprehensive Guide on ‘let’, ‘var’, and ‘const’</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Journey of a console.log in React Native]]></title>
            <link>https://javascript.plainenglish.io/journey-of-a-console-log-in-react-native-6148b4627563?source=rss-5e7993f1513e------2</link>
            <guid isPermaLink="false">https://medium.com/p/6148b4627563</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Shivam Bhasin]]></dc:creator>
            <pubDate>Sun, 30 Jan 2022 08:16:25 GMT</pubDate>
            <atom:updated>2022-01-31T15:11:41.228Z</atom:updated>
            <content:encoded><![CDATA[<h4>A brief introduction to React Native’s new architecture.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U0WSAruR02OOZFWXJ03Yeg.png" /></figure><p>I’ve been developing user interfaces for a long time now. I learned many new things during this phase, switched from JavaScript to TypeScript for a while, then back at JavaScript, worked on web apps using React and also mobile apps using React Native.</p><p>One thing that stayed with me all this time was the love for console.log . Today, I’m using different debuggers and minifiers for debugging my code but I don’t trust anyone as much as I do console.log.</p><p>Like most JavaScript beginners, I also, for a majority of the time, believed that console.log is provided to us by JavaScript. But as I got more familiar with terms like Google’s V8, JavaScript Engine, and WebAPI’s, it got clearer. But like an experienced JavaScript developer said — it’s not that simple.</p><h3>It’s not that simple</h3><p>Yes, it’s not. Once, I tried to print the value of console.log in the browser and got a function that says native code. See the image below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*-3eA7YlhfGGgm5gj1dg1mg.png" /><figcaption>Chrome in a normal environment</figcaption></figure><p>This was pretty much meeting my expectations as console.log is anyway a function lying inside WebAPIs which has native code. But I tried a similar thing inside a react native environment, and that’s where things started taking a turn. See the image below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1022/1*ClbhoWAB0Z6j53cEgCy3nw.png" /><figcaption>Safari in React Native JSContext</figcaption></figure><p>So what is it that React Native does to get console.log up and running from our JavaScript code to native Android and iOS devices? I knew about React Native’s asynchronous bridge and how it serializes and deserializes stuff from JavaScript to native Android and iOS. But is this just that?</p><h3>Let’s find out</h3><p>I finally landed on React Native’s Github repository and searched for console. See the image below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vKUc7_wJPxMhX79JhPWS7g.png" /></figure><p>Two console.js files came up — the first one inside flow which has the type declarations for the module, and the one inside polyfills appeared to be a good place to start investigating. So I opened the file, started messing around, and read the functions until I found this function getNativeLogFunction. See below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a1d2b1b46a6ceca77f8978217a88dc17/href">https://medium.com/media/a1d2b1b46a6ceca77f8978217a88dc17/href</a></iframe><p>This function takes in the argument of log level, manipulates our string, and finally calls the nativeLoggingHook on the global object. But there is no function with the name nativeLoggingHook in the browser. This got me curious and I investigated further to see if React Native provides an implementation of this function.</p><p>So now I searched for nativeLoggingHook in the repo and interestingly found one file. See the image below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l8A7uh_z-6J2eNeuwcLgEA.png" /></figure><p>I have been a JavaScript developer for most of my development life and never really got a chance to work on CPP. But we all have a curious kid inside us and mine led me to open the file and give the method bindNativeLogger a read.</p><p>After giving it a few minutes I realized how bad I’m at CPP so before going into depression, I did what I’ve been doing a lot while learning new things — I assumed that I know what this code does and moved ahead with my investigation to how bindNativeLogger is used in the code.</p><p>I searched bindNativeLogger in the repository and found two files. See the image below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-i0SEXgVxaPbva4ock3eqA.png" /></figure><p>This is where things finally started to make sense. In these two files above bindNativeLogger is called with JavaScript runtime and the native loggers — iosLoggingBinder in RCTJSIExecutorRuntimeInstaller.mm and androidLogger in OnLoad.cpp.</p><p>Then I opened the RCTJSIExecutorRuntimeInstaller.mm file where the method bindNativeLogger is called with the JavaScript runtime and iosLoggingBinder. See the code below at line 15.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f25761fb770e621b020a440ce0617416/href">https://medium.com/media/f25761fb770e621b020a440ce0617416/href</a></iframe><p>After I dig a little deeper, I found out thatiosLoggingBinder is a function _RCTLogJavaScriptInternal defined in RCTLog.mm. See the image below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xrl3BEjSF51GJ84KGM0PXw.png" /></figure><p>This is where console.log finally gets called on the iOS ecosystem. So somehow the console I wrote in JavaScript went a bunch of methods deep and eventually called _RCTLogJavaScriptInternal method in the RCTLog.mm file. There was CPP involved in between but I as a JavaScript developer can ignore it, at least for some time. See the image below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bWvbO90mqOHpGcsjqnTTQw.png" /><figcaption>Credit: YT video — Building React Native: Take a look at the internals — Parashuram N</figcaption></figure><p>So in a way, JavaScript is invoking a native module without actually using the React Native bridge. This is not even asynchronous, it’s just one call after the other. This got me curious and I finally went back to the CPP code that I previously ignored.</p><p>The CPP code that I ignored previously is what is known as the JavaScript interface a.k.a JSI — the new React Native architecture. JSI is a new and standardized way of exposing native Java or Objective-C objects from native modules to the JavaScript world.</p><h3>Bonus</h3><p>This got me even more curious and then I got to know about React Native’s new architecture that’s been under development. This was just a brief introduction to light up your curiosity about this new and interesting thing that’s been cooking inside the React Native community.</p><p>If you’re someone that’s been developing mobile apps on React Native then do subscribe to this blog as in the next part of this I’ll be deep-diving more inside this new architecture and explore things like TurboModules, JSI, Fabric, and CodeGen.</p><p><strong><em>LET THE GEEK INSIDE YOU WIN!</em></strong></p><p><em>More content at </em><a href="http://plainenglish.io/"><strong><em>plainenglish.io</em></strong></a><em>. Sign up for our </em><a href="http://newsletter.plainenglish.io/"><strong><em>free weekly newsletter</em></strong></a><em>. Get exclusive access to writing opportunities and advice in our </em><a href="https://discord.gg/GtDtUAvyhW"><strong><em>community Discord</em></strong></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6148b4627563" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/journey-of-a-console-log-in-react-native-6148b4627563">Journey of a console.log in React Native</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Let’s build our own Redux]]></title>
            <link>https://javascript.plainenglish.io/lets-build-our-own-redux-9384b283529c?source=rss-5e7993f1513e------2</link>
            <guid isPermaLink="false">https://medium.com/p/9384b283529c</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[redux]]></category>
            <dc:creator><![CDATA[Shivam Bhasin]]></dc:creator>
            <pubDate>Fri, 05 Nov 2021 17:58:13 GMT</pubDate>
            <atom:updated>2021-11-06T14:43:14.160Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y8d2YnHhgwEBNr8a6Krvkg.png" /></figure><p>I coded in Java/Kotlin for most of my college life, and hence, followed the MVC pattern mostly for projects. Ironically, my first job right after college was as a ReactJS developer. Now that I had to shift my paradigm from that to the functional approach of modeling data, Redux, it wasn’t easy for me and, I had my share of tough times getting my head around.</p><p>For starters, it was almost like magic. How is <strong>redux putting all the pieces together</strong> was the question that haunted me for a long time until one day I decided not anymore. The geek inside me, just like yours, started getting to know it more. Well, you’re at the right place and wonder no more, today when you’ll leave you’d have sufficient knowledge to build your own <strong>redux</strong>.</p><p>Redux, minimally, can be broken down into two things — reducers and flux.</p><h3>What is flux?</h3><p>Flux is a pattern or architecture, not a library or framework, for managing data flow in our applications. Created by Facebook, now Meta, its USP is that data flows in one and only one direction. See the image below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pgxTL69KXTYjupzGO015Ew.png" /><figcaption>Image source: <a href="https://github.com/facebook/flux/tree/main/examples/flux-concepts">https://github.com/facebook/flux/tree/main/examples/flux-concepts</a></figcaption></figure><p>Any change in the data, i.e. the <strong>store</strong>, will have to go through the <strong>dispatcher. </strong>That prevents more than one action from changing the same data in the <strong>store </strong>at the same time<strong>.</strong> Views read any required information from the store and display it on the UI part. Let’s understand these quickly using a simple add-to-cart functionality in our application.</p><h4>Dispatcher</h4><p>The only source of incoming to the store is through the dispatchers. The dispatcher receives information through actions and passes it to the store. <strong>Every store will receive every action</strong>. Also, the flux pattern states that every application should have a singleton dispatcher.</p><p>As soon as the user presses the add-to-cart button, our view captures the event and dispatches an add-to-cart action containing the product id.</p><h4>Store</h4><p>The store is the mini database of our application. It has all the data that is needed to persist and that’s it. It registers with the dispatcher to receive actions. The data in the store must only be mutated by responding to an action.</p><p>On receiving the add-to-cart action, our store updates the cart and emits a change event in our application.</p><h4>Actions</h4><p>Actions are simple JavaScript objects with the type of action that needs to be dispatched and the payload, or data required for that particular action. Conventionally, actions should be semantic and not describe the implementation of the action.</p><p>In our case add-to-cart is the action which will look more or like below.</p><pre>{<br>   type: &#39;add-to-cart&#39;,<br>   payload: { <br>     product: &#39;1&#39; <br>   }<br>}</pre><h4>Views</h4><p>These are just UI components that display data from the store. They listen to change events from the store and re-render depending on the context. Actions are typically dispatched from the UI on user-triggered event callbacks.</p><p>When the user presses the add-to-cart button, we dispatch the add-to-cart action on the onclick callback.</p><p>Now that we know the flux framework, let’s start with building our own redux. Also, if you have a lesser understanding of the reduce method of JavaScript, quickly give this <a href="https://javascript.plainenglish.io/lets-deduce-the-reduce-method-in-javascript-bdc828f368a2">piece</a> a read and join back here. If you already know let&#39;s start with a simple sum function using reduce.</p><h4>Reducing an array to sum</h4><p>Reduce method can be used to calculate the sum of the array. Here’s a simple implementation.</p><pre>const sum = (nums) =&gt; {<br>   return nums.reduce((state, next) =&gt; state + next);<br>};<br>sum([1,2,3,4]); // <strong>10</strong></pre><p>Let’s make this a bit more complex to write.</p><pre>const sum = (nums) =&gt; {<br>   const iterator = (state, next) =&gt; state + next;<br>   const [initialState, rest] = nums;<br>   return rest.reduce(iterator, initialState);<br>};<br>sum([1,2,3,4]); // <strong>10</strong></pre><p>I just destructured the array and created the iterator function separately. Looks good till now. Now let’s try to move towards a more real-world-like application of this concept.</p><h4>Getting specific</h4><p>Suppose we have a cart that receives updates about the product quantity as per the user interaction on the UI. Here’s an updated version of the above code to match this use case.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c7a56944d2363211cf170e610bb09294/href">https://medium.com/media/c7a56944d2363211cf170e610bb09294/href</a></iframe><p>The update method is the same sum function we saw before just used as an update method of the quantity of a product inside the cart. All values in the array passed to the update method are essentially actions passed to the reducer. Let’s make it more clear by giving names to our actions. See below code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/81a9b3eb3a8ec4bf6e31f577f19adca0/href">https://medium.com/media/81a9b3eb3a8ec4bf6e31f577f19adca0/href</a></iframe><p>See how all our actions now have a type field and the payload, qty in our case. Also, passing the existing store as the initial state to reduce() then overwriting it with the result, we can start transforming data across multiple calls to reduce.</p><p>This approach makes our code easier to read and maintainable. Also, our store is only concerned with data modeling and logic which makes store and reducers extremely portable. The same set of reducers and stores can be used for both, a web application on ReactJS and a mobile application on React Native which is pretty cool considering the less time we have nowadays to ship our idea to a product.</p><p>Hope you’ve learned something new today. Do try to make a redux-like application to solve an application challenge closer to you. Also, let me know what JavaScript topics are still haunting you and we’ll try to understand them.</p><p><strong><em>Let the GEEK inside you win!</em></strong></p><p><em>More content at </em><a href="http://plainenglish.io/"><strong><em>plainenglish.io</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9384b283529c" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/lets-build-our-own-redux-9384b283529c">Let’s build our own Redux</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Let’s Deduce the Reduce Method in JavaScript]]></title>
            <link>https://javascript.plainenglish.io/lets-deduce-the-reduce-method-in-javascript-bdc828f368a2?source=rss-5e7993f1513e------2</link>
            <guid isPermaLink="false">https://medium.com/p/bdc828f368a2</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[computer-science]]></category>
            <dc:creator><![CDATA[Shivam Bhasin]]></dc:creator>
            <pubDate>Wed, 27 Oct 2021 04:12:52 GMT</pubDate>
            <atom:updated>2021-10-27T05:25:50.918Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2dIXR94-NecFxfrc3g8eIg.png" /></figure><p>I’ve been learning JavaScript for two years now and got familiar with almost all of its tricks pretty soon — the map function, filter, sort, and others. Well, not lying, I got stuck at points but some decent explanations were covering these topics on the web or YouTube except for this one thing —the reduce method.</p><p>And then I wondered why no one was talking about the reduce method confidently like other methods in JavaScript. This led me to dig deep into it and figure out the what, why, and how of the reduce method in JavaScript. After this 4 min read, the one thing that I guarantee you is you’ll be using the reduce method in your code more confidently.</p><h4>So what is it?</h4><p>Mozilla docs define the reduce method as,</p><blockquote>&quot;The <strong>reduce()</strong> method executes a user-supplied “reducer” callback function on each element of the array, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the array is a single value&quot;</blockquote><p>That seems scary at first but let’s simplify this in layman terms. Here’s my definition of it.</p><blockquote>&quot;The <strong>reduce()</strong> method traverses the array from left to right and for each element it calculates the next value given an existing value and a method to calculate the new value. The existing value is the intial value for first iteration and result of previous iteration for all other iterations. It returns the value of the final iteration as the result&quot;</blockquote><p>I hope this one’s clearer. The syntax for the reduce method is,</p><pre>arr.reduce(<br>   (accumulator, currentValue, index, array) =&gt; {}, // <strong>callback function </strong><br>   initialValue <br>)</pre><p>Now that you’ve seen the syntax, let’s break down my definition of the reduce method even further.</p><ul><li>It will traverse through all the elements inside the array just like the map or filter methods.</li><li>It will calculate a value for each iteration based on the method we provide it. Again, same as map or filter methods. This method is what we call the callback function.</li><li>For each iteration, we will get the result of the previous iteration in the callback function. This result will be in the first argument of the callback function, the accumulator.</li><li>In the case of the first iteration, this value will be the initialValue what we provide as a second argument to the reduce method.</li><li>The second argument of the callback function is the current element of the array for which this iteration is going. This again is similar to what we get as the first argument in the callback for the map method.</li><li>The result of the last iteration is what we get out of the reduce method. One thing to pay attention to here is that reduce returns a single value. We get a single value out of the reduce method in JavaScript, unlike the map or filter methods.</li><li>index and array are optional parameters where the index is the index of the current iteration’s element just like the map function and the array is the complete array on which we are using the reduce method.</li></ul><p>Wooh! That was pretty much the what of the reduce method of JavaScript. Pat yourself on the back, you’ve made it till here.</p><p>So now we know what the reduce method is. Let’s see how we can use it to write a neat and clean JavaScript code.</p><h4>Why reduce?</h4><p>We can do refactor a lot of code with our knowledge of the reduce method. Let’s start with a simple example. Let’s suppose we need to find the sum of all elements of an array. Before the knowledge of the reduce method, here’s how I’d have done it.</p><pre>const arr = [1,2,3,4,5];<br>let sum = 0;<br>for (let i = 0; i &lt; arr.length; i++) {<br>     sum += arr[i]; <br>} <br>console.log(sum); // 15</pre><p>But that looks childish. This doesn’t look like a modern-day JavaScript code, it’s a for loop. Here’s how I’m doing it now.</p><pre>const sum = [1,2,3,4,5].reduce((a,c)=&gt;a+c, 0);<br>console.log(sum); // 15</pre><p>Now that looks like JavaScript. Also, notice how in the for loop code we used let for variable sum, but with the reduce method, we can use const.</p><p>Let’s simplify this a bit more. Our callback function is (a,c) =&gt; a+c , which is pretty much straightforward. For every iteration, we add the current element, c of the array to the result of the previous iteration, a. Also, our initial value is 0, that is simply because the sum of no numbers taken is 0.</p><p>Okay so now I know how to get the sum of elements of an array using the reduce method. Let’s take one more step towards reduce and calculate the average of all elements of an array. I’m not telling you the for loop solution to this, because you’re smart enough if you’ve stayed till here. Let’s see the reduce solution to this.</p><pre>[10,20,10,5,5].reduce((a,c,i) =&gt; {<br>     a+=c;<br>     if(i===4) return a/5; <br>     else return a;<br>}); // 10</pre><p>In the above example, I added the current element to the accumulator and then checked whether this is the last iteration. If yes, I returned the sum divided by the size of the array. Else, I’ve returned the sum.</p><p>Here’s a parting tip if you’ve stayed this long. Notice that in the above example I’ve <strong>not given an initial value</strong> to my reduce method. It is an optional parameter and if not provided <strong>the first element of the array is taken as the initial value and iterations start from the second element</strong>.</p><p>That was pretty much about the reduce method in JavaScript. Hope you’ve learned something new today. Do check this space for more JavaScript’y things.</p><p><em>Let the geek inside you win!</em></p><p><em>More content at </em><a href="http://plainenglish.io/"><strong><em>plainenglish.io</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bdc828f368a2" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/lets-deduce-the-reduce-method-in-javascript-bdc828f368a2">Let’s Deduce the Reduce Method in JavaScript</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The JavaScript Nobody Told You About]]></title>
            <link>https://javascript.plainenglish.io/the-javascript-nobody-told-you-about-ac1bf4f56eb9?source=rss-5e7993f1513e------2</link>
            <guid isPermaLink="false">https://medium.com/p/ac1bf4f56eb9</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Shivam Bhasin]]></dc:creator>
            <pubDate>Mon, 25 Oct 2021 18:14:03 GMT</pubDate>
            <atom:updated>2021-10-27T09:01:11.867Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VrsFi6WLoauCsGjagvpXuA.png" /></figure><p>I’ve used JVM languages like Java and Kotlin for most of my college life. Ironically, my first job right after college was as a ReactJS developer. The language that I feared and ran away from in the past 4 years was now in front of me. The reason I was afraid of JavaScript is mostly because of why you’re here too. It’s not easy to understand why it works the way it works.</p><p>Almost 1.5 years down the line, I feel more confident now, and hopefully, you’ll too after reading this. Here I’ve pointed out some mysteries which I’m pretty sure you never thought existed in JavaScript.</p><h4>Falsy values</h4><p>undefined, null, 0, false, NaN, ‘’ are all falsy values. You probably already knew this but did you know that an empty string is false too?</p><p>See below.</p><pre>console.log(&#39;&#39; == false); // true<br>console.log(&#39;&#39; === false); // false</pre><h4>Filter function</h4><p>You must have used the <strong>filter</strong> function a lot on arrays. Here’s a tip if you want to filter falsy values in an array. Just provide <strong>Boolean</strong> inside the filter function.</p><pre>const arr = [1,4,undefined,null,9,NaN,10,&#39;&#39;];<br>console.log(arr.filter(<strong>Boolean</strong>)); // [1,4,9,10]</pre><h4>Sort function</h4><p>What do you know about the <strong>sort</strong> function in JavaScript? It sorts the array, right? Well, not exactly.</p><pre>const arr = [1,2,20,10,8];<br>arr.sort(); // [1, 10, 2, 20, 8]<br>arr.sort((a,b) =&gt; a-b); //[1,2,8,10,20]</pre><p>Output in line 2 above doesn’t look like a sorted array. Why? It’s because when we call the sort method without arguments, JavaScript <strong>converts the elements of the array to string</strong> and then sorts them alphabetically. Crazy? I know.</p><h4>Swapping</h4><p>Many times I had a use case to swap two elements inside an array or just two variables. I used to write a utility function for that but here’s a JavaScript’y way of doing this.</p><pre><strong>Inside arrays<br></strong>let arr = [1,2,3,4,5];<br>[arr[4],arr[0]] = [arr[0],arr[4]];<br>console.log(arr); //[5,2,3,4,1]</pre><pre><strong>Just two variables<br></strong>let a = 10, b = 20;<br>[a,b] = [b,a];<br>console.log(a,b); // 20 10</pre><p>This is the power of <strong>destructuring</strong> in JavaScript. Although I was using destructuring for a long time, never thought of it like this.</p><h4>Trim function</h4><p>In many programming languages, we have a <strong>trim</strong> method on strings that removes any whitespace in the string. But with JavaScript trim doesn’t remove all whitespaces in your string. See below.</p><pre>&quot; shivam bhasin  &quot;.trim(); // &quot;shivam bhasin&quot;<br>&quot;shivam bhasin&quot;.trim(); // &quot;shivam bhasin&quot;</pre><p>It <strong>removes all the leading and trailing whitespaces</strong> from your string but not all. This was confusing for me because of my experience with strings in Java.</p><h4>Push function</h4><p>I use the push method a lot in my code. Though I recently got to know that we can also merge arrays using push.</p><pre>const a = [1,2];<br>const b = [3,4];<br>a.push(b); // [1,2,[3,4]] <strong>not merged</strong><br>Array.prototype.push.apply(a,b); // [1,2,3,4] <strong>merged</strong></pre><p>In line 4 above, the merged array will be in <strong>variable a</strong>.</p><h4>isNaN function</h4><p>isNaN is again one of the most used methods in JavaScript. It checks whether a given argument is a number or not. But it behaves differently for empty strings and filled strings. See below.</p><pre>isNaN(1); // false<br>isNaN(&quot;&quot;); // false<br>isNaN(&quot;a&quot;); // true<br>isNaN(&quot;1&quot;); // false</pre><p>Line 1 is probably clear to you, 1 is a number, hence it returned false. But in line 2, JavaScript treats an <strong>empty string as 0, </strong>which is a number and hence fails the NaN test. Line 3 should also be clear as ‘a’ is a string therefore not a number. Again, in line 4 “1” is a string but JavaScript internally <strong>parses it to a number 1</strong> and hence it fails the NaN test. Weird, right? After knowing this I started using parseInt() on the arguments before passing them to the isNaN function.</p><h4>Dynamic keys to objects</h4><p>Sometimes I had to assign dynamic keys to my objects based on an API response, or some calculation. Here’s how we can do that.</p><pre>const a = &quot;age&quot;;<br>const b = {<br>     name: &#39;shivam&#39;,<br>     [a]: 22, // this will become <strong>age: 22</strong> at runtime<br>};</pre><h4>Splice and Slice</h4><p>After almost 3 months I realized that slice and splice are different methods in JavaScript. Lol, I know. Here’s how they behave differently.</p><pre><strong>slice(s,e);<br></strong>Here s is the starting index and end is the end index of the new array which will be a sub-array of the original array. <strong>Note that the original array will not be changed when using slice.</strong></pre><pre><strong>splice(i,n);<br></strong>Here i denotes the starting index and n denotes the number of items to be removed starting from index i.<strong> Note that splice will alter the original array.</strong></pre><h4>Floating point numbers</h4><p>This one is almost unbelievable but stay with me. The addition of floating numbers behaves very weirdly in JavaScript. See below.</p><pre>console.log(0.1+0.2 === 0.3); // false</pre><p>This is because 0.1+0.2 gives 0.30000000000000004 which is not equal to 0.3. Also,</p><pre>console.log(9007199254740992 + 1); // 9007199254740992  <br>console.log(9007199254740992 + 2); // 9007199254740994</pre><p>This looked weird until I came to know that <strong>all JavaScript numbers are floating points</strong> represented internally in 64-bit binary according to the IEEE 754 standard. You can read more about it <a href="https://2ality.com/2012/04/number-encoding.html">here</a>.</p><h4>typeOf Operator</h4><p>typeOf is a unary operator which returns a string denoting the primitive type of the variable. As we know that JavaScript is mostly objects, so in most cases, this returns object . Here are a few weird exceptions.</p><pre>typeOf NaN; // &#39;number&#39;</pre><p>typeOf NaN is a number that seems weird but NaN is technically a numeric data type. However, it is a numeric data type whose value cannot be represented using actual numbers. See below.</p><pre>const nan1 = 2*&#39;a&#39;; // NaN<br>const nan2 = 4*&#39;b&#39;; // NaN<br>nan1 === nan2; // false</pre><p>In the example above, both nan1 and nan2 are not equal which means they hold some value. It’s just that value can’t be represented in numbers therefore they are NaN. See another exception,</p><pre>typeOf null; // &#39;object&#39;</pre><p>Kudos if you’ve made it here. Most people end up way before this. But the more you know about it the more you realize how the world’s number one programming language works.</p><p>Here’s a parting tip for you.</p><h4>Primitive operations &gt; Methods</h4><p>If you want to make your code even faster, then try to use primitive operations instead of making method calls. Use VanillaJS wherever you can and it will make your code fast during runtime. See below.</p><pre>const min = Math.min(a,b); // slow<br>const min = a&lt;b? a: b; // fast</pre><pre>arr.push(x); // slow<br>arr[arr.length] = x; // fast</pre><p>Hope you’ve learned something new today. Comment down below how many of these you knew already. Also, comment if there’s something you think should be on this list.</p><p><em>Let the geek inside you win!</em></p><p><em>More content at </em><a href="http://plainenglish.io/"><strong><em>plainenglish.io</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ac1bf4f56eb9" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/the-javascript-nobody-told-you-about-ac1bf4f56eb9">The JavaScript Nobody Told You About</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TypeScript — JavaScript with no surprises]]></title>
            <link>https://javascript.plainenglish.io/typescript-javascript-with-no-surprises-bbc4cf5c23a6?source=rss-5e7993f1513e------2</link>
            <guid isPermaLink="false">https://medium.com/p/bbc4cf5c23a6</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Shivam Bhasin]]></dc:creator>
            <pubDate>Sat, 15 May 2021 18:41:36 GMT</pubDate>
            <atom:updated>2021-05-19T07:20:30.157Z</atom:updated>
            <content:encoded><![CDATA[<h3>TypeScript — JavaScript with No Surprises</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e1kRPupIPsi6F2F84AttNw.png" /></figure><p>Yes,<strong> TypeScript is like JavaScript but with no surprises. </strong>That’s how I describe the open-source programming language introduced by Microsoft in 2012. Last year, Github marked it among the top 10 most wanted programming languages. But why are developers preferring Microsoft’s creation more than JavaScript? Let’s find out!</p><h3>Why not JavaScript?</h3><p>JavaScript has been the number one language for many years now. It changed web development completely by giving lives to previously dead websites. Thanks to the many frameworks around it, it is used for backend and mobile application development too.</p><p>But was JavaScript made to create enterprise-level applications? I hardly think so. That’s where TypeScript steps in. <strong>TypeScript is JavaScript with static typing</strong>. And the best part is it’s still optional. There are a lot of benefits of adding static typing to JavaScript. You’ll not see that undefined pop up in your applications anymore. Refactoring code will not be a nightmare anymore. And many more. A study shows that 15% of JavaScript bugs can be detected by TypeScript.</p><h3>Types — The difference between JS and TS</h3><p>Programming languages fall into two categories: statically typed or dynamically typed.</p><p>Consider the following code snippet of JavaScript — A dynamically typed language like Python:</p><pre>function add(num){<br>   console.log(num + 5);<br>}</pre><p>Here, the type of variable num is not known. If I call this with, add(“I love TS”) it will print I love TS5. This is known as Type Coercion in JavaScript. It will convert the number 5 to its string equivalent and concatenate both of’em. The problem is that it doesn’t throw an error even though it is not working as intended.</p><p>Now consider the same function in TypeScript — A statically typed language like Java:</p><pre>function add(num: number){<br>   console.log(num + 5);<br>}</pre><p>We just added the type of variable num as a number. If I call add(“I love TS”) now, it’ll throw a compilation error — <strong>Argument of type </strong><strong>string is not assignable to parameter of type </strong><strong>number</strong> .</p><h4>Benefits of Static Typing</h4><ul><li>It allows us to save time and check why our input is not of the type we think it is instantly rather than spending time later.</li><li>Everything stays the way it was initially intended. If a variable is declared as a string, it’ll remain the string the entire time.</li><li>Adding strict types makes code more readable. A code that speaks for itself can offset the lack of direct communication between team members.</li><li>Information about types lets IDEs help us with code navigation, autocompletion, and accurate suggestions. We also get feedback while typing. All this helps us write maintainable code and results in a significant productivity boost.</li></ul><h3>TypeScript — Working BTS</h3><p>Every device, browser, or platform that runs JavaScript can run TypeScript as well. This is because the TypeScript code is compiled to vanilla JS before executing by <strong>tsc — TypeScriptCompiler</strong>. IDEs supporting TypeScript usually have this built-in and can be invoked from the command line. It allows converting the codebase or a part of it by adding tsconfig.json to the root directory.</p><p>TypeScript is not delivered as .ts files but as .js and .d.ts files. Given a TypeScript file, main.ts tsc can convert it to several artifacts. The most common ones are:</p><ul><li>JavaScript file: main.js (It contains vanilla js code generated by our ts code)</li><li>Declaration file: main.d.ts (This file have the type information)</li><li>Source map file: main.js.map (It specifies for each part of the output code in main.js , which part of the input code in main.ts produced it)</li></ul><h3>Brief about TypeScript Compiler</h3><p>The TypeScript compiler can also process vanilla JavaScript code by using option allowsJs . So when migrating from JavaScript to TypeScript, we can start with a mix of both and slowly convert more JavaScript code to TypeScript.</p><p>It allows us to type-check JavaScript files by using checkJs for the complete codebase or putting @ts-check as a comment on particular files.</p><p>It uses static type information provided by JSDoc comments. In fact, we can fully statically type JavaScript code and can even derive declaration files from them. A simple JSDoc comment example can be:</p><pre>/**<br> * @param {number} x - A number param.<br> * @returns {number} This is the result.<br> */<br>function add(num){<br>   return num + 5;<br>}</pre><h3>Cons of TypeScript</h3><p>Honestly, there are very few of them that came to my notice. But here are some that I think might be of help to you:</p><ul><li><strong>Not true static typing</strong> — Static typing in TypeScript is different than Java, C++, or C#. Our code is eventually transpiled to JavaScript, so there is always the risk of weird type conversions at runtime.</li><li><strong>Bloated code</strong> — We will have to write more code as types that can slow down the development process. Also, it makes TS files larger in size than JS because of the extra lines of code. But all this disappears after being transpiled. In the end, the browser will execute plain JavaScript.</li><li><strong>Extra compilation step</strong> — We need to transpile TypeScript code to JavaScript before running. However, this process is highly automated and doesn&#39;t require a lot of additional time. In short, the downside of this step is far less significant than its benefits.</li></ul><h3>Who is TypeScripting?</h3><p>TypeScript is an open-source programming language with an ever-growing community. It was created by Microsoft and is now used by Asana, Slack, Lyft, all Angular 2+ developers, multiple React and Vue developers, and thousands of other companies. It is undoubtedly the most popular superset of JavaScript at the moment and is not going anytime soon.</p><p>With new updates coming in TypeScript, the <strong>main idea behind is to bring productivity, reliability, and predictability to a chaotic JavaScript world</strong>. Honestly, I’m keen to hear reasons for not using TypeScript now.</p><p>Let’s start TypeScripting coders!</p><p><em>More content at </em><a href="http://plainenglish.io/"><em>plainenglish.io</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bbc4cf5c23a6" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/typescript-javascript-with-no-surprises-bbc4cf5c23a6">TypeScript — JavaScript with no surprises</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cryptocurrency for a 10-year-old]]></title>
            <link>https://medium.com/geekculture/cryptocurrency-for-a-10-year-old-e0f28d2ee08?source=rss-5e7993f1513e------2</link>
            <guid isPermaLink="false">https://medium.com/p/e0f28d2ee08</guid>
            <category><![CDATA[cryptocurrency]]></category>
            <category><![CDATA[investing]]></category>
            <category><![CDATA[dogecoin]]></category>
            <category><![CDATA[finance]]></category>
            <category><![CDATA[bitcoin]]></category>
            <dc:creator><![CDATA[Shivam Bhasin]]></dc:creator>
            <pubDate>Mon, 26 Apr 2021 05:26:52 GMT</pubDate>
            <atom:updated>2021-05-11T20:45:50.889Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/625/1*3us2iiKwcqjEirRieoBL8g.jpeg" /></figure><p>Complex terms like crypto or bitcoin are some of the highest-searched words on google these days. I heard of these the very first time back in my first year of engineering. Here I’ve simplified my 5 years of understanding crypto in a 5 min story.</p><p><strong>Why has crypto gained popularity recently? What has happened? </strong>The answer is <strong>Covid-19</strong> happened. In the past few months, people have seen <strong>inflation </strong>too closely. They understood that the value of money will degrade over time and putting money in assets is the real game. Earlier people used to invest in gold, stocks, and real estate, but now when the equity market is at its peak and real estate is not giving much return, everyone sees crypto as a good investment opportunity. In fact, not only people, but big companies like Tesla and Paypal have also<strong> put their cash reserves in Bitcoin.</strong></p><p>Crypto is also a good option for our portfolio diversification. Let’s say I have 100 rupees to invest, I’ll put some in mutual funds, some in the equity market, maybe some in real estate, but some of it may be just 10 rs, will definitely go to crypto. By diversifying my investment I’ll be able to cover any net losses. I’ll in fact diversify those 10 rs too in <strong>Bitcoin</strong>, <strong>Ethereum, </strong>and maybe some unpopular ones like <strong>Basic Attention Token(BAT) </strong>or <strong>Dogecoin </strong>in some ratio.</p><h3>What is crypto?</h3><p>Imagine that you have to pay me a hundred rupees today. How would you do it? Of course, you can send me cash but if that’s not an option you’ll have to somehow transact that money through your bank account to mine. Now, see how we need middlemen(banks) to do this transaction for us. We’re kind of dependent on banks and have trusted them with our money. But do we have complete transparency on how they operate? Can we trust them? We did see what happened with banks recently.</p><p>Now, imagine a world where we don’t need these middlemen. This exchange of value(money in our case) can be done online straight from one person to another without anyone in the midst. And this happens in an absolutely <strong>transparent </strong>way. In fact, the whole <strong>record is public</strong>. I got this outline from Investopedia-</p><p>”A <strong>cryptocurrency</strong> is a digital or virtual currency that is secured by cryptography, which makes it nearly impossible to counterfeit or double-spend. Many <strong>cryptocurrencies</strong> are decentralized networks based on blockchain technology — a distributed ledger enforced by a disparate network of computers.”</p><p>If you send me x bitcoins right now, transaction data will be stored in the public ledger online and anyone on this planet will be able to see that a transaction of x bitcoins issued at a timestamp between two individuals. Obviously, our identities will not be revealed but a public record would be stored.</p><p>Now imagine all transactions in the world using crypto. So that every record is publicly stored and available for anyone to see and check, making the system completely transparent.</p><h3>Where did it come from?</h3><p>Companies like Facebook, Google, and Amazon hold the personal data of almost everyone on this planet. They are apparently using it for advertisements as of now. But are we sure that they, are, or maybe, will not use it to manipulate us? That led <strong>Satoshi Nakamoto, </strong>in 2009, to see the need for a decentralized way of exchanging value. A place where everything is up on the internet for anyone to see. That led him to invent <strong>Bitcoin, the first cryptocurrency ever.</strong></p><p>Now <strong>blockchain </strong>is a chain of blocks where every block holds some piece of data within it. But how is a new block added to the blockchain? There has to be a way to decide. When we are talking about a decentralized way, where we don’t need banks, some communities have come up controlling this addition to the block. So when we have a new block of data to be added to the blockchain, that’s where <strong>mining is required</strong>.</p><p><strong>What is mining? </strong>It is solving a complex mathematical puzzle that is needed to add a new block to the blockchain. Earlier these puzzles were solved on mobile phones and laptops but as the system has grown over time, we need powerful machines to solve these. There are around <strong>21 million bitcoin</strong>s that can be mined and right now we are somewhere near <strong>19</strong> <strong>million</strong>. It is said that by the year 2140 all the bitcoins will be mined.</p><p>After all the bitcoins are mined, people will still be able to participate in the transactions but there will not be any more of them coming into the system. And with every transaction, like if you send bitcoin to me, then <strong>we’ll have to pay the miner some fee</strong>.</p><p>I wish I could’ve mined bitcoins but it’s not in my plans anytime soon. Though there are<strong> mine pools</strong>, where we can just give our machines to be used for mining. Some miners are mining it using solar energy, or wind energy, everyone is trying their best to mine these, just like how <strong>earlier people used to mine gold in gold mines</strong>.</p><h3><strong>Future of Crypto</strong></h3><p>We can use this new technology to create more transparent and decentralized financial systems, also know as <strong>De-Fi</strong>. Now there are a lot of problems with the current one. They still use the oldest technology… people sitting in the village don’t have access to credits. But with crypto coming in, the world will get even more connected, lending and borrowing will get better. And blockchain doesn’t distinguish between people. Banks will prefer high-value customers because they are going to provide the best returns. But <strong>blockchain is a technology, it is coded, and the algorithm</strong> doesn’t know the difference between someone in a village and in a city.</p><p>Hopefully, the financial systems in the world will get more evolved in the upcoming years, a world where people are more connected financially too as they are connected socially right now. Also, don’t take my words for investing money in any crypto. I’ve invested in it but <strong>you should do your own research too before putting your money in it</strong>. Let me know in the comments if you’d like more investment advice around crypto and I’d be more than happy to write about it.</p><p>Until next time, VISITOR!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e0f28d2ee08" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/cryptocurrency-for-a-10-year-old-e0f28d2ee08">Cryptocurrency for a 10-year-old</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>