<?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[Skay's Blog]]></title><description><![CDATA[A Full-stack engineer meets a product manager. I build products & publish articles on technologies such as HTML5, CSS3, JavaScript, ReactJS, Java Spring, PostgreSQL, MongoDB, Docker & Kubernetes]]></description><link>https://blog.skay.dev</link><generator>RSS for Node</generator><lastBuildDate>Mon, 13 Apr 2026 21:39:14 GMT</lastBuildDate><atom:link href="https://blog.skay.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[What is Technical Debt?]]></title><description><![CDATA[What is Technical Debt?
I would like to simply define Technical debt as the actions taken by the engineering team to expedite delivery for a piece of functionality that often needs to be refactored at a later point in time. However, there's no one si...]]></description><link>https://blog.skay.dev/what-is-technical-debt</link><guid isPermaLink="true">https://blog.skay.dev/what-is-technical-debt</guid><category><![CDATA[100DaysOfCode]]></category><category><![CDATA[Startups]]></category><category><![CDATA[General Programming]]></category><dc:creator><![CDATA[Skay]]></dc:creator><pubDate>Sat, 28 Nov 2020 00:00:31 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1606521032040/Y1ZFRtd6f.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="what-is-technical-debt">What is Technical Debt?</h2>
<p>I would like to simply define Technical debt as the actions taken by the engineering team to expedite delivery for a piece of functionality that often needs to be refactored at a later point in time. However, there's no one single definition that exists technically.</p>
<p>The term 'Technical debt' was originally coined by software developer, 'Ward Cunningham'. He had coined this term to explain to Non-Technical stakeholders why budgeting needs to be allocated for refactoring.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1606521297991/DDb2mzWe5.jpeg" alt="cytonn-photography-n95VMLxqM2I-unsplash.jpg" /></p>
<p>Cunningham's explanation to the stakeholders was along the following lines:</p>
<p>"With borrowed money, you can do something sooner than you might otherwise, but then until you pay back that money you’ll be paying interest. I thought borrowing money was a good idea, I thought that rushing software out the door to get some experience with it was a good idea, but that of course, you would eventually go back and as you learned things about that software you would repay that loan by refactoring the program to reflect your experience as you acquired it."</p>
<h2 id="why-technical-debt-is-necessary">Why Technical Debt is necessary?</h2>
<p>Typically an early-stage startup needs to validate their product idea first and ensure they can sign up customers rather than build out all the nuts n bolts of the feature. In order to do that, agility is of paramount importance. The engineering team deliberately incurs tech debt to reduce the time to market.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1606521308884/uWbqm--8b.jpeg" alt="micheile-henderson-SoT4-mZhyhE-unsplash.jpg" /></p>
<p>However, often companies have known to abuse this term and prescribe, “Hack it, for now, fix it later” mantra to ship the project fast and acquire more users than their competition. But, often they don't realize that having technical debt has its consequences. Before we dive into that, let us find out the various types of technical debt that exists and how to address them.</p>
<h2 id="types-of-technical-debt">Types of Technical Debt</h2>
<p>While you can categorize technical debt into more granular level such as code debt, design debt, infrastructure debt, testing debt, etc. I would broadly want to classify them into the following categories:</p>
<h3 id="planned-technical-debt">Planned Technical Debt</h3>
<p>As explained above, it is a decision made by the engineering team to take a short-cut for shipping the feature faster.</p>
<h4 id="how-to-address-them">How to address them?</h4>
<p>The tech leads/managers must ensure to track the tech debt in the backlog and address them as the product grows. The Product &amp; Sales team must be made aware of the consequences of not addressing them in a timely manner and everyone should be held accountable to ensure that the tech debt is addressed in a timely manner.</p>
<h3 id="unintentional-technical-debt">Unintentional Technical Debt</h3>
<p>This occurs generally due to the lack of understanding of the product or poor communication that exists in the translation of business goals or simply poor engineering practices.</p>
<h4 id="how-to-address-them">How to address them?</h4>
<p>Retrospectives are necessary no matter how fast a project needs to build. It is imperative to reflect back to find out what went well &amp; what needs to change. Tech leads/managers must involve themselves in understanding the true business objectives and the product team must keep validating the software being built and provide feedback incrementally.</p>
<h3 id="unavoidable-technical-debt">Unavoidable Technical Debt</h3>
<p>When there's a huge change in project scope or a complete pivot of technology choice during mid-project, it leads to unavoidable technical debt. </p>
<h4 id="how-to-address-them">How to address them?</h4>
<p>Typically, this is the hardest of them all and usually, the debt is paid back in phases. For e.g. mid-project, the engineering team decides to move from React to Vue. The way to do this would be to create new features for the project in Vue and migrate the existing features from React to Vue in phases.</p>
<h2 id="is-technical-debt-bad">Is Technical Debt bad?</h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1606521458922/V1MhB3s-1.jpeg" alt="ayo-ogunseinde-sibVwORYqs0-unsplash.jpg" /></p>
<p>It's yes and no based on which point in software development you view it. For example, at an early stage, having a technical debt is considered a good thing to ship your product faster to the hands of the end-users. However, as the product matures, it is important to pay back the debt to ensure the product is stable and can actually scale as more and more users start adopting the product.</p>
<p>One important thing to acknowledge is that Technical debt unlike Financial debt is much harder to detect and people generally tend to ignore it unless it really becomes a problem. It is important to have the consequences of technical debt explained to all stakeholders and ensure that the responsibility and accountability is shared between the engineering and product teams.</p>
<h2 id="conclusion">Conclusion</h2>
<p>To summarize, technical debt can be described as the consequences of software development actions that intentionally or unintentionally prioritize client value and/or project constraints such as delivery deadlines, over more technical implementation, and design considerations.</p>
<p>Technical debt should not be confused with the mess. A mess is a just mess that is being created based on laziness and unprofessionalism and has no chance of payback in the future.</p>
<p>I hope you enjoyed the article. Please don't forget to subscribe to my newsletter and connect with me on Twitter <a target="_blank" href="https://twitter.com/skay_tech">@skaytech</a></p>
<h3 id="you-may-also-enjoy-the-following-articles">You may also enjoy the following articles:</h3>
<ul>
<li><a target="_blank" href="https://blog.skay.dev/why-you-should-choose-to-learn-react">Why you should learn 'React'?</a></li>
<li><a target="_blank" href="https://blog.skay.dev/the-react-ecosystem">The React Ecosystem</a></li>
<li><a target="_blank" href="https://blog.skay.dev/asyncawait-in-javascript-explained">Async/Await explained in JavaScript</a></li>
<li><a target="_blank" href="https://blog.skay.dev/what-are-javascript-promises">What are JavaScript Promises</a></li>
<li><a target="_blank" href="https://blog.skay.dev/javascript-callbacks-explained">JavaScript Callbacks Explained</a></li>
<li><a target="_blank" href="https://blog.skay.dev/all-you-need-to-about-javascript-objects">Everything you need to know about JavaScript Objects</a></li>
<li><a target="_blank" href="https://blog.skay.dev/javascript-functions-everything-you-must-know-as-a-javascript-newbie">Everything you need to know about JavaScript Funtions</a></li>
<li><a target="_blank" href="https://blog.skay.dev/es6-higher-order-functions">ES6 - Higher Order Functions</a></li>
<li><a target="_blank" href="https://blog.skay.dev/es6-spread-operator">ES6 - Spread Operator</a></li>
<li><a target="_blank" href="https://blog.skay.dev/es6-understanding-destructuring">ES6 - Understanding Destructuring</a></li>
<li><a target="_blank" href="https://blog.skay.dev/es6-arrow-functions">ES6 - Arrow Functions</a></li>
<li><a target="_blank" href="https://blog.skay.dev/what-is-currying-in-javascript">What is Currying in JavaScript?</a></li>
<li><a target="_blank" href="https://blog.skay.dev/understanding-hoisting">Understanding Hoisting</a></li>
<li><a target="_blank" href="https://blog.skay.dev/introduction-to-big-o-notation-time-space-complexity">Introduction to Big O Notation, Time &amp; Space Complexity</a></li>
</ul>
]]></content:encoded></item><item><title><![CDATA[How to provide estimates as a Junior Developer?]]></title><description><![CDATA[Introduction
I recently interacted with a friend who had just started out as a developer and she told me that she found it really hard to provide estimates against the user stories assigned to her.
We had an interesting conversation following that an...]]></description><link>https://blog.skay.dev/how-to-provide-estimates-as-a-junior-developer</link><guid isPermaLink="true">https://blog.skay.dev/how-to-provide-estimates-as-a-junior-developer</guid><category><![CDATA[General Programming]]></category><category><![CDATA[General Advice]]></category><category><![CDATA[100DaysOfCode]]></category><dc:creator><![CDATA[Skay]]></dc:creator><pubDate>Fri, 13 Nov 2020 06:07:15 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1605246434557/jRo6pd1-I.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="introduction">Introduction</h2>
<p>I recently interacted with a friend who had just started out as a developer and she told me that she found it really hard to provide estimates against the user stories assigned to her.</p>
<p>We had an interesting conversation following that and I thought this might actually be applicable not just to her, but, a much wider audience who might be going through the same thing.</p>
<p>In this article, I will provide my thoughts on how you can go about providing estimates when you start out as a new (junior) developer. </p>
<p>Please do note that the article is in NO way "the only" way to provide estimates and it may largely vary based on the project. This is merely some things to consider that can help you provide estimates and manage insecurities that arise while providing them as a new developer.</p>
<h2 id="estimation">Estimation</h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1605246551306/OdlqsAuPN.png" alt="2-Estimate.png" /></p>
<p>One of the first things to understand whether you are a junior or a senior developer is that the word 'Estimation' means it's a 'ballpark', i.e., it is not supposed to be exact. Providing the amount of time to complete a task largely varies based on a number of factors such as your current skill level, your overall experience in the field to understand requirements, whether you are building something ground up vs adding functionality to an existing product, etc.</p>
<p>For example, let's assume you have joined a project which has a fairly large codebase. When you are asked to estimate for a feature, your first instinct would be to provide estimates for the time it takes to complete building out the feature. However, what is often 'untold' is the fact, you'll also need to include time in your estimates to perform 'impact analysis', i.e., performing analysis to ensure that the code you add does not impact any other existing functionality. Ensuring that you consider providing estimates for things that are untold requires some amount of experience and hence it is always recommended to have a senior review your estimates before providing them to the lead or manager.</p>
<h2 id="key-terminologies">Key Terminologies</h2>
<p>I'm providing a list of key things that are commonly used with the Agile development workflow.</p>
<h3 id="user-story">User Story</h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1605246705912/3Mb9XJiCO.jpeg" alt="linkedin-sales-navigator-4rvBjoQWERk-unsplash.jpg" /></p>
<p>In an Agile process, a feature would be written in terms of a user story, i.e., what the feature means to the end-user. Generally, user stories will be worded like 'As a user, I should be able to do this, to meet a particular outcome'. A good user story should have the acceptance criteria clearly specified that should help you and others identify what are the things that need to be verified to mark the user story completed.</p>
<p>Every user story is sized based on the complexity level and 'T-Shirt' sizing is a common methodology followed in the industry. Every user story is marked with a sizing such as XS, S, M, L, XL based on the level of complexity. The sizing will most likely be provided by the senior members of the team, since, they understand the product and are generally more experienced with the software. As a junior developer, you will be required to break down the user story into smaller tasks and estimate them.</p>
<h3 id="scope">Scope</h3>
<p>Scope can simply be explained as the agreed set of things that need to be developed as a part of the user story. Usually, during the development process, things might arise which have not been explicitly stated in the user story and it is important to call them out and notify your senior in the team. </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1605246801437/Mz6TInPvQ.jpeg" alt="austin-distel-rxpThOwuVgE-unsplash.jpg" /></p>
<p>Most likely that might get added to the current story or if the impact is much larger, a new story might get created to address that. However, the important thing to note is that, if you have to develop that as a part of the same user story, your initial estimates will get impacted. </p>
<p>This is something tough to spot for a new developer and a good lead should explain this and guide you on how to handle scope creep.</p>
<h3 id="velocity">Velocity</h3>
<p>The term 'Velocity' is used to measure how fast a developer can complete the user story assigned to them. The same user story might take 4 hours for a senior developer to complete, but can take up to, 2 days for a junior developer to complete.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1605246851284/EJgKjtuQH.jpeg" alt="mark-tuzman-kwXwZxKVgao-unsplash.jpg" /></p>
<p>You must understand that it is completely 'normal' and you must feel free to communicate with your seniors about how you feel and ask them for any specific directions/guidelines they recommend for providing estimates.</p>
<p>Imposter Syndrome is a big thing to tackle at this point and your ego might also take a hit sometimes. Acknowledge that and keep telling yourself that this is a learning phase and it's just a matter of time before you will have command over the product and technology.</p>
<h3 id="capacity">Capacity</h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1605247105228/lbSGV5EBU.jpeg" alt="peter-feghali-HJpISHFSkJo-unsplash.jpg" /></p>
<p>This one is relatively simple. Capacity planning is done before the beginning of the sprint to find out if the developers are on any planned vacation. You may ask, how does this change the estimates? While in most cases it does not. However, if your vacation duration is a week or more, you must ensure that you reach out to the team after you come back and find out if something has changed that might impact your coding before your break. Also, it usually takes a day to build context and get back to that 'work mindset' after a relaxing holiday 🙂</p>
<h2 id="general-guidelines-for-estimation">General Guidelines for Estimation</h2>
<p>I would recommend the following steps for providing estimates when you are starting out as a new developer:</p>
<ol>
<li>Break down the task into the most fundamental thing. For example, building the Home page of the application can be broken up into building individual components on the homepage.</li>
<li>Spend some time to understand if there are any more questions to clarify the requirement or things to be called out at this stage that will impact the estimation. </li>
<li>Think through the corner cases (not just the happy path ones) and find out if they'll impact your estimates in any way.</li>
<li>Add estimates in hours against each task.</li>
<li>Your estimates must include time to write unit tests.</li>
<li>Review your estimates with a senior developer and take notes of the feedback provided by the senior developer.</li>
</ol>
<p>Even after this, it might be possible, you might take additional time to complete the task and that is perfectly normal. But, it is important to record how much more additional time you've spent as compared to the original estimates. This is 'super important' because, it's a big learning for yourself and your team on where your current skill/understanding level is, and in due time this number will improve as you gain more expertise in the project.</p>
<h2 id="conclusion">Conclusion</h2>
<p>While it can be daunting and stressful as a junior developer while providing estimates in the beginning, remember in due time you'll gain expertise and knowledge about the project and your estimation will start to get much better.</p>
<p>A good project manager or a lead would constantly gather statistics regarding your estimates and provide you with constant feedback on how to improve them. As your productivity improves, they'll be aware of that and keep sending more work your way.</p>
<p>I sincerely hope this article helped you with some knowledge of providing software estimates as a developer who is just starting out in the industry.</p>
<p>Don't forget to subscribe to my newsletter and connect with me on Twitter <a target="_blank" href="https://twitter.com/skay_tech">@skaytech</a></p>
<h3 id="you-may-also-like-the-following-articles">You may also like the following articles:</h3>
<ul>
<li><a target="_blank" href="https://blog.skay.dev/hiring-software-engineers-for-startups-an-engineering-managers-perspective">Hiring Software Engineers for Startups - An Engineering Manager's view</a></li>
<li><a target="_blank" href="https://blog.skay.dev/why-do-you-want-to-work-for-us-interview-question-demystified">Why do you want to work for us?</a></li>
<li><a target="_blank" href="https://blog.skay.dev/evaluate-product-marketfit">How to evaluate your idea for Product Market Fitment</a></li>
<li><a target="_blank" href="https://blog.skay.dev/what-is-value-proposition">What is Value Proposition?</a></li>
<li><a target="_blank" href="https://blog.skay.dev/5-must-read-tips-to-write-a-killer-blog-article">5 Must-Read Tips for a Killer Blog Article</a></li>
<li><a target="_blank" href="https://blog.skay.dev/history-of-ecma-es5-es6-and-beyond">History of ECMAScript and Beyond</a></li>
<li><a target="_blank" href="https://blog.skay.dev/guide-organised-and-productive">A Practical Guide to help you stay more organized and productive</a></li>
<li><a target="_blank" href="https://blog.skay.dev/what-is-this-in-javascript">What is 'this' in JavaScript?</a></li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Why work at a Startup and What to expect?]]></title><description><![CDATA[Introduction
This is an article based on my experience working with startups for 4+ years. I have previously worked with enterprises and product companies, but with startups, the kind of unique experience of having both creative freedom and increased...]]></description><link>https://blog.skay.dev/why-work-at-a-startup-and-what-to-expect</link><guid isPermaLink="true">https://blog.skay.dev/why-work-at-a-startup-and-what-to-expect</guid><dc:creator><![CDATA[Skay]]></dc:creator><pubDate>Thu, 05 Nov 2020 10:33:36 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1604571915740/DU4Qv0EZa.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="introduction">Introduction</h2>
<p>This is an article based on my experience working with startups for 4+ years. I have previously worked with enterprises and product companies, but with startups, the kind of unique experience of having both creative freedom and increased responsibility was probably the most fulfilling in my career.</p>
<p>While startup culture is often glamorized with a whole lot of cool-looking offices, young vibrant engineers, there are a lot of challenges that are important to be prepared for.</p>
<p>In this article, I will share my experiences on why you should consider working at a startup and what to expect while working with startups.</p>
<h2 id="why-work-with-startups">Why work with Startups?</h2>
<h3 id="creative-freedom">Creative Freedom</h3>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1604570619554/bJzWEiZLF.jpeg" alt="joshua-coleman-uB16HY_ah4o-unsplash.jpg" /></p>
<p>I think the best way to explain this in a single phrase would be 'If you can do it, you can lead it'. Startups are generally known for having small teams and while this may mean that your workload increases, it also offers creative freedom. You can shape your job description by simply raising your hand or offering a solution.</p>
<p>For example, while you might have been hired to do a developer job, you can still jump into your areas of interest such as design or documentation, and lead the way if there's an opportunity. </p>
<h3 id="career-development">Career Development</h3>
<p>With startups, there aren't layers of management to weed through, so if you started off taking up a particular role and you realized that your skills probably suit a different role in the team, you have the freedom to explore such a thing and slowly turn that into your career.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1604570723898/TfgOR760P.jpeg" alt="hunters-race-MYbhN8KaaEc-unsplash.jpg" /></p>
<p>There's a significant gap even today on what a university teaches and what skills are needed on a real job and the option to explore your career within a job is very liberating.</p>
<h3 id="develop-resiliency">Develop Resiliency</h3>
<p>This one is my personal favorite. As humans, we have been in-built with a mechanism to resist failure. However, failure is essential to any kind of growth. In startups, you are burning your hands constantly. Everyone fails, and it's considered fine. Oftentimes there are no wrong answers and some solution that’s more correct than another one may well emerge as the winning formula. However, failure will not only make you a seasoned professional with hands-on learning but a resilient individual.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1604570804771/q1-lX-nCW.jpeg" alt="gmb-fitness-NYCVycvTbek-unsplash.jpg" /></p>
<p>If you join a healthy startup, you’ll see the commitment and conviction of founders, and the team will hold onto each other – celebrating success together and taking failure in collective stride. As a result, you’ll become a problem solver, think outside the box, and build your ability to find creative solutions to problems, solutions that have the potential to move the needle significantly.</p>
<h3 id="a-unified-feeling-and-connecting-over-the-mission">A Unified feeling and connecting over the mission</h3>
<p>A startup team works shoulder-to-shoulder. You’ll spend a lot of hours collaborating with the same few people. Startup culture is very very important and the team will have to be a network of like-minded people who have the same agenda. This is super important because the emotional connection towards a unified cause increases your resolve and you'll push each other to grow and in return create long-lasting friendships out of the understanding.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1604571627411/W6-a_eB45.jpeg" alt="spacex-YSvUYqf9Mjk-unsplash.jpg" /></p>
<p>While the above are certainly some of the reasons why you should try to work for a startup, I'll also want to mention a few points on what to expect while working with startups.</p>
<h2 id="what-to-expect-while-working-with-startups">What to expect while working with Startups?</h2>
<h3 id="be-comfortable-with-uncertainty">Be comfortable with uncertainty</h3>
<p>You'll need to embrace uncertainty as much as the fish would take to the water or at least 80% of it. It is not easy for everyone to embrace uncertainly. Not at least at first, but, ensuring you communicate to the team certainly relives pressure from self and also ensures that everyone understands that you are charting unknown waters.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1604570970663/xg_pYQQ76.jpeg" alt="luke-stackpoole-M5q1m4n9ES8-unsplash.jpg" /></p>
<p>You'll be encountered with questions that no one has the answers to, even the founders, but this is what makes a startup so special – you’re finding out together. Once you are through one such an experience, you would have learned a life skill of navigating through uncertainty.</p>
<h3 id="be-independent-and-a-team-player">Be Independent and a team player</h3>
<p>While a healthy startup culture will rally the team together, understand how to structure your work. Let yourself be pushed outside of your comfort zone. At a startup, there is little traditional ‘management’. You’ll need to be a self-starter and know how to manage your time.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1604571185579/xra0Rqt_d.jpeg" alt="giorgio-trovato-iP4Ju2-4paQ-unsplash.jpg" /></p>
<p>There will be days when it feels like a lot; stay motivated. You’re growing. Structuring how you spent your time and proactively checking in with your manager to ensure your Key Performance Indicators (KPIs) remain aligned will help you stay on course and feel connected. Know when to ask for help and communicate with your team. Use your team as support and as a pillar of strength. I promise whatever you’re feeling you’re not alone, and reaching out will only help everyone involved.</p>
<h3 id="find-your-sparkle">Find your Sparkle</h3>
<p>Self-doubt can be an outcome of all-round rapid development. Focus on the larger goal and your part in it. Ask where you shine. Sometimes we can’t see our own sparkle. Again, with little traditional ‘management’ the standard review process most likely won’t exist the way it does at large, established companies.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1604571235892/K_mfweMvn.jpeg" alt="dawid-zawila-E9b5kcgCR9Y-unsplash.jpg" /></p>
<p>Ask for the time you need, but be sure to ask for clear feedback. Reflect on your KPIs to make sure that your goals are well aligned with the company. Everyone is low on resources and time is the most important, so be specific where you need support and take ownership of your projects.</p>
<h3 id="enjoy-the-ride">Enjoy the ride</h3>
<p>There may be frequent spurts of feedback and periods with none at all. Write it down and keep it for later. Time moves FAST in a startup. Make sure that you remember to write down all the lessons you learn because they will be vast. Keep a journal to remember what you did well, what you learned, and to keep the memories.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1604571281469/jdTcMoWIs.jpeg" alt="josh-hild-JYQkVLOPy8U-unsplash.jpg" /></p>
<p>One of the startup customers I had worked with, Carlos, who's currently an Engineer Manager at Google, is still my close friend and I remember the fights, arguments, laughter, and euphoric moments that we celebrated together while taking an idea from concept to launch. It is still one of my most fond memories of my career.</p>
<h3 id="conclusion">Conclusion</h3>
<p>To summarize while working in a startup has its challenges, it also is equally rewarding in terms of experience. Not everyone likes it or is up for a challenge as steep as working for a startup. But, I would urge you to consider working with a startup at least once in your career. </p>
<p>I hope you enjoyed the article. Don't forget to subscribe to my newsletter and connect with me on Twitter <a target="_blank" href="https://twitter.com/skay_tech">@skaytech</a></p>
<h3 id="you-may-also-like-the-following-articles">You may also like the following articles:</h3>
<ul>
<li><a target="_blank" href="https://blog.skay.dev/hiring-software-engineers-for-startups-an-engineering-managers-perspective">Hiring Software Engineers for Startups - An Engineering Manager's view</a></li>
<li><a target="_blank" href="https://blog.skay.dev/why-do-you-want-to-work-for-us-interview-question-demystified">Why do you want to work for us?</a></li>
<li><a target="_blank" href="https://blog.skay.dev/evaluate-product-marketfit">How to evaluate your idea for Product Market Fitment</a></li>
<li><a target="_blank" href="https://blog.skay.dev/what-is-value-proposition">What is Value Proposition?</a></li>
<li><a target="_blank" href="https://blog.skay.dev/5-must-read-tips-to-write-a-killer-blog-article">5 Must-Read Tips for a Killer Blog Article</a></li>
<li><a target="_blank" href="https://blog.skay.dev/history-of-ecma-es5-es6-and-beyond">History of ECMAScript and Beyond</a></li>
<li><a target="_blank" href="https://blog.skay.dev/guide-organised-and-productive">A Practical Guide to help you stay more organized and productive</a></li>
<li><a target="_blank" href="https://blog.skay.dev/what-is-this-in-javascript">What is 'this' in JavaScript?</a></li>
</ul>
]]></content:encoded></item><item><title><![CDATA[A Detailed overview of NPM, Registry, CLI & it's related Components]]></title><description><![CDATA[Introduction
In this article, we will look at an overview of what NPM is. When we usually run 'npm install', we know that certain packages are being created inside the 'node_modules' folder. Let us look at what they mean and what role they play in or...]]></description><link>https://blog.skay.dev/overview-of-npm-node-package-manager</link><guid isPermaLink="true">https://blog.skay.dev/overview-of-npm-node-package-manager</guid><category><![CDATA[100DaysOfCode]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[npm]]></category><category><![CDATA[Node.js]]></category><dc:creator><![CDATA[Skay]]></dc:creator><pubDate>Mon, 02 Nov 2020 05:35:49 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1604294306919/oK-EHRcR7.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="introduction">Introduction</h2>
<p>In this article, we will look at an overview of what NPM is. When we usually run 'npm install', we know that certain packages are being created inside the 'node_modules' folder. Let us look at what they mean and what role they play in order to support running your web application. </p>
<p>We will look at the following topics in detail:</p>
<ul>
<li>What is npm, Registry, and CLI?</li>
<li>How to initialize your project with NPM?</li>
<li>A detailed overview of 'package.json' and it's important properties.</li>
<li>How to install and publish your packages?</li>
<li>Version management of packages.</li>
</ul>
<p>This article is based on my learnings from Tyler Mcginnis's course on React which you find <a target="_blank" href="https://ui.dev/">over here.</a></p>
<h2 id="what-is-npm">What is NPM?</h2>
<p>For a long time, I assumed 'NPM' meant 'Node Package Manager'. But, strangely and funnily it's not. <a target="_blank" href="https://www.npmjs.com/">'npm, Inc.'</a> is a for-profit, venture-backed company founded in 2014 and was acquired by Github in March of 2020.</p>
<p>npm.inc is behind the creation and management of the following components:</p>
<ul>
<li>Node Package Manager</li>
<li>Registry</li>
<li>npm CLI</li>
</ul>
<p>But before, we jump into the details of the above components, let us take a step back and find out what problem NPM solves.</p>
<h2 id="why-do-we-need-a-package-manager">Why do we need a Package Manager?</h2>
<p>Whenever we write any web application, it is generally composed of individual modules that are often bundled together.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1604287989886/1a0X5sy2m.png" alt="npm.png" /></p>
<p>If we have to use a certain package with our application, the traditional way of doing it is using the 'script' tag as shown below:</p>
<pre><code class="lang-js">&lt;body&gt;

  ...

&lt;script src=<span class="hljs-string">"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"</span>&gt;&lt;/script&gt;  
<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"libs/jquery2.1.4.min.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span></span>
&lt;/body&gt;
</code></pre>
<p>While the above works, there are the following disadvantages using the above approach:</p>
<ol>
<li>If the CDN network is down, then your application cannot access the resource.</li>
<li>In the JQuery import example above, while you have downloaded the library to your application. Managing version related changes are left up to us in terms of manually fetching the latest version and replacing them in our code, which is far from ideal.</li>
<li>Finally, the biggest them of all is the order of script tags placed inside the body tag which is required in order for them to be referenced appropriately inside your application.</li>
</ol>
<p>'npm' precisely solves the above problems and more in terms of managing the way your packages are referenced, versioning, and more.</p>
<h2 id="node-package-manager">Node Package Manager</h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1604287956651/Jfvb2GjLZ.jpeg" alt="npm.jpg" /></p>
<p>The node package manager manages the below-mentioned points and does it well:</p>
<ul>
<li>Provides a way to package your program for others to consume.</li>
<li>Provides a way to download the packages from a centralized repository.</li>
<li>Makes it easier for you to manage &amp; switch versions.</li>
</ul>
<h4 id="registry">Registry</h4>
<p>The registry is a centralized repository that contains a list of all npm packages that have been published by others.</p>
<h4 id="npm-cli">npm CLI</h4>
<p>npm CLI provides you a way for you to install &amp; publish the packages using the command-line interface. </p>
<h3 id="how-to-install-npm">How to <strong>install npm?</strong></h3>
<p>'npm' comes with Node. Hence, if you have installed NodeJS, then you should already have npm as it comes with it. You can install Node from <a target="_blank" href="https://nodejs.org/en/download/">here</a> or if you are using Windows, I have a detailed article on how to install Node using a node version manager or 'nvm' <a target="_blank" href="https://blog.skay.dev/how-to-install-node-version-manager-nvm-for-windows-10">over here.</a></p>
<p>If Node and npm are installed correctly, you should be able to run the following commands in your terminal to check which versions you have installed.</p>
<pre><code class="lang-bash">node -v <span class="hljs-comment"># My installed version: v11.10.0</span>
npm -v <span class="hljs-comment"># My installed version: 6.9.0</span>
</code></pre>
<p>Now that you should have Node and npm installed successfully, we will look at how to initialize your project with NPM and the important components associated with the node package manager.</p>
<h2 id="how-to-initialize-your-project-with-npm">How to initialize your Project with npm?</h2>
<p>The first step to use npm is navigating to your project folder (e.g. myProject) and run the command 'npm init' command from the command terminal.</p>
<pre><code class="lang-bash">$ root&gt; <span class="hljs-built_in">cd</span> myproject

$ root/myproject&gt; npm init
</code></pre>
<p>The above command will perform the initialization process and you’ll notice that you have a brand new <code>package.json</code> file and an empty <code>node_modules</code> directory.</p>
<h3 id="nodemodules"><strong>node_modules</strong></h3>
<p>Whenever you install a package, the source code for that package will be put inside of the <code>node_modules</code> directory. Then, whenever you import a module into your project that isn’t a file path, i.e. <code>import React from 'react'</code>, your app will look to <code>node_modules</code> for the source.</p>
<h3 id="packagejson"><strong>package.json</strong></h3>
<p>The '<code>package.json</code>' file contains all of the meta-information for your project. It contains information like the project’s name, author, description, and most importantly, the list of packages (as well as what versions) that your project depends on and how to run your project.</p>
<p>Here's a sample of the 'package.json' file:</p>
<pre><code class="lang-json">{
   <span class="hljs-attr">"name"</span>:<span class="hljs-string">"Example Project"</span>,
   <span class="hljs-attr">"version"</span>:<span class="hljs-string">"1.0.0"</span>,
   <span class="hljs-attr">"description"</span>: <span class="hljs-string">"An Example Project demonstrating Node Package Manager"</span>,
   <span class="hljs-attr">"author"</span>:<span class="hljs-string">"Skay"</span>,
   <span class="hljs-attr">"license"</span>:<span class="hljs-string">"ISC"</span>,
   <span class="hljs-attr">"homepage"</span>:<span class="hljs-string">"https://github.com/skaytech"</span>,
   <span class="hljs-attr">"keywords"</span>:[
      <span class="hljs-string">"react"</span>,
      <span class="hljs-string">"react-router"</span>,
      <span class="hljs-string">"babel"</span>,
      <span class="hljs-string">"webpack"</span>
   ],
   <span class="hljs-attr">"repository"</span>:{
      <span class="hljs-attr">"type"</span>:<span class="hljs-string">"git"</span>,
      <span class="hljs-attr">"url"</span>:<span class="hljs-string">"https://github.com/skaytech/webpack-example.git"</span>
   },
   <span class="hljs-attr">"main"</span>:<span class="hljs-string">"index.js"</span>,
   <span class="hljs-attr">"dependencies"</span>:{
      <span class="hljs-attr">"prop-types"</span>:<span class="hljs-string">"^15.7.2"</span>,
      <span class="hljs-attr">"query-string"</span>:<span class="hljs-string">"^6.2.0"</span>,
      <span class="hljs-attr">"react"</span>:<span class="hljs-string">"^16.8.3"</span>,
      <span class="hljs-attr">"react-dom"</span>:<span class="hljs-string">"^16.8.3"</span>,
      <span class="hljs-attr">"react-icons"</span>:<span class="hljs-string">"^3.4.0"</span>,
      <span class="hljs-attr">"react-router-dom"</span>:<span class="hljs-string">"^4.3.1"</span>
   },
   <span class="hljs-attr">"devDependencies"</span>:{
      <span class="hljs-attr">"@babel/core"</span>:<span class="hljs-string">"^7.3.4"</span>,
      <span class="hljs-attr">"@babel/plugin-proposal-class-properties"</span>:<span class="hljs-string">"^7.3.4"</span>,
      <span class="hljs-attr">"@babel/preset-env"</span>:<span class="hljs-string">"^7.3.4"</span>,
      <span class="hljs-attr">"@babel/preset-react"</span>:<span class="hljs-string">"^7.0.0"</span>,
      <span class="hljs-attr">"babel-loader"</span>:<span class="hljs-string">"^8.0.5"</span>,
      <span class="hljs-attr">"babel-plugin-syntax-dynamic-import"</span>:<span class="hljs-string">"^6.18.0"</span>,
      <span class="hljs-attr">"copy-webpack-plugin"</span>:<span class="hljs-string">"^5.0.0"</span>,
      <span class="hljs-attr">"css-loader"</span>:<span class="hljs-string">"^2.1.0"</span>,
      <span class="hljs-attr">"html-webpack-plugin"</span>:<span class="hljs-string">"^3.2.0"</span>,
      <span class="hljs-attr">"style-loader"</span>:<span class="hljs-string">"^0.23.1"</span>,
      <span class="hljs-attr">"webpack"</span>:<span class="hljs-string">"^4.29.5"</span>,
      <span class="hljs-attr">"webpack-cli"</span>:<span class="hljs-string">"^3.2.3"</span>,
      <span class="hljs-attr">"webpack-dev-server"</span>:<span class="hljs-string">"^3.2.1"</span>
   },
   <span class="hljs-attr">"scripts"</span>:{
      <span class="hljs-attr">"start"</span>:<span class="hljs-string">"webpack-dev-server --open"</span>,
      <span class="hljs-attr">"build"</span>:<span class="hljs-string">"NODE_ENV='production' webpack"</span>
   }
}
</code></pre>
<p>Let us look at a few of those properties in detail:</p>
<h3 id="dependencies"><strong>dependencies</strong></h3>
<p>The list of packages listed under the 'dependencies' property is the ones your application needs in order to run. When you install a new package, the source for the package will be placed inside the 'node_modules' directory. The name &amp; version of that package will automatically be added to the 'dependencies' property in your 'package.json' file.</p>
<h3 id="devdependencies"><strong>devDependencies</strong></h3>
<p>'devDependencies' is exactly like the 'dependencies' in the sense the source will be placed inside the 'node_modules' directory. However, these 'dependencies' will only be made available to your application while running them in your development environment.</p>
<p>In other words, these 'dependencies' will not be required to run in the production environment.</p>
<h3 id="scripts">scripts</h3>
<p>The 'scripts' property defines the set of commands you can provide to the node package manager to run any kind of automation tasks. In the above example, we have two scripts, namely the 'start' and 'build'.</p>
<p>The general syntax to run any script is:</p>
<pre><code class="lang-bash">$ root &gt; npm run [SCRIPT NAME]
</code></pre>
<p>In the above example, if you run the to start the 'webpack-dev-server', you can run the script 'start' using the following command: </p>
<pre><code class="lang-bash">$ root/myproject&gt; npm run start
</code></pre>
<h2 id="npm-registry-and-how-to-install-packages-from-the-registry">NPM Registry and How to install packages from the registry?</h2>
<p>Now, that we've looked at the basics of 'npm' and the 'package.json'. We will look at how you can install certain packages from the 'npm registry'.</p>
<p>As I had introduced earlier, the registry is a centralized repository where all the packages are published and are available for downloads.</p>
<p>For Example, if you want to install 'react', you can run the following command:</p>
<pre><code class="lang-bash">$ root/myproject&gt; npm install react
</code></pre>
<p>The general syntax to install any package is:</p>
<pre><code class="lang-bash">$ root&gt; npm install [PACKAGE NAME]
</code></pre>
<p>Running 'npm install', will do the following things:</p>
<ul>
<li>It will put the 'react' package inside of your 'node_modules' directory.</li>
<li>It will add 'react' as a property on your 'dependencies' object inside your package.json file.</li>
</ul>
<h3 id="install-your-dependency-as-a-dev-dependency">Install your dependency as a Dev Dependency</h3>
<p>In order to tell 'npm' that your dependency needs to be added only as a 'dev dependency', i.e., the package needs to be made only for development purposes, you should run the following command:</p>
<pre><code class="lang-bash">$ root&gt; npm install webpack --save-dev
</code></pre>
<p>The key differentiator is the '—save-dev' flag while running the 'npm install' command for installing the package as a dev dependency.</p>
<h2 id="how-to-publish-your-package-to-npm">How to publish your package to NPM?</h2>
<p>NPM has over a million packages as of the date and it wouldn't be possible if it wasn't easy to publish one. You need to have the following to publish a package on npm:</p>
<ol>
<li>An account on npm</li>
<li>A package.json file with 'name', 'version', and 'main' (which points to the entry point of your package) properties.</li>
</ol>
<p>Once you have the above, in your command line run the following commands:</p>
<pre><code class="lang-bash">$ root/myPackage &gt; npm login

$ root/myPackage &gt; npm publish
</code></pre>
<p>That's all there's to it! There are more advanced features that you can check out their <a target="_blank" href="https://docs.npmjs.com/packages-and-modules/contributing-packages-to-the-registry">official guide</a>.</p>
<h2 id="versioning"><strong>Versioning</strong></h2>
<p>If you remember, at the start of our post, we had discussed managing the different versions of our packages. Thankfully npm CLI provides a very nice way to manage it as well.</p>
<p>Typically each package on the npm registry follows semantic versioning. There are three parts to semantic versioning, major versions, minor versions, and patch versions.</p>
<p>For example, if your package version is v1.2.3, the following is the break-up:</p>
<ul>
<li>Major Version - 1 -  If you had a breaking change, you'll increment the major version.</li>
<li>Minor Version - 2 - If you had a non-breaking feature, you'll increment the minor version.</li>
<li>Patch Version - 3 - Everything else, you'll increment the patch version.</li>
</ul>
<p>Why is this important? We want to avoid having our app break because we installed the wrong version of a package. npm gives us some tools to prevent this.</p>
<h3 id="the-operator-in-your-version-number">The '<strong>^' operator in your Version number</strong></h3>
<p>Let us look at the 'dependencies' inside your 'package.json' file again:</p>
<pre><code class="lang-json"><span class="hljs-string">"dependencies"</span>:{
      <span class="hljs-attr">"prop-types"</span>:<span class="hljs-string">"^15.7.2"</span>,
      <span class="hljs-attr">"query-string"</span>:<span class="hljs-string">"^6.2.0"</span>,
      <span class="hljs-attr">"react"</span>:<span class="hljs-string">"^16.8.3"</span>,
      <span class="hljs-attr">"react-dom"</span>:<span class="hljs-string">"^16.8.3"</span>,
      <span class="hljs-attr">"react-icons"</span>:<span class="hljs-string">"^3.4.0"</span>,
      <span class="hljs-attr">"react-router-dom"</span>:<span class="hljs-string">"^4.3.1"</span>
}
</code></pre>
<p>You’ll notice that before each version number, there’s a little <code>^</code> or a 'carrot' symbol.</p>
<p>The <code>^</code> instructs npm to install the newest version of the package <strong>with the same major version</strong>. </p>
<p>Let's take, for example, the 'react' package released v16.9.0. After the new version of the package is released and you run 'npm install' inside your project, then that version of the package will be available to your project.</p>
<p>If 'react' released a v17.0.0, which means it's breaking change and you run 'npm install', the breaking change won't be installed and made available to your project.</p>
<h3 id="the-operator-in-your-version-number">The '<strong>~' operator in your version number</strong></h3>
<p>If your requirement is to only update your package only for updates for <strong>the same major and minor versions</strong>, then you'll use the '~' operator.</p>
<p>In the above example, if you change the 'prop-types' package to have the '~' operator:</p>
<pre><code class="lang-json"><span class="hljs-string">"dependencies"</span>:{
      <span class="hljs-attr">"prop-types"</span>:<span class="hljs-string">"~15.7.2"</span>,      
}
</code></pre>
<p>If you run 'npm install', a new package will only be installed if 'v15.7.3' is released. If 'v16.0.0' or 'v15.8.0' came out, neither would be installed.</p>
<h3 id="exact-version"><strong>Exact version</strong></h3>
<p>Finally, the simplest and direct use-case of having the exact version of what’s listed in your <code>package.json</code> file, you'll just need to remove all 'symbols' before your version number and only list only the version number as shown below:</p>
<pre><code class="lang-json"><span class="hljs-string">"dependencies"</span>:{
      <span class="hljs-attr">"prop-types"</span>:<span class="hljs-string">"15.7.2"</span>,      
}
</code></pre>
<p>Now if you run 'npm install' anytime, only the version 'v15.7.2' will ever be installed.</p>
<h2 id="conclusion">conclusion</h2>
<p>A quick summary of what we discussed in this article:</p>
<ul>
<li>What is npm, Registry, and CLI?</li>
<li>How to initialize your project with NPM?</li>
<li>A detailed overview of 'package.json' and it's important properties.</li>
<li>How to install and publish your packages?</li>
<li>Version management of packages.</li>
</ul>
<p>I hope you enjoyed the article. Don't forget to subscribe to my newsletter and connect with me on Twitter <a target="_blank" href="https://twitter.com/skay_tech">@skaytech</a></p>
<h3 id="you-will-also-enjoy-the-following-articles">You will also enjoy the following articles:</h3>
<ul>
<li><a target="_blank" href="https://blog.skay.dev/why-you-should-choose-to-learn-react">Why you should learn 'React'?</a></li>
<li><a target="_blank" href="https://blog.skay.dev/the-react-ecosystem">The React Ecosystem</a></li>
<li><a target="_blank" href="https://blog.skay.dev/asyncawait-in-javascript-explained">Async/Await explained in JavaScript</a></li>
<li><a target="_blank" href="https://blog.skay.dev/what-are-javascript-promises">What are JavaScript Promises</a></li>
<li><a target="_blank" href="https://blog.skay.dev/javascript-callbacks-explained">JavaScript Callbacks Explained</a></li>
<li><a target="_blank" href="https://blog.skay.dev/all-you-need-to-about-javascript-objects">Everything you need to know about JavaScript Objects</a></li>
<li><a target="_blank" href="https://blog.skay.dev/javascript-functions-everything-you-must-know-as-a-javascript-newbie">Everything you need to know about JavaScript Funtions</a></li>
<li><a target="_blank" href="https://blog.skay.dev/es6-higher-order-functions">ES6 - Higher Order Functions</a></li>
<li><a target="_blank" href="https://blog.skay.dev/es6-spread-operator">ES6 - Spread Operator</a></li>
<li><a target="_blank" href="https://blog.skay.dev/es6-understanding-destructuring">ES6 - Understanding Destructuring</a></li>
<li><a target="_blank" href="https://blog.skay.dev/es6-arrow-functions">ES6 - Arrow Functions</a></li>
<li><a target="_blank" href="https://blog.skay.dev/what-is-currying-in-javascript">What is Currying in JavaScript?</a></li>
<li><a target="_blank" href="https://blog.skay.dev/understanding-hoisting">Understanding Hoisting</a></li>
<li><a target="_blank" href="https://blog.skay.dev/introduction-to-big-o-notation-time-space-complexity">Introduction to Big O Notation, Time &amp; Space Complexity</a></li>
</ul>
]]></content:encoded></item><item><title><![CDATA[The React Ecosystem]]></title><description><![CDATA[Introduction
When I started learning React, there was a huge debate on whether React is a library or a framework. While I assumed React to be a framework, since, it was always compared with the likes of Vue or Angular, it is actually a JavaScript lib...]]></description><link>https://blog.skay.dev/the-react-ecosystem</link><guid isPermaLink="true">https://blog.skay.dev/the-react-ecosystem</guid><category><![CDATA[100DaysOfCode]]></category><category><![CDATA[React]]></category><category><![CDATA[JavaScript]]></category><dc:creator><![CDATA[Skay]]></dc:creator><pubDate>Fri, 30 Oct 2020 13:01:08 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1604062825974/UyRRojbdB.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="introduction">Introduction</h2>
<p>When I started learning React, there was a huge debate on whether React is a library or a framework. While I assumed React to be a framework, since, it was always compared with the likes of Vue or Angular, it is actually a JavaScript library.</p>
<p>However, there are other components such as the Webpack, Babel, Router, etc. that make it more wholesome into a complete framework that it is. Often, this is hidden under the hood, since we typically use 'create-react-app' to generate a React boilerplate code to start our application with.</p>
<p>In this article, we will look at a brief overview of the following key components that comprise the 'React Ecosystem'. </p>
<ul>
<li>Babel</li>
<li>Webpack</li>
<li>Routing</li>
<li>Styling</li>
<li>State (Redux/Context)</li>
</ul>
<p>This is my second article, in the 'React Series' based on my learnings from <a target="_blank" href="https://ui.dev/">Tyler Mcginnis course @ ui.dev</a>. </p>
<p>You can read the first article on <a target="_blank" href="https://blog.skay.dev/why-you-should-choose-to-learn-react">Why you should learn 'React'?</a></p>
<h2 id="react">React</h2>
<p>As I had mentioned in the introduction, React is just a library and you can just include the 'react' and 'react-dom' script tag inside the index.html and it's perfectly valid. </p>
<p>You can run the below code and it's a perfect valid React application. You can find the code in action <a target="_blank" href="https://codepen.io/skaytech/pen/bGevWVo">over here.</a></p>
<pre><code class="lang-js">&lt;!DOCTYPE html&gt;
<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">html</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>React<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"app"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span>
      <span class="hljs-attr">crossorigin</span>
      <span class="hljs-attr">src</span>=<span class="hljs-string">"https://unpkg.com/react@16.14/umd/react.development.js"</span>
    &gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span>
      <span class="hljs-attr">crossorigin</span>
      <span class="hljs-attr">src</span>=<span class="hljs-string">"https://unpkg.com/react-dom@16.14/umd/react-dom.development.js"</span>
    &gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"https://unpkg.com/babel-standalone@6/babel.min.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text/babel"</span>&gt;</span><span class="javascript">
      <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Hello</span>(<span class="hljs-params">{ name }</span>) </span>{
        <span class="hljs-keyword">return</span> <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Hello, {name}<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span></span>;
      }

      ReactDOM.render(<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">Hello</span> <span class="hljs-attr">name</span>=<span class="hljs-string">'Skay'</span> /&gt;</span></span>, <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'app'</span>));
    </span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span></span>
</code></pre>
<p>So, then the question becomes why is it we don't use the above setup for building our React apps? The setup when we run 'create-react-app' looks quiet different. What's the role of other components such as 'Webpack', 'Babel', etc. in supporting a production-grade react apps.</p>
<p>Let us look at each of those components at a high-level and what they do behind the scenes to support a production-grade React app.</p>
<h2 id="babel">Babel</h2>
<p>If you visit, <a target="_blank" href="https://babeljs.io/">Babel's website</a>, it'll be mentioned that Babel is a JavaScript compiler. What that means is Babel is responsible to transform JavaScript code from one format to another based on specified configuration.</p>
<p>Now, let us look at the below code example. </p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">User</span> (<span class="hljs-params">{ name }</span>) </span>{

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Hello, {name}<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>      
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  )
}
</code></pre>
<p>A couple of things to note here:</p>
<ul>
<li>User is a React component that returns a UI (view) Hello, "name" based on the name passed to the component.</li>
<li>The 'HTML' syntax within the JavaScript context is called JSX. It is React's way to allow you to describe UI inside of your components.</li>
</ul>
<p>Now, if your browser needs to display the above information, it needs to know to get hold of the HTML view and the regular old JavaScript. This looks like a perfect job for 'Babel' which accepts the  JSX input and transforms it into a valid JavaScript that can be understood by the browser.</p>
<p>But what's cool about Babel is that it's not limited to JSX → JS transformations, but, it can do almost any kind of transformations and it is most commonly used to transform ES6+ code to the backward-compatible version of JavaScript that old browsers can understand.</p>
<h2 id="webpack">Webpack</h2>
<p>Webpack is a module bundler. It examines your codebase for all imports and exports and intelligently bundles all your modules into a single file that your browser can understand.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1604056811300/_dnqOUjjJ.png" alt="webpackbundle.png" /></p>
<p>So in our above example, the following lines of code, the 'import' and 'export' statements are what Webpack will scan and bundle it into a single bundle.js file which will be referenced inside of index.html.</p>
<pre><code class="lang-js"><span class="hljs-keyword">import</span> React <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">User</span></span>
</code></pre>
<p>I have an article that describes Webpack in much greater detail, which you can read <a target="_blank" href="https://blog.skay.dev/a-basic-introduction-to-webpack">over here.</a></p>
<h2 id="routing">Routing</h2>
<p>The idea was to keep React as a simple UI library and not include the Router as a part of the core library. It was done with the intent to provide the users the flexibility to decide what kind of router they would want to integrate with React.</p>
<p>The most popular router for React is of course the <a target="_blank" href="https://www.npmjs.com/package/react-router">'React Router'</a></p>
<p>You can describe React Router’s job is to render specific React components based on the current URL path of the user.</p>
<pre><code class="lang-js">&lt;Router&gt;
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">ul</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">Link</span> <span class="hljs-attr">to</span>=<span class="hljs-string">"/"</span>&gt;</span>Home<span class="hljs-tag">&lt;/<span class="hljs-name">Link</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">Link</span> <span class="hljs-attr">to</span>=<span class="hljs-string">"/about"</span>&gt;</span>About<span class="hljs-tag">&lt;/<span class="hljs-name">Link</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">Link</span> <span class="hljs-attr">to</span>=<span class="hljs-string">"/contact"</span>&gt;</span>Contact<span class="hljs-tag">&lt;/<span class="hljs-name">Link</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">ul</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">Route</span> <span class="hljs-attr">exact</span> <span class="hljs-attr">path</span>=<span class="hljs-string">"/"</span> <span class="hljs-attr">component</span>=<span class="hljs-string">{Home}/</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">Route</span> <span class="hljs-attr">path</span>=<span class="hljs-string">"/about"</span> <span class="hljs-attr">component</span>=<span class="hljs-string">{About}/</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">Route</span> <span class="hljs-attr">path</span>=<span class="hljs-string">"/contact"</span> <span class="hljs-attr">component</span>=<span class="hljs-string">{Contact}/</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
&lt;/Router&gt;
</code></pre>
<p>When a user navigates to the home page (/), React Router will render the Home component. When they navigate to /about, React Router will render About. Likewise, when they navigate to /contact, React Router will render the Contact component.</p>
<p>React Router is again a vast topic and will warrant a separate blog post of its own. For now, you can simply understand it as the component that is responsible to render React components based on the URL path the user visits.</p>
<h2 id="styling">Styling</h2>
<p>There are two ways to Style a React application. The traditional way and the React way. Let us look at both ways of defining styling to your react application. </p>
<h3 id="traditional-styling">Traditional Styling</h3>
<p>The traditional approach includes adding all your styling inside index.css and you can have classes, cascading defined there typically how you would do for a non-react application. In fact, you can also have SASS or any CSS pre-processors included.</p>
<h3 id="react-styling">React Styling</h3>
<p>The React approach of styling embraces the component model. Let's add styling to our above example and see how the code looks.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> styles = {
  <span class="hljs-attr">header</span>: {
    <span class="hljs-attr">fontWeight</span>: <span class="hljs-number">400</span>,
    <span class="hljs-attr">fontSize</span>: <span class="hljs-number">55</span>,
    <span class="hljs-attr">color</span>: <span class="hljs-string">'#a41c1c'</span>
  }
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">User</span> (<span class="hljs-params">{ name }</span>) </span>{

  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">h1</span> <span class="hljs-attr">style</span>=<span class="hljs-string">{styles.header}</span>&gt;</span>Hello {name}<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>      
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  )
}
</code></pre>
<p>As you can see from the above code, the styling is contained within each component. One of the most popular CSS in the JS library in the React ecosystem is the Styled Components. You can check them out <a target="_blank" href="https://styled-components.com/">over here.</a></p>
<h2 id="state-reduxcontext">State (Redux/Context)</h2>
<p>Before we talk above Redux or Context, we will take a step back and define what state means to a React component.</p>
<h3 id="react-state">React State</h3>
<p>React's philosophy is that you build individual components that can each manage their own state as well as describe their UI. You then compose those components together to get your app.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1604056898402/1h2BX7r7Q.png" alt="reactphilosophy-Page-1.png" /></p>
<p>But often in real-life applications, the state of components needs to be shared with other components and it becomes a challenge to pass the state through the component tree if there are multiple levels. This is generally the case as the application grows larger and becomes more complex.</p>
<h3 id="redux">Redux</h3>
<p>To solve the above problem, Redux came into the picture. Redux is a state management library and while it's often used within the context of React library, it can in fact be used with any other view library and it's not tied to React.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1604056911639/Nbhf1TIMC.png" alt="reactphilosophy-Page-2.png" /></p>
<p>The philosophy of Redux is pretty different. Instead of having state spread out in different places, with Redux, you stick all of your 'State' in a single location called a 'Store'. You then establish strict rules for how the state of your 'Store' can change through something called 'Actions'.</p>
<h3 id="context">Context</h3>
<p>Context API was introduced by the React team for providing a centralized way to manage a Component's state without relying on external libraries such as 'Redux'.</p>
<p>As per the official React docs, Context provides a way to pass data through the component tree without having to pass props down manually at every level.</p>
<p>Each of the topics such as Redux, Context API requires a dedicated blog article to explain the details. The important takeaway as a part of this article is that 'State' management is a core part of React's ecosystem and you can manage it simply within a component's state management mechanism or use Context API or Redux library based on your use-case or the complexity of the application.</p>
<h2 id="conclusion">Conclusion</h2>
<p>I think that's pretty much an overview of the core components. I hope after this article, you'll idea of what is under the hood when you run CRA (create-react-app) in your CLI, and when someone says it's a React application, it's an ecosystem and not just the React library. </p>
<p>Don't forget to subscribe to my newsletter and follow me on Twitter <a target="_blank" href="https://twitter.com/skay_tech">@skaytech</a>.</p>
<h3 id="you-will-also-enjoy-the-following-articles">You will also enjoy the following articles:</h3>
<ul>
<li><a target="_blank" href="https://blog.skay.dev/why-you-should-choose-to-learn-react">Why should you learn React?</a></li>
<li><a target="_blank" href="https://blog.skay.dev/asyncawait-in-javascript-explained">Async/Await in JavaScript</a></li>
<li><a target="_blank" href="https://blog.skay.dev/all-you-need-to-about-javascript-objects">All you need to know about JavaScript Objects</a></li>
<li><a target="_blank" href="https://blog.skay.dev/what-are-javascript-promises">JavaScript Promises</a></li>
<li><a target="_blank" href="https://blog.skay.dev/javascript-functions-everything-you-must-know-as-a-javascript-newbie">JavaScript Functions</a></li>
<li><a target="_blank" href="https://blog.skay.dev/iife-immediately-invoked-function-expressions">IIFE</a></li>
<li><a target="_blank" href="https://blog.skay.dev/history-of-ecma-es5-es6-and-beyond">History of ECMAScript</a></li>
<li><a target="_blank" href="https://blog.skay.dev/es6-arrow-functions">ES6 =&gt; Arrow Functions</a></li>
<li><a target="_blank" href="https://blog.skay.dev/docker-fundamentals">Docker Fundamentals</a></li>
<li><a target="_blank" href="https://blog.skay.dev/what-are-git-hooks">What are Git Hooks?</a></li>
<li><a target="_blank" href="https://blog.skay.dev/guide-organised-and-productive">A Practical Guide to help you stay organized and productive</a></li>
<li><a target="_blank" href="https://blog.skay.dev/javascript-event-loop-explained">What is Event Loop in JavaScript?</a></li>
<li><a target="_blank" href="https://blog.skay.dev/a-basic-introduction-to-webpack">A Basic Introduction to Webpack</a></li>
<li><a target="_blank" href="https://blog.skay.dev/understanding-closures">Understanding Closures</a></li>
<li><a target="_blank" href="https://blog.skay.dev/what-is-this-in-javascript">What is 'this' in JavaScript?</a></li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Why you should choose to learn 'React'?]]></title><description><![CDATA[Introduction
I have been working with the React library for a while now and the more I understand it, the more I'm in awe of the library. 
In this article, I wanted to share my thoughts on why I think React is one of the most popular JavaScript frame...]]></description><link>https://blog.skay.dev/why-you-should-choose-to-learn-react</link><guid isPermaLink="true">https://blog.skay.dev/why-you-should-choose-to-learn-react</guid><category><![CDATA[100DaysOfCode]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[React]]></category><category><![CDATA[framework]]></category><dc:creator><![CDATA[Skay]]></dc:creator><pubDate>Tue, 27 Oct 2020 11:25:30 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1603797780927/S6loCK6fY.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="introduction">Introduction</h2>
<p>I have been working with the React library for a while now and the more I understand it, the more I'm in awe of the library. </p>
<p>In this article, I wanted to share my thoughts on why I think React is one of the most popular JavaScript frameworks ever and why you should consider learning it if you are planning to learn a JavaScript framework.</p>
<p>This is the first article, under the series 'React' and is based on my learnings from <a target="_blank" href="https://ui.dev">Tyler Mcginnis course @ ui.dev</a>. Do check out Tyler, he's one heck of a teacher.</p>
<h2 id="a-powerful-composition-model">A Powerful Composition Model</h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1603796976053/niabYzG3i.png" alt="Unidirectionaldataflow-Page-4.png" /></p>
<p>Composition is a language-agnostic programming principle that relies on building programs or functions by composing them together.</p>
<p>React extends the same concept and it is possible to build React components by composing them together.</p>
<p>Let us see a very simple example, to begin with, a page containing a header, main, and a footer component.</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Header</span> (<span class="hljs-params">props</span>) </span>{
        &lt;&gt;
            <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h3</span>&gt;</span>{props.headerInfo}<span class="hljs-tag">&lt;/<span class="hljs-name">h3</span>&gt;</span></span>
    &lt;/&gt;
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Footer</span> (<span class="hljs-params">props</span>) </span>{
        &lt;&gt;
            <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h5</span>&gt;</span>{props.footerInfo}<span class="hljs-tag">&lt;/<span class="hljs-name">h5</span>&gt;</span></span>
    &lt;/&gt;
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Main</span> (<span class="hljs-params">props</span>) </span>{
    <span class="hljs-keyword">return</span> (
        <span class="xml"><span class="hljs-tag">&lt;&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>{props.mainInfo}<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
    <span class="hljs-tag">&lt;/&gt;</span></span>
    )
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Home</span> (<span class="hljs-params">props</span>) </span>{
  <span class="hljs-keyword">return</span> (
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">Header</span> <span class="hljs-attr">headerContent</span>=<span class="hljs-string">{props.headerInfo}</span> /&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">Main</span> <span class="hljs-attr">mainContent</span>=<span class="hljs-string">{props.mainInfo}</span> /&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">Footer</span> <span class="hljs-attr">footerContent</span>=<span class="hljs-string">{props.footerInfo}</span> /&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
  )
}
</code></pre>
<p>As you can see from the above example, every function such as Header, Main, and Footer returns a view. Each of those views is further composed within the 'Home' component. This idea of having the power to create a UI by combining any one or more components makes it incredibly powerful.</p>
<p>And this idea has been exploited by the community to develop a multitude of third-party React components that is available on NPM.</p>
<p>A simple analogy that can make all of the above 'click', is, React to composition is equivalent to Pizzeria to 'Build your own Pizza'.</p>
<p>Reference - https://reactjs.org/docs/composition-vs-inheritance.html</p>
<h2 id="unidirectional-data-flow">Unidirectional Data Flow</h2>
<p>In a traditional application, you have event handlers that update the DOM which generally holds the state of the application as shown below.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1603797029476/kqjzaOrxt.png" alt="Unidirectionaldataflow-1.png" /></p>
<p>As the application grows, the event handlers start updating other parts of the state and the above diagram starts to look like the Spaghetti below.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1603797044830/sPUPllSHX.png" alt="Unidirectionaldataflow-2.png" /></p>
<p>With React, it follows a Unidirectional Data Flow concept which means that data has one, and only one, way to be transferred to other parts of the application.</p>
<p>Every component has its own state and they need to only bother about updating them. Based on the change in state, React does the hard work of updating the UI based on the change in state. </p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1603797016518/rVUgo21zN.png" alt="Unidirectionaldataflow-3.png" /></p>
<p>Advantages of a system with a Unidirectional data flow:</p>
<ol>
<li>Since the state is maintained at a single location, it can be easily traced to what actions are updating the data as the flow is one way only.</li>
<li>You can control which components to re-render on a common state change. You put all those components under one common state containing the parent component.</li>
<li>Easy to trace and fix bugs and errors caused by any poorly written code.</li>
</ol>
<h2 id="declarative-ui">Declarative UI</h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1603797892385/Gl8oo7wi3.jpeg" alt="kelly-sikkema-v9FQR4tbIq8-unsplash.jpg" /></p>
<p>In React everything is a component and each component has primarily two things (three actually which includes the lifecycle methods) that you need to be bothered about while defining a component.</p>
<p>a. The Components state.</p>
<p>b. How the UI looks based on the state.</p>
<p>Let us take a look at the following code example in JQuery &amp; React:</p>
<p>Using JQuery:</p>
<pre><code class="lang-js">$(<span class="hljs-string">'btn'</span>).click(<span class="hljs-function">() =&gt;</span> {
  $(<span class="hljs-built_in">this</span>).toggleClass(<span class="hljs-string">'highlight'</span>)
  $(<span class="hljs-built_in">this</span>).text() === <span class="hljs-string">'Add Highlight'</span>
    ? $(<span class="hljs-built_in">this</span>).text(<span class="hljs-string">'Remove Highlight'</span>)
    : $(<span class="hljs-built_in">this</span>).text(<span class="hljs-string">'Add Highlight'</span>)
})
</code></pre>
<p>Using React:</p>
<pre><code class="lang-js">&lt;Btn
  highlight={<span class="hljs-built_in">this</span>.state.highlight}
  onToggle={<span class="hljs-built_in">this</span>.toggleBtn}
/&gt;
</code></pre>
<p>Key things to note based on the above code example:</p>
<ol>
<li>In the JQuery example, you have to access the DOM and ensure that is updated based on events.</li>
<li>In the React example, you have to only worry about the following two things:<ul>
<li>The state or how to update the state based on an event. React will do the hard lifting of updating the DOM.</li>
<li>How the Button component's UI should respond when the state changes? This is described in the 'this.toggleBtn' function.</li>
</ul>
</li>
</ol>
<p>React provides the abstraction, so that, the Component does not need to worry about updating the DOM.</p>
<h2 id="utilizes-core-javascript-features-minimal-custom-api">Utilizes "Core JavaScript" features - Minimal Custom API</h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1603797268468/XSb-8qkaM.png" alt="Reactjs.png" /></p>
<p>React does not try to re-create functionality that you can already do using JavaScript.</p>
<p>Let us look at the following example of creating unordered lists from a 'products' array using the three different JavaScript Frameworks: Angular, Vue &amp; React.</p>
<p>Angular uses 'ngFor' to loop through the 'products' array.</p>
<pre><code class="lang-js">&lt;ul id=<span class="hljs-string">"products"</span>&gt;
        <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">li</span> *<span class="hljs-attr">ngFor</span>=<span class="hljs-string">"let product in products"</span>&gt;</span>
                {{product.name}}
        <span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span></span>
&lt;/ul&gt;
</code></pre>
<p>Vue uses 'v-for' to loop through the 'products' array.</p>
<pre><code class="lang-js">&lt;ul id=<span class="hljs-string">"products"</span>&gt;
        <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">li</span> <span class="hljs-attr">v-for</span>=<span class="hljs-string">"product in products"</span>&gt;</span>
                {{product.name}}
        <span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span></span>
&lt;/ul&gt;
</code></pre>
<p>React uses </p>
<pre><code class="lang-js">&lt;ul id=<span class="hljs-string">"products"</span>&gt;
        {products.map(<span class="hljs-function">(<span class="hljs-params">product, index</span>) =&gt;</span> (
            <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">li</span> <span class="hljs-attr">key</span>=<span class="hljs-string">"index"</span>&gt;</span>
                {{product.name}}
          <span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span></span>
&lt;/ul&gt;
</code></pre>
<p>As you can see from the above example, React uses JavaScript's map method as compared to any special APIs provided by Vue or Angular. Before Angular or Vue folks jump on me, by no means, I'm trying to belittle other frameworks. It is just one significant point that I wanted to highlight over here.</p>
<p>The important point to note here is that React's API layer is kept to the minimum and it utilizes the features provided by JavaScript.</p>
<h2 id="the-right-abstraction">The Right Abstraction</h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1603797555672/knlHUfySc.png" alt="Brown, Pink and Green Abstract Shapes Wellness YouTube Channel Art.png" /></p>
<p>I think that 'React' provides the right abstraction due to the following reasons:</p>
<ol>
<li>React is highly opinionated as any abstraction should be.</li>
<li>The abstraction provided by React empowers users to adopt it without making it very complicated.</li>
<li>The behavior provided by the abstraction is simple enough to extend and supports almost infinite use-cases as possible without giving away the implementation details.</li>
</ol>
<p>As the saying goes, the 'proof is in the pudding' and you just need to look at the tools built using or on top of React to realize how powerful the abstraction provided by React is.</p>
<ul>
<li><strong><a target="_blank" href="https://www.gatsbyjs.org/">Gatsby</a></strong> is a free and open-source framework based on React that helps developers build blazing-fast websites and apps.</li>
<li><strong><a target="_blank" href="https://nextjs.org/">Next.js</a></strong> is a JavaScript framework that lets you build server-side rendered, static web applications using React.</li>
</ul>
<h2 id="conclusion">Conclusion</h2>
<p>I hope the reasons mentioned in the post make it compelling enough for you to start learning ReactJS as the JavaScript framework of choice.</p>
<p>Don't forget to subscribe and follow me on Twitter <a target="_blank" href="https://twitter.com/skay_tech">@skaytech</a></p>
<h3 id="you-may-also-like-the-following-articles">You may also like the following articles:</h3>
<ul>
<li><a target="_blank" href="https://blog.skay.dev/all-you-need-to-about-javascript-objects">JavaScript Objects</a></li>
<li><a target="_blank" href="https://blog.skay.dev/javascript-functions-everything-you-must-know-as-a-javascript-newbie">JavaScript Functions</a></li>
<li><a target="_blank" href="https://blog.skay.dev/es6-higher-order-functions">ES6 - Higher-Order Functions</a></li>
<li><a target="_blank" href="https://blog.skay.dev/what-is-currying-in-javascript">What is currying?</a></li>
<li><a target="_blank" href="https://blog.skay.dev/introduction-to-big-o-notation-time-space-complexity">A Guide to Big O, Time &amp; Space Complexity</a></li>
<li><a target="_blank" href="https://blog.skay.dev/understanding-hoisting">Understanding Hoisting</a></li>
<li><a target="_blank" href="https://blog.skay.dev/es6-spread-operator">ES6 - Spread Operator</a></li>
<li><a target="_blank" href="https://blog.skay.dev/how-to-make-an-argument-required-in-javascript">How to make an argument "required" in JavaScript?</a></li>
<li><a target="_blank" href="https://blog.skay.dev/5-must-read-tips-to-write-a-killer-blog-article">5 Must-Read Tips to write a killer blog article</a></li>
<li><a target="_blank" href="https://blog.skay.dev/what-are-git-hooks">What are Git Hooks?</a></li>
<li><a target="_blank" href="https://blog.skay.dev/javascript-event-loop-explained">What is Event Loop in JavaScript?</a></li>
<li><a target="_blank" href="https://blog.skay.dev/a-basic-introduction-to-webpack">A Basic introduction to Webpack</a></li>
<li><a target="_blank" href="https://blog.skay.dev/es6-arrow-functions">ES6 =&gt; Arrow Functions</a></li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Async/Await in JavaScript Explained]]></title><description><![CDATA[Introduction
I have previously written articles on Callback & Promises which I recommend you read first to understand the absolute fundamentals of asynchronous processing 

What is Callback in JavaScript?
Promises in JavaScript explained

With the in...]]></description><link>https://blog.skay.dev/asyncawait-in-javascript-explained</link><guid isPermaLink="true">https://blog.skay.dev/asyncawait-in-javascript-explained</guid><category><![CDATA[100DaysOfCode]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[JavaScript]]></category><dc:creator><![CDATA[Skay]]></dc:creator><pubDate>Sat, 24 Oct 2020 06:50:51 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1603438098936/aaiyCeejQ.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="introduction">Introduction</h2>
<p>I have previously written articles on Callback &amp; Promises which I recommend you read first to understand the absolute fundamentals of asynchronous processing </p>
<ul>
<li><a target="_blank" href="https://blog.skay.dev/javascript-callbacks-explained">What is Callback in JavaScript?</a></li>
<li><a target="_blank" href="https://blog.skay.dev/what-are-javascript-promises">Promises in JavaScript explained</a></li>
</ul>
<p>With the introduction of Async/Await in ES7, the code looks and behaves more like a synchronous code. However, you should know that async/await is basically syntax sugar built on top of promises.</p>
<h2 id="how-does-asyncawait-work">How does Async/Await work?</h2>
<p>Async - The keyword 'async', when added before a function, indicates that it returns a promise &amp; the functions inside it are asynchronous in nature and are denoted by the keyword 'await'.</p>
<p>Await - The keyword 'await' can only be used within a function that is defined with the 'async' keyword. The 'await' tells the JavaScript engine to ensure that the execution is paused until the function completes execution and returns a promise.</p>
<p>Let us look at the below code snippet to understand it better.</p>
<h4 id="without-asyncawait">Without Async/Await:</h4>
<p>Let us assume we have a function getCake, that returns the cake. There are two more functions, buyEggs and bakeCake. In order to bakeCake, we need to buyEggs first. However, in the buyEggs function, there's a timeout set to 2 seconds , which means, the bakeCake function will run immediately and buyEggs function will run after the time interval of 2 seconds. </p>
<p>Hence, the output 'undefined' (since the variable 'eggs' isn't assigned a value yet) &amp; 'Cake' is displayed as the output on the console.</p>
<pre><code class="lang-jsx"><span class="hljs-comment">//Function getCake calls the buyEggs &amp; bakeCake functions</span>
<span class="hljs-comment">//the code execution will not wait for Promise to be resolved</span>
<span class="hljs-keyword">const</span> getCake = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-comment">//Buy Eggs</span>
    <span class="hljs-keyword">const</span> eggs = buyEggs();
    <span class="hljs-built_in">console</span>.log(eggs); <span class="hljs-comment">//Output -&gt; undefined</span>

    <span class="hljs-comment">//Bake Cake</span>
    <span class="hljs-keyword">const</span> cake = bakeCake();
    <span class="hljs-built_in">console</span>.log(cake); <span class="hljs-comment">//Output -&gt; Cake on the console</span>
}

<span class="hljs-comment">//Function Buy Eggs returns a promise after 2 seconds</span>
<span class="hljs-keyword">const</span> buyEggs = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
        <span class="hljs-keyword">return</span> <span class="hljs-string">'Eggs'</span>;
    }, <span class="hljs-number">2000</span>);    
}

<span class="hljs-comment">//Bake cake returns cake - But Cake can only be baked after buying eggs</span>
<span class="hljs-keyword">const</span> bakeCake = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-string">'Cake'</span>;
}

<span class="hljs-comment">//Call the getCake() async method</span>
getCake();

<span class="hljs-comment">//Program Output</span>
<span class="hljs-comment">//undefined</span>
<span class="hljs-comment">//Cake</span>
</code></pre>
<h4 id="after-adding-asyncawait">After adding Async/Await:</h4>
<p>In order to ensure that buyEggs function runs before bakeCake function, first, you'll need to return a promise from buyEggs function. </p>
<p>The next step would be to add 'async' keyword to the getCake function to indicate that there are asynchronous functions inside the function.</p>
<p>Further, add the keyword 'await' before the buyEggs function to indicate to the JavaScript engine, that the code execution should be paused until the promise is resolved from the buyEggs function.</p>
<pre><code class="lang-jsx"><span class="hljs-comment">//Function getCake calls the buyEggs &amp; bakeCake functions</span>
<span class="hljs-comment">//The async keyword to the getCake function indicates that the function needs to be run asynchronously</span>
<span class="hljs-comment">//The await keyword to function call buyEggs ensures that </span>
<span class="hljs-comment">//the code execution will not proceed unless the promise is returned from buyEggs()</span>
<span class="hljs-keyword">const</span> getCake = <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-comment">//Buy Eggs</span>
    <span class="hljs-keyword">const</span> eggs = <span class="hljs-keyword">await</span> buyEggs(); <span class="hljs-comment">//Adding await ensures that code execution is paused until promise is resolved</span>
    <span class="hljs-built_in">console</span>.log(eggs); <span class="hljs-comment">// Output -&gt; Eggs</span>

    <span class="hljs-comment">//Bake Cake</span>
    <span class="hljs-keyword">const</span> cake = bakeCake();
    <span class="hljs-built_in">console</span>.log(cake); <span class="hljs-comment">// Output -&gt; Cake</span>
}

<span class="hljs-comment">//Function Buy Eggs returns a promise after 2 seconds</span>
<span class="hljs-keyword">const</span> buyEggs = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> {
        <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
            resolve(<span class="hljs-string">'Eggs'</span>);
        }, <span class="hljs-number">2000</span>);
    });
}

<span class="hljs-comment">//Bake cake returns cake - But Cake can only be baked after buying eggs</span>
<span class="hljs-keyword">const</span> bakeCake = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-string">'Cake'</span>;
}

<span class="hljs-comment">//Call the getCake() async method</span>
getCake();

<span class="hljs-comment">// Program Output</span>
<span class="hljs-comment">//Eggs</span>
<span class="hljs-comment">//Cake</span>
</code></pre>
<h2 id="async-returns-promise-by-default">Async returns Promise by default</h2>
<p>In the above example, we wrapped the buyEggs function to return a promise. But, by adding an 'async' keyword before any function, it returns a promise implicitly. </p>
<p>The first code snippet below contains the keyword 'async' added before the buyEggs function. In the second example, the function buyEggs function explicitly returns a promise. </p>
<p>What I wanted to show in the example was how the function behaves internally, when the keyword 'async' is added in front of it.</p>
<pre><code class="lang-jsx"><span class="hljs-comment">//The below function will return a promise when the 'async' keyword is added </span>
<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">buyEggs</span>(<span class="hljs-params"></span>)</span>{
    <span class="hljs-comment">//Do something</span>
}

<span class="hljs-comment">//The above is same as the below one</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">buyEggs</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">const</span> promise = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>((resolve, reject) {
        <span class="hljs-comment">//Do something</span>
    });
    <span class="hljs-keyword">return</span> promise; 
}
</code></pre>
<p>Let us look at an actual code example</p>
<pre><code class="lang-jsx"><span class="hljs-comment">//The Sum function is indicated with the 'async' keyword</span>
<span class="hljs-comment">//Hence the sum of two numbers x &amp; y is wrapped inside a promise</span>
<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sum</span>(<span class="hljs-params">x, y</span>) </span>{
    <span class="hljs-keyword">return</span> x + y;
}

<span class="hljs-comment">//When the async function 'sum' is invoked</span>
<span class="hljs-comment">//It returns a promise and the return value can be accessed using 'then'</span>
sum(<span class="hljs-number">2</span>, <span class="hljs-number">3</span>).then(<span class="hljs-function"><span class="hljs-params">result</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(result));
</code></pre>
<p>As you can see from the above code example using async before a function will implicitly have a promise returned. Since a promise is returned, the return value can be accessed using the 'then' keyword.</p>
<h1 id="what-happens-when-you-use-await-without-async">What happens when you use Await without Async?</h1>
<p>Let us take the above getCake example and see what happens when we remove the async keyword but retain the await keyword beside the buyEggs function.</p>
<pre><code class="lang-js"><span class="hljs-comment">/*
    getCake Function without the async keyword
    await is added to the buyEggs function
*/</span>
<span class="hljs-keyword">const</span> getCake = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-comment">//Buy Eggs</span>
    <span class="hljs-keyword">const</span> eggs = <span class="hljs-keyword">await</span> buyEggs(); <span class="hljs-comment">//Adding await ensures that code execution is paused until promise is resolved</span>
    <span class="hljs-built_in">console</span>.log(eggs); <span class="hljs-comment">// Output -&gt; Eggs</span>

    <span class="hljs-comment">//Bake Cake</span>
    <span class="hljs-keyword">const</span> cake = bakeCake();
    <span class="hljs-built_in">console</span>.log(cake); <span class="hljs-comment">// Output -&gt; Cake</span>
}

<span class="hljs-comment">//Output -&gt; Uncaught SyntaxError: await is only valid in async function</span>
</code></pre>
<p>As you can see, a syntax error is thrown saying 'await' can only be used inside an async function. I think the reason for this is because when the JavaScript notices the keyword 'await', it first looks up the parent 'async' function it is present within and when it cannot locate one, it ends up complaining that you've violated the declarative rules of async/await.</p>
<h2 id="error-handling">Error Handling</h2>
<p>Finally, the last topic about async/await is how we'll need to approach error handling. If you remember from the promises example, we had a 'then' as well as a 'catch' block which was used for error handling.</p>
<h4 id="using-promise-catch-block-for-error-handling">Using Promise - catch block for error handling</h4>
<pre><code class="lang-js"><span class="hljs-comment">//Using Promises</span>
<span class="hljs-keyword">const</span> someAsyncFn = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>((resolve, reject)) {
            <span class="hljs-keyword">if</span>(someCondition) {
                    resolve(data);
            } <span class="hljs-keyword">else</span> {
                    reject(err);
            }
    }
}

<span class="hljs-comment">//Invoking someAsyncFn</span>
someAsyncFn
.then(<span class="hljs-function"><span class="hljs-params">data</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(data));
.catch(<span class="hljs-function"><span class="hljs-params">err</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(err)); <span class="hljs-comment">//Error Handling is done through the 'catch' block</span>
</code></pre>
<h4 id="using-asyncawait-error-handling-using-trycatch-block">Using Async/Await - Error Handling using try/catch block</h4>
<p>In the below example, the code inside the 'async' function fetchFruits is wrapped within a try and a catch block. When the promise returns 'Resolved' then the 'updateUI' function is invoked.</p>
<p>When Promise is Resolved:</p>
<pre><code class="lang-js"><span class="hljs-comment">//Using Async Await</span>
<span class="hljs-keyword">const</span> fetchFruits = <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">try</span> {
        <span class="hljs-keyword">const</span> fruits = <span class="hljs-keyword">await</span> getFruits();
        updateUI(fruits);
    } <span class="hljs-keyword">catch</span> (e) {
        showError(e);
    }
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getFruits</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> {
        resolve([<span class="hljs-string">'apple'</span>, <span class="hljs-string">'orange'</span>, <span class="hljs-string">'banana'</span>]);
    });
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">updateUI</span>(<span class="hljs-params">items</span>) </span>{
    <span class="hljs-keyword">let</span> output = <span class="hljs-string">''</span>;
    items.forEach(<span class="hljs-function"><span class="hljs-params">item</span> =&gt;</span> {
        output += <span class="hljs-string">`
        &lt;li&gt;<span class="hljs-subst">${item}</span>&lt;/li&gt;        
        `</span>
    })
    <span class="hljs-keyword">const</span> list = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'.list-item'</span>);
    list.innerHTML += output;
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">showError</span>(<span class="hljs-params">e</span>) </span>{
    <span class="hljs-keyword">const</span> error = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'#error'</span>);
    error.appendChild(<span class="hljs-built_in">document</span>.createTextNode(e));
}

fetchFruits();
</code></pre>
<p>When the promise is rejected, the 'showError' function defined within the catch block will be executed as shown in the code below.</p>
<p>When Promise is rejected:</p>
<pre><code class="lang-js"><span class="hljs-comment">//Using Async Await</span>
<span class="hljs-keyword">const</span> fetchFruits = <span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">try</span> {
        <span class="hljs-keyword">const</span> fruits = <span class="hljs-keyword">await</span> getFruits();
        updateUI(fruits);
    } <span class="hljs-keyword">catch</span> (e) {
        showError(e);
    }
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getFruits</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> {
        reject([<span class="hljs-string">'apple'</span>, <span class="hljs-string">'orange'</span>, <span class="hljs-string">'banana'</span>]);
    });
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">updateUI</span>(<span class="hljs-params">items</span>) </span>{
    <span class="hljs-keyword">let</span> output = <span class="hljs-string">''</span>;
    items.forEach(<span class="hljs-function"><span class="hljs-params">item</span> =&gt;</span> {
        output += <span class="hljs-string">`
        &lt;li&gt;<span class="hljs-subst">${item}</span>&lt;/li&gt;        
        `</span>
    })
    <span class="hljs-keyword">const</span> list = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'.list-item'</span>);
    list.innerHTML += output;
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">showError</span>(<span class="hljs-params">e</span>) </span>{
    <span class="hljs-keyword">const</span> error = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'#error'</span>);
    error.appendChild(<span class="hljs-built_in">document</span>.createTextNode(e));
}

fetchFruits();
</code></pre>
<p>You can play around with the code <a target="_blank" href="https://codepen.io/skaytech/pen/RwrgrxX">over here</a></p>
<p>The biggest benefit of using async/await is that it makes code much more readable and maintainable. It makes the code feel it's streamlined and structured similarly as though it is synchronous.</p>
<h2 id="conclusion">Conclusion</h2>
<p>A quick recap of what we've covered in this article:</p>
<ul>
<li>What is Async/Await?</li>
<li>How do they work?</li>
<li>Async functions return promise by default.</li>
<li>Error Handling</li>
</ul>
<p>I hope you enjoyed the three-part series on asynchronous functions. Don't forget to subscribe to my newsletter &amp; connect with me on Twitter <a target="_blank" href="https://twitter.com/skay_tech">@skaytech</a></p>
<h3 id="you-will-also-enjoy-the-following-articles">You will also enjoy the following articles:</h3>
<ul>
<li><a target="_blank" href="https://blog.skay.dev/all-you-need-to-about-javascript-objects">JavaScript Objects</a></li>
<li><a target="_blank" href="https://blog.skay.dev/javascript-functions-everything-you-must-know-as-a-javascript-newbie">JavaScript Functions</a></li>
<li><a target="_blank" href="https://blog.skay.dev/es6-higher-order-functions">ES6 - Higher-Order Functions</a></li>
<li><a target="_blank" href="https://blog.skay.dev/what-is-currying-in-javascript">What is currying?</a></li>
<li><a target="_blank" href="https://blog.skay.dev/introduction-to-big-o-notation-time-space-complexity">A Guide to Big O, Time &amp; Space Complexity</a></li>
<li><a target="_blank" href="https://blog.skay.dev/understanding-hoisting">Understanding Hoisting</a></li>
<li><a target="_blank" href="https://blog.skay.dev/es6-spread-operator">ES6 - Spread Operator</a></li>
<li><a target="_blank" href="https://blog.skay.dev/how-to-make-an-argument-required-in-javascript">How to make an argument "required" in JavaScript?</a></li>
<li><a target="_blank" href="https://blog.skay.dev/5-must-read-tips-to-write-a-killer-blog-article">5 Must-Read Tips to write a killer blog article</a></li>
<li><a target="_blank" href="https://blog.skay.dev/what-are-git-hooks">What are Git Hooks?</a></li>
<li><a target="_blank" href="https://blog.skay.dev/javascript-event-loop-explained">What is Event Loop in JavaScript?</a></li>
<li><a target="_blank" href="https://blog.skay.dev/a-basic-introduction-to-webpack">A Basic introduction to Webpack</a></li>
<li><a target="_blank" href="https://blog.skay.dev/es6-arrow-functions">ES6 =&gt; Arrow Functions</a></li>
</ul>
]]></content:encoded></item><item><title><![CDATA[All you need to about JavaScript Objects]]></title><description><![CDATA[Introduction
Almost everything in JavaScript is an Object. In this article, I'll share my understanding of what an object is, how an object can be created, modified, and how its properties can be accessed.
What is an Object?
An object is a collection...]]></description><link>https://blog.skay.dev/all-you-need-to-about-javascript-objects</link><guid isPermaLink="true">https://blog.skay.dev/all-you-need-to-about-javascript-objects</guid><category><![CDATA[100DaysOfCode]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[Web Development]]></category><dc:creator><![CDATA[Skay]]></dc:creator><pubDate>Fri, 23 Oct 2020 14:28:33 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1603438880394/MC2mj5RB3.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="introduction">Introduction</h2>
<p>Almost everything in JavaScript is an Object. In this article, I'll share my understanding of what an object is, how an object can be created, modified, and how its properties can be accessed.</p>
<h2 id="what-is-an-object">What is an Object?</h2>
<p>An object is a collection of properties having name-value pairs. The value of the property could be a simple string, integer, boolean, or could be another object or even a function.</p>
<pre><code class="lang-js"><span class="hljs-comment">//Object with the value String</span>
<span class="hljs-keyword">const</span> name = <span class="hljs-string">'Skay'</span>;

<span class="hljs-comment">//Object with the value Integer</span>
<span class="hljs-keyword">let</span> number = <span class="hljs-number">5</span>;

<span class="hljs-comment">//Object with the value boolean</span>
<span class="hljs-keyword">let</span> isCorrect = <span class="hljs-literal">true</span>;

<span class="hljs-comment">//Object with the value of another Object</span>
<span class="hljs-keyword">const</span> car = {
    <span class="hljs-attr">make</span> : <span class="hljs-string">'Honda'</span>,
    <span class="hljs-attr">modal</span> : <span class="hljs-string">'CR-v'</span>,
    <span class="hljs-attr">year</span> : <span class="hljs-number">2018</span>
}

<span class="hljs-comment">//Object with the value of a function</span>
<span class="hljs-keyword">const</span> greeting = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-string">'Hello, How are you?'</span>;
}
</code></pre>
<h2 id="object-creation">Object Creation</h2>
<p>In JavaScript, there are many ways to create an object. Let us look at each of them with examples.</p>
<h3 id="using-the-object-literal">Using the Object Literal</h3>
<p>The simplest form of object creation is using the Object literal, which we saw in the 'Car' example above. Let us look at another example of the book object.</p>
<pre><code class="lang-js">    <span class="hljs-keyword">const</span> book = {
        <span class="hljs-attr">name</span> : <span class="hljs-string">'Atomic Habits'</span>,
        <span class="hljs-attr">author</span> : <span class="hljs-string">'James Clear'</span>,
        <span class="hljs-attr">year</span> : <span class="hljs-number">2018</span>
    }
</code></pre>
<p>The values assigned to an object within the braces are referred to as the properties of an object.</p>
<h3 id="using-the-new-keyword">Using the New Keyword</h3>
<p>Using the new keyword, you can first create the object and then add the properties to it later.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> book = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Object</span>();
book.name = <span class="hljs-string">'Atomic Habits'</span>;
book.author = <span class="hljs-string">'James Clear'</span>;
book.year = <span class="hljs-number">2018</span>;

<span class="hljs-built_in">console</span>.log(book);
</code></pre>
<h3 id="using-a-constructor">Using a Constructor</h3>
<p>Constructors are code snippets that run while creating an object. You can optionally pass parameters while the creation of an object. Generally, in modern object-oriented languages such as Java, the constructors are defined within a class and are used to create an instance of the class.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> Movie = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">title, director, genre, rating</span>) </span>{
    <span class="hljs-built_in">this</span>.title = title;
    <span class="hljs-built_in">this</span>.director = director;
    <span class="hljs-built_in">this</span>.genre = genre;
    <span class="hljs-built_in">this</span>.rating = rating;
    <span class="hljs-built_in">this</span>.getDetails = <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">`<span class="hljs-subst">${<span class="hljs-built_in">this</span>.title}</span> of the genre <span class="hljs-subst">${<span class="hljs-built_in">this</span>.genre}</span> has a rating of <span class="hljs-subst">${<span class="hljs-built_in">this</span>.rating}</span>. It is directed by <span class="hljs-subst">${<span class="hljs-built_in">this</span>.director}</span>.`</span>);
    }
}

<span class="hljs-keyword">const</span> matrix = <span class="hljs-keyword">new</span> Movie(<span class="hljs-string">'The Matrix'</span>, <span class="hljs-string">'The Wachowski Brothers'</span>, <span class="hljs-string">'Sci-Fi'</span>, <span class="hljs-number">8.7</span>);
<span class="hljs-keyword">const</span> inception = <span class="hljs-keyword">new</span> Movie(<span class="hljs-string">'Inception'</span>, <span class="hljs-string">'Christopher Nolan'</span>, <span class="hljs-string">'Sci-Fi'</span>, <span class="hljs-number">8.8</span>);

<span class="hljs-built_in">console</span>.log(matrix.getDetails());
<span class="hljs-built_in">console</span>.log(inception.getDetails());
</code></pre>
<p>It is considered a good practice to use Capital letters while naming the constructor.</p>
<p>This method of creating an object is favored in real-life projects since you can create as many objects as you would like by using the new keyword and if you need to add/edit a property at a later time, it's very simple to do it within the constructor.</p>
<p>Another thing to note in the above example is that the property getDetails is also a function. What this means is that you can literally define anything as a property to an object, such as a literal, object, or a function that I mentioned at the beginning of this article.</p>
<p>There are two more ways to create an object. Using the object.create() method which was introduced with ES5 and using the prototype pattern. These will require some understanding of JavaScript Prototype and I will cover this in a separate article.</p>
<h3 id="accessing-the-properties-of-an-object">Accessing the Properties of an Object</h3>
<p>The properties assigned to an object can be accessed using one of the two ways:</p>
<p>a. Using the '.' operator. </p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> book = {
        <span class="hljs-attr">name</span> : <span class="hljs-string">'Atomic Habits'</span>,
        <span class="hljs-attr">author</span> : <span class="hljs-string">'James Clear'</span>,
        <span class="hljs-attr">year</span> : <span class="hljs-number">2018</span>
    }

<span class="hljs-built_in">console</span>.log(book.name);
</code></pre>
<p>b. Using the square brackets []</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> book = {
        <span class="hljs-attr">name</span> : <span class="hljs-string">'Atomic Habits'</span>,
        <span class="hljs-attr">author</span> : <span class="hljs-string">'James Clear'</span>,
        <span class="hljs-attr">year</span> : <span class="hljs-number">2018</span>
    }

<span class="hljs-built_in">console</span>.log(book[<span class="hljs-string">"author"</span>];
</code></pre>
<p>The dot operator is generally more popular in use, due to it's the simplicity of use. However, the other option is particularly useful in two instances</p>
<p>a. When the property name contains a space and cannot be used with a dot operator. Although, the chances of this are pretty rare.</p>
<p>b. If a property name of the object is only known at run-time. In the example below, person.propName will give an undefined, whereas a person[propName] will display 38.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> person = {
    <span class="hljs-attr">name</span> : <span class="hljs-string">'Skay'</span>,
    <span class="hljs-attr">age</span> : <span class="hljs-number">38</span>
}

<span class="hljs-keyword">const</span> propName = <span class="hljs-string">'age'</span>;

<span class="hljs-comment">//Will output 38</span>
<span class="hljs-built_in">console</span>.log(person[propName]);

<span class="hljs-comment">//Will output undefined</span>
<span class="hljs-built_in">console</span>.log(person.propName);
</code></pre>
<h2 id="objects-are-referenced-by-type">Objects are referenced by Type</h2>
<p>When a variable is assigned a non-primitive value (except string, integer, boolean, null, and undefined), then the variable is assigned a reference to the value and not the actual value.</p>
<p>If you did not understand a word of the above statement, don't worry, let us break it down by using the below code as a reference:</p>
<h4 id="step-1">Step 1</h4>
<p>As you can see the variable 'person' is assigned the object {name : 'skay', age : 38}. But what happens internally is that, the object {name : 'skay', age : 38} is stored in a location in your computer's memory. </p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> person = {
    <span class="hljs-attr">name</span>: <span class="hljs-string">'Skay'</span>,
    <span class="hljs-attr">age</span>: <span class="hljs-number">38</span>
}

<span class="hljs-keyword">const</span> newPerson = person;

<span class="hljs-built_in">console</span>.log(newPerson === person);
</code></pre>
<h4 id="step-2">Step 2</h4>
<p>The memory location allocated to the object {name : 'skay', age : 38} is assigned to the variable 'person'.</p>
<h3 id="step-3">Step 3</h3>
<p>In the above code, when the newPerson variable is assigned to the person variable, then it also receives a reference of the same address location of the object {name : 'skay', age : 38} and hence the console.log(newPerson === person) will output the value of 'true'.</p>
<h2 id="conclusion">Conclusion</h2>
<p>If you gotten until here, thank you so much for taking the time to read through the article, and hope you've gained some insight into what JavaScript objects are. </p>
<p>Let me summarize what I have covered so far in this article.</p>
<ul>
<li>Except for primitive types such as strings, numbers, boolean, null, and undefined, everything else is an object in JavaScript. For example, an array is an object and so is a function.</li>
<li>In JavaScript objects are mutable, i.e. they can be changed.</li>
<li>Objects are referenced by type and hence the variable containing the object has a reference to the object and not the value.</li>
</ul>
<p>Hope you enjoyed this article. Don't forget to subscribe to my newsletter and connect with me on Twitter <a target="_blank" href="https://twitter.com/skay_tech">@skaytech</a></p>
<p>You might also be interested in:</p>
<ul>
<li><a target="_blank" href="https://blog.skay.dev/javascript-functions-everything-you-must-know-as-a-javascript-newbie">JavaScript Functions</a></li>
<li><a target="_blank" href="https://blog.skay.dev/es6-higher-order-functions">ES6 - Higher-Order Functions</a></li>
<li><a target="_blank" href="https://blog.skay.dev/what-is-currying-in-javascript">What is currying?</a></li>
<li><a target="_blank" href="https://blog.skay.dev/introduction-to-big-o-notation-time-space-complexity">A Guide to Big O, Time &amp; Space Complexity</a></li>
<li><a target="_blank" href="https://blog.skay.dev/understanding-hoisting">Understanding Hoisting</a></li>
<li><a target="_blank" href="https://blog.skay.dev/es6-spread-operator">ES6 - Spread Operator</a></li>
<li><a target="_blank" href="https://blog.skay.dev/how-to-make-an-argument-required-in-javascript">How to make an argument "required" in JavaScript?</a></li>
<li><a target="_blank" href="https://blog.skay.dev/5-must-read-tips-to-write-a-killer-blog-article">5 Must-Read Tips to write a killer blog article</a></li>
<li><a target="_blank" href="https://blog.skay.dev/what-are-git-hooks">What are Git Hooks?</a></li>
<li><a target="_blank" href="https://blog.skay.dev/javascript-event-loop-explained">What is Event Loop in JavaScript?</a></li>
<li><a target="_blank" href="https://blog.skay.dev/a-basic-introduction-to-webpack">A Basic introduction to Webpack</a></li>
<li><a target="_blank" href="https://blog.skay.dev/es6-arrow-functions">ES6 =&gt; Arrow Functions</a></li>
</ul>
]]></content:encoded></item><item><title><![CDATA[JavaScript Callbacks Explained]]></title><description><![CDATA[Introduction
I think Async is one of the most powerful yet not-so-direct concepts to grasp at first for JavaScript Newbies.
In this article, I have covered the following topics:

What does asynchronous execution mean?
What are higher-order functions ...]]></description><link>https://blog.skay.dev/javascript-callbacks-explained</link><guid isPermaLink="true">https://blog.skay.dev/javascript-callbacks-explained</guid><category><![CDATA[100DaysOfCode]]></category><category><![CDATA[JavaScript]]></category><dc:creator><![CDATA[Skay]]></dc:creator><pubDate>Thu, 22 Oct 2020 14:16:43 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1603376056026/TbPFtLm0H.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="introduction">Introduction</h2>
<p>I think Async is one of the most powerful yet not-so-direct concepts to grasp at first for JavaScript Newbies.</p>
<p>In this article, I have covered the following topics:</p>
<ul>
<li>What does asynchronous execution mean?</li>
<li>What are higher-order functions and callback functions?</li>
<li>How to create &amp; pass callback functions?</li>
<li>Inversion of Control</li>
</ul>
<h2 id="asynchronous-execution">Asynchronous Execution</h2>
<p>Let us first understand what an asynchronous activity is. Let us assume, you need to go to a laundromat to wash your clothes and to the bank to withdraw some money.</p>
<p>You first head over to the laundromat and put your clothes to wash and it says the wash/dry cycle will take about an hour. Instead of waiting in the laundromat for an hour, you decide to go to the bank instead which is a 20-min drive, and make the withdrawal. You realize you are still left with some time and make a quick stop at the supermarket and pick up a few things. Finally, at the end of the hour, you return to the laundromat to collect your clothes.</p>
<p>In the above example, while the clothes were being washed, you still proceeded to do other activities. This is precisely what asynchronous activity is all about. One program execution does not happen sequentially to other program executions.</p>
<h1 id="higher-order-function-and-callback">Higher-Order Function &amp; Callback</h1>
<p>In the example shown below, we have a simple function returning the sum of two numbers.</p>
<pre><code class="lang-js"><span class="hljs-comment">//Function returns the sum of two numbers</span>
<span class="hljs-keyword">const</span> add = <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 + b;
}

<span class="hljs-comment">//Output the sum of two numbers</span>
<span class="hljs-built_in">console</span>.log(add(<span class="hljs-number">2</span>, <span class="hljs-number">3</span>));
</code></pre>
<p>A cool thing that you can do in JavaScript language is that you can pass other functions to your function. If you would like to revisit JavaScript functions basics, you can read them <a target="_blank" href="https://blog.skay.dev/javascript-functions-everything-you-must-know-as-a-javascript-newbie">over here.</a></p>
<pre><code class="lang-js"><span class="hljs-comment">//Function returns the sum of two numbers</span>
<span class="hljs-keyword">const</span> add = <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 + b;
};

<span class="hljs-keyword">const</span> multiply = <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 * b;
};

<span class="hljs-keyword">const</span> calculate = <span class="hljs-function">(<span class="hljs-params">funcParam</span>) =&gt;</span> <span class="hljs-function">(<span class="hljs-params">a, b</span>) =&gt;</span> {
  <span class="hljs-keyword">return</span> funcParam(a, b);
};

<span class="hljs-comment">//PASSING FUNCTION AS AN ARGUMENT</span>
<span class="hljs-comment">//Pass the 'add' function to the 'calculate' function</span>
<span class="hljs-keyword">const</span> sum = calculate(add);
<span class="hljs-built_in">console</span>.log(sum(<span class="hljs-number">2</span>, <span class="hljs-number">3</span>)); <span class="hljs-comment">//Output the sum of two numbers -&gt; 5</span>

<span class="hljs-comment">//PASSING FUNCTION AS AN ARGUMENT</span>
<span class="hljs-comment">//Pass the multiply function to the 'calculate' function</span>
<span class="hljs-keyword">const</span> multi = calculate(multiply);
<span class="hljs-built_in">console</span>.log(multi(<span class="hljs-number">2</span>, <span class="hljs-number">3</span>)); <span class="hljs-comment">//Output the multiplication of two numbers -&gt; 6</span>
</code></pre>
<p>Things to note:</p>
<ul>
<li>The function 'add' is passed as an argument to the calculate function and assigned to the 'sum' variable. Likewise, the function 'multiply' is passed as an argument in the next line and assigned to the variable 'multi'.</li>
<li>The parameter 'funcParam' of the 'calculate' function holds a reference to either the 'add' or 'multiply' function based on what is passed in while invoking the function.</li>
</ul>
<p>NOTE: The function 'sum' or 'multi' is known as the 'higher-order function' and the function 'add' or 'multiply' that is passed as an argument is known as the 'callback'.</p>
<p>Using the above semantics, the same example can be demonstrated as shown below:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> callback = <span class="hljs-function">(<span class="hljs-params">a, b</span>) =&gt;</span> {
    <span class="hljs-keyword">return</span> a + b;
}

<span class="hljs-keyword">const</span> higherOrderFunction = <span class="hljs-function">(<span class="hljs-params">callback</span>) =&gt;</span> (a, b) {
    <span class="hljs-keyword">return</span> callback(a, b);
}
</code></pre>
<p>Callbacks are used everywhere in JavaScript. Array-based functions such as a map, filter, sort, etc. use callbacks and if you are already using JavaScript most likely you are already using them without realizing that they are callbacks.</p>
<h2 id="so-how-does-callback-help">So, How does Callback help?</h2>
<p>In most of the real-life applications we build, the UI will have to wait to fetch data from the backend, while the user continues to interact with the web application. This is exactly the use-case for callback functions.</p>
<p>Let us look at an example of a function making an external API call:</p>
<pre><code class="lang-js"><span class="hljs-comment">//Define the Github User ID</span>
<span class="hljs-keyword">const</span> userId = <span class="hljs-string">'skaytech'</span>;

<span class="hljs-comment">/*
Function to fetch data using XMLHTTPRequest
The function accepts a callback to invoke upon the success
*/</span>
<span class="hljs-keyword">const</span> fetchData = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">userId, callbacks, callback2</span>) </span>{
    <span class="hljs-comment">//Initialize xhr to a new XMLHttpRequest object </span>
    <span class="hljs-keyword">const</span> xhr = <span class="hljs-keyword">new</span> XMLHttpRequest();

    <span class="hljs-comment">// Define the parameters to call an External API</span>
    <span class="hljs-comment">// Calling the Github getUsers API by userId</span>
    <span class="hljs-comment">// Params are - HTTP Method name, URL, Async (true/false)</span>
    <span class="hljs-comment">// When the third param is 'true', it means it's an asynchronous request</span>
    xhr.open(
      <span class="hljs-string">'GET'</span>, <span class="hljs-string">`https://api.github.com/users/<span class="hljs-subst">${userId}</span>`</span>, <span class="hljs-literal">true</span>);

    <span class="hljs-comment">//The onload method will execute when a response has been received from external API</span>
    xhr.onload = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
        <span class="hljs-comment">//Checking for a response of 200 (It's a success (OK) response)</span>
        <span class="hljs-keyword">if</span> (xhr.status === <span class="hljs-number">200</span>) {
            <span class="hljs-comment">//On success - invoke the callback method passed to the function</span>
                        <span class="hljs-comment">//In this example - displayUserPicture function will be run</span>
            callback1(xhr.responseText);
        } <span class="hljs-keyword">else</span> {
            <span class="hljs-comment">//On Error - invoke the onError method and pass the HTTP status</span>
            callback2(xhr.status);
        }
    }

    <span class="hljs-comment">//Upon Send the XMLHttpRequest will actual be processed</span>
    <span class="hljs-comment">//This is the method that actually triggers the API call</span>
    xhr.send();

}

<span class="hljs-comment">//UI method to display the picture of Github User</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">displayUserPicture</span>(<span class="hljs-params">response</span>) </span>{
    <span class="hljs-keyword">const</span> data = <span class="hljs-built_in">JSON</span>.parse(response);
    <span class="hljs-keyword">const</span> imgUrl = data.avatar_url;
    <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'#userimg'</span>).setAttribute(<span class="hljs-string">'src'</span>, imgUrl);
}

<span class="hljs-comment">//UI method to display Error if the Github User does not exits</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">onError</span>(<span class="hljs-params">status</span>) </span>{
             <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'#userimg'</span>).style.display = <span class="hljs-string">'none'</span>;
  <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'#errorDiv'</span>).textContent = <span class="hljs-string">`Error Status: <span class="hljs-subst">${status}</span>`</span>;
}

<span class="hljs-comment">//Invoke the fetch data function</span>
<span class="hljs-comment">//Params - userId &amp; displayUserPicture is the callback function</span>
fetchData(userId, displayUserPicture, onError);
</code></pre>
<p>Things to note:</p>
<ul>
<li>In the above example, I have used the XMLHttpRequest which is used to make external API calls. This is one of the earliest methods in JavaScript to make API requests. You can read about them <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest">over here.</a></li>
<li>The function 'fetchData' accepts the callback methods 'displayUserPicture' and 'onError'.</li>
<li>If the HTTP response status is 200 then the function 'displayUserPicture' will be executed or else the function 'onError' will be executed.</li>
<li>Here the UI update method will not be invoked until the data from the external API is available. If it's successful, the GitHub user's image will be displayed and on error, the error status will be displayed on the UI.</li>
</ul>
<p>You can find play around with the above code <a target="_blank" href="https://codepen.io/skaytech/pen/QWyvpzq">over here.</a></p>
<h3 id="callback-hell">Callback Hell</h3>
<p>In the above example, we had seen that the callbacks are separate methods that are invoked from within the main function. Let us look at an example where instead of calling a separate function, you are nesting the function calls.</p>
<pre><code class="lang-js"><span class="hljs-comment">//Define the Github User ID</span>
<span class="hljs-keyword">const</span> userId = <span class="hljs-string">'skaytech'</span>;

<span class="hljs-comment">/*
Function to fetch data using XMLHTTPRequest
The function accepts a callback to invoke upon the success
*/</span>
<span class="hljs-keyword">const</span> fetchData = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">userId, callback1, callback2</span>) </span>{
    <span class="hljs-keyword">const</span> xhr = <span class="hljs-keyword">new</span> XMLHttpRequest();

    xhr.open(
        <span class="hljs-string">'GET'</span>, <span class="hljs-string">`https://api.github.com/users/<span class="hljs-subst">${userId}</span>`</span>, <span class="hljs-literal">true</span>);

    xhr.onload = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
        <span class="hljs-keyword">if</span> (xhr.status === <span class="hljs-number">200</span>) {
            <span class="hljs-comment">//Parse the incoming response to JSON object</span>
            <span class="hljs-keyword">const</span> data = <span class="hljs-built_in">JSON</span>.parse(response);
            <span class="hljs-comment">//Fetch the user's followers URL</span>
            <span class="hljs-keyword">const</span> followersUrl = data.followers_url;

            <span class="hljs-comment">//Create another XMLHttpRequest</span>
            <span class="hljs-keyword">const</span> xhr1 = <span class="hljs-keyword">new</span> XMLHttpRequest();

            xhr1.open(<span class="hljs-string">'GET'</span>, followersUrl, <span class="hljs-literal">true</span>);
            xhr1.onload = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
                <span class="hljs-keyword">if</span> (xhr.status === <span class="hljs-number">200</span>) {
                    <span class="hljs-comment">//Get the followers Data</span>
                } <span class="hljs-keyword">else</span> {
                    <span class="hljs-comment">//Show Error</span>
                }
            }
            xhr1.send();
        } <span class="hljs-keyword">else</span> {
            callback2(xhr.status);
        }
    }
    xhr.send();
}

<span class="hljs-comment">//Fetch the User's Github details based on the user ID</span>
fetchData(userId);
</code></pre>
<p>The code gets harder to read and maintain when the callback functions are invoked in a nested order and that's what usually referred to as callback hell.</p>
<p>Callbacks are considered hard for a fact that the human mind perceives things sequentially or in a linear fashion, whereas, the way callback works in an inverted manner. This brings us to the next topic, inversion of control.</p>
<h3 id="inversion-of-control">Inversion of Control</h3>
<p>When your main function invokes the callback function, it basically hands over the program execution to the callback function. In essence, the entire program's flow depends on the response of the callback function, and then it proceeds from there onward. This nature of program execution is referred to as inversion of control.</p>
<p>Let us take a simple example and look at what I mean:</p>
<pre><code class="lang-js"><span class="hljs-comment">//Displays the name on the console</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sayHello</span>(<span class="hljs-params">name</span>) </span>{
    <span class="hljs-comment">//Displays the name on the console</span>
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Hello <span class="hljs-subst">${name}</span>`</span>);
}

<span class="hljs-comment">//Function accepting the callback and a string parameter</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greeting</span>(<span class="hljs-params">callback, name</span>) </span>{
    <span class="hljs-comment">//The callback function passed here is 'SayHello'</span>
    <span class="hljs-keyword">return</span> callback(name);
}

<span class="hljs-comment">//Call the greeting function</span>
greeting(sayHello, <span class="hljs-string">'Skay'</span>);
</code></pre>
<p>Note: The execution of the function 'greeting' will be completed only after the execution of the function 'sayHello' (callback) completed. In essence, the flow of control is inverted.</p>
<h2 id="conclusion">Conclusion</h2>
<p>A quick recap on what we've covered in this article:</p>
<ul>
<li>What does asynchronous execution mean?</li>
<li>What are higher-order functions and callback functions?</li>
<li>How to create &amp; pass callback functions?</li>
<li>Inversion of Control</li>
</ul>
<p>I think we've covered in great detail on what Callback is all about and an excellent article to continue reading is on Promises and you find it <a target="_blank" href="https://blog.skay.dev/what-are-javascript-promises">over here</a></p>
<p>Don't forget to subscribe and connect with me on Twitter <a target="_blank" href="https://twitter.com/skay_tech">@skaytech</a></p>
<h3 id="youll-also-enjoy-the-following-articles">You'll also enjoy the following articles:</h3>
<ul>
<li><a target="_blank" href="https://blog.skay.dev/what-are-javascript-promises">What are JavaScript Promises</a></li>
<li><a target="_blank" href="https://blog.skay.dev/what-is-currying-in-javascript">What is currying in JavaScript?</a></li>
<li><a target="_blank" href="https://blog.skay.dev/es6-higher-order-functions">ES6 - Higher-Order Functions</a></li>
<li><a target="_blank" href="https://blog.skay.dev/es6-spread-operator">ES6 - Spread Operator</a></li>
<li><a target="_blank" href="https://blog.skay.dev/understanding-hoisting">Understanding Hoisting</a></li>
<li><a target="_blank" href="https://blog.skay.dev/introduction-to-big-o-notation-time-space-complexity">A Gentle introduction to the Big O Notation, Time &amp; Space Complexity</a></li>
<li><a target="_blank" href="https://blog.skay.dev/a-basic-introduction-to-webpack">A Basic Introduction to Webpack</a></li>
<li><a target="_blank" href="https://blog.skay.dev/javascript-event-loop-explained">What is Event Loop in JavaScript?</a></li>
<li><a target="_blank" href="https://blog.skay.dev/history-of-ecma-es5-es6-and-beyond">History of ECMAScript and beyond</a></li>
<li><a target="_blank" href="https://blog.skay.dev/understanding-closures">Understanding Closures</a></li>
</ul>
]]></content:encoded></item><item><title><![CDATA[What are JavaScript Promises?]]></title><description><![CDATA[Introduction
While JavaScript Async/Await have gained immense popularity over the recent years. It is important to understand Promises first, since, they lay the foundation over which Async/Await works. 
In this article, we will look at the following...]]></description><link>https://blog.skay.dev/what-are-javascript-promises</link><guid isPermaLink="true">https://blog.skay.dev/what-are-javascript-promises</guid><category><![CDATA[100DaysOfCode]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[promises]]></category><category><![CDATA[Web Development]]></category><dc:creator><![CDATA[Skay]]></dc:creator><pubDate>Sat, 17 Oct 2020 06:17:43 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1602914962976/K6uBZwNVY.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="introduction">Introduction</h2>
<p>While JavaScript Async/Await have gained immense popularity over the recent years. It is important to understand Promises first, since, they lay the foundation over which Async/Await works. </p>
<p>In this article, we will look at the following concepts:</p>
<ul>
<li>What are 'Promises'?</li>
<li>What are the various execution states of a 'Promise'?</li>
<li>How to create and modify a 'Promise'?</li>
<li>How to use the 'Then' &amp; 'Catch' blocks?</li>
<li>What is 'Promise Chaining'?</li>
</ul>
<h2 id="what-are-promises">What are  'Promises'?</h2>
<p>If you've ever been to a Starbucks during peak hours, you would have come across a scenario where the barista asks for your name and notes it down on your cup. When the order is ready, she calls out for you, so that you can pick up your order. Promises do exactly that.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1602915077035/zt2PljqX0.jpeg" alt="matt-hoffman-YdEpiHpwhyM-unsplash.jpg" /></p>
<p>Promises return back the execution status to the calling function to let them know what their current state of execution is.</p>
<h2 id="what-are-the-various-execution-states-of-a-promise">What are the various execution states of a 'Promise'?</h2>
<p>Promises are in one of the below three states:</p>
<ul>
<li>Pending - This is the state when the execution is still under processing.</li>
<li>Resolved - This is the state when the promise is fulfilled and the resolution will be returned back to the calling function.</li>
<li>Rejected - This is the state when something has gone wrong and the error will be returned back to the calling function.</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1602915163464/2eA8KXYv9.jpeg" alt="josh-redd-UGf37D6PMiQ-unsplash.jpg" /></p>
<p>If you remember <a target="_blank" href="https://blog.skay.dev/javascript-callbacks-explained">the callback example</a>, once the main function passes over the control to the callback function, the responsibility of returning the status of execution to the main function solely lies on the callback function. </p>
<p>'Promises' solve this problem by returning back the status of execution. Let's look at how to create a promise.</p>
<h2 id="how-to-create-and-modify-a-promise">How to create &amp; Modify a Promise?</h2>
<p>A promise can simply be created by calling the constructor.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> promise = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>();
</code></pre>
<p>A callback is generally passed to a Promise with the resolve and reject status as parameters as shown below.</p>
<pre><code class="lang-js"><span class="hljs-comment">//A new promise is created and an anonymous function is passed on resolve &amp; reject as the parameters</span>
<span class="hljs-keyword">const</span> promise = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> {
    <span class="hljs-comment">//After a timeout of 3 seconds the status of promise will be changed to resolved</span>
    <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
            resolve(); <span class="hljs-comment">//Promise status changes to resolve</span>
        }, <span class="hljs-number">3000</span>) <span class="hljs-comment">//End of setTimeout method - After 3 sec resolve will be run</span>
})

<span class="hljs-comment">//Displays the status of the promise immediately. Note that the above function will run after 3 seconds</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Status of Promise before being resolved: '</span>, promise);

<span class="hljs-comment">//Function will run after 5 seconds and hence will run after the promise has been resolved</span>
<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Status of Promise after being resolved: '</span>, promise);
}, <span class="hljs-number">5000</span>); <span class="hljs-comment">//Timeout set to 5 seconds</span>

<span class="hljs-comment">//Output</span>
<span class="hljs-comment">//Status of Promise before being resolved:  Promise {&lt;pending&gt;}</span>

<span class="hljs-comment">//After 5 seconds, the following will be output to the console</span>
<span class="hljs-comment">//Status of Promise after being resolved:  Promise {&lt;resolved&gt;: undefined}</span>
</code></pre>
<p>Things to note:</p>
<ul>
<li>A promise is created using the 'new' constructor.</li>
<li>To the promise constructor, an anonymous function (callback) is passed with the 'resolve' and 'reject' parameters.</li>
<li>The above example uses ES6 arrow functions and setTimeout for delaying the execution of the function. If you like a refresher on ES6 arrow functions, you can read <a target="_blank" href="https://blog.skay.dev/es6-arrow-functions">over here</a> &amp; about setTimeout function <a target="_blank" href="https://blog.skay.dev/when-to-use-settimeout-vs-setinterval">over here</a>.</li>
<li>The anonymous function changes the promise state to resolved after 3 seconds.</li>
<li>Hence, the first statement will output the status of promise as 'pending'.</li>
<li>The second anonymous function setTimeout will output the status of promise as 'resolved' since the function runs after 5 seconds and by then the previous anonymous function would have run and changed the status of promise to resolve.</li>
</ul>
<h2 id="the-then-and-catch-blocks">The 'Then' &amp; 'Catch' Blocks</h2>
<p>'Then' &amp; 'Catch' are two methods of the JavaScript object that can be invoked. When a promise is resolved, then the function that is passed to the 'then' will be invoked. Likewise, when a promise is rejected, the function passed to the 'catch' will be invoked.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1602915277459/WvHXil6P8.jpeg" alt="keith-johnston-3OQk-5DJTEE-unsplash.jpg" /></p>
<p>Let us take a look with at the following examples:</p>
<h3 id="promise-resolved">Promise (resolved)</h3>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> promise = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> {
    <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
        resolve(); <span class="hljs-comment">//Promise is resolved after 3 seconds</span>
    }, <span class="hljs-number">3000</span>)
});

promise.then(onSuccess); <span class="hljs-comment">//the function 'onSuccess' will be invoked upon resolve()</span>
promise.catch(onError);

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">onSuccess</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'The Promise has been resolved'</span>);
} <span class="hljs-comment">//onSuccess() will be executed since the promise is resolved()</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">onError</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'An error has been encountered'</span>);
}
</code></pre>
<h3 id="promise-rejected">Promise (rejected)</h3>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> promise = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> {
    <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
        reject(); <span class="hljs-comment">//Promise is rejected after 3 seconds</span>
    }, <span class="hljs-number">3000</span>)
});

promise.then(onSuccess);
promise.catch(onError); <span class="hljs-comment">// the function 'onError' will be invoked on reject()</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">onSuccess</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'The Promise has been resolved'</span>);
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">onError</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'An error has been encountered'</span>);
} <span class="hljs-comment">//onError() will be executed since the promise is rejected()</span>
</code></pre>
<h2 id="a-practical-use-case-of-a-promise">A Practical Use-Case of a 'Promise'</h2>
<p>Let us modify the previous example to use promise instead of callback.</p>
<pre><code class="lang-js"><span class="hljs-comment">//Define the Github User ID</span>
<span class="hljs-keyword">const</span> userId = <span class="hljs-string">'skaytech'</span>;

<span class="hljs-comment">/*
Function to fetch data using XMLHTTPRequest
The function uses Promise to resolve, reject based on the external API response
*/</span>
<span class="hljs-keyword">const</span> fetchData = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">userId</span>) </span>{

    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> {
        <span class="hljs-comment">//Initialize xhr to a new XMLHttpRequest object </span>
        <span class="hljs-keyword">const</span> xhr = <span class="hljs-keyword">new</span> XMLHttpRequest();

        <span class="hljs-comment">// Define the parameters to call an External API</span>
        <span class="hljs-comment">// Calling the Github getUsers API by userId</span>
        <span class="hljs-comment">// Params are - HTTP Method name, URL, Async (true/false)</span>
        <span class="hljs-comment">// When the third param is 'true', it means it's an asynchronous request</span>
        xhr.open(
            <span class="hljs-string">'GET'</span>, <span class="hljs-string">`https://api.github.com/users/<span class="hljs-subst">${userId}</span>`</span>, <span class="hljs-literal">true</span>);

        <span class="hljs-comment">//The onload method will execute when a response has been received from external API</span>
        xhr.onload = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
            <span class="hljs-comment">//Checking for a response of 200 (It's a success (OK) response)</span>
            <span class="hljs-keyword">if</span> (xhr.status === <span class="hljs-number">200</span>) {
                <span class="hljs-comment">//On success - resolve the promise and send response as a parameter</span>
                resolve(xhr.responseText);
            } <span class="hljs-keyword">else</span> {
                <span class="hljs-comment">//On Error - reject the promise and pass the HTTP status as a parameter</span>
                reject(xhr.status);
            }
        }

        <span class="hljs-comment">//Upon Send the XMLHttpRequest will actual be processed</span>
        <span class="hljs-comment">//This is the method that actually triggers the API call</span>
        xhr.send();
    });
}

<span class="hljs-comment">//UI method to display the picture of Github User</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">displayUserPicture</span>(<span class="hljs-params">response</span>) </span>{
    <span class="hljs-keyword">const</span> data = <span class="hljs-built_in">JSON</span>.parse(response);
    <span class="hljs-keyword">const</span> imgUrl = data.avatar_url;
    <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'#userimg'</span>).setAttribute(<span class="hljs-string">'src'</span>, imgUrl);
}

<span class="hljs-comment">//UI method to display Error if the Github User does not exits</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">onError</span>(<span class="hljs-params">status</span>) </span>{
    <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'#userimg'</span>).style.display = <span class="hljs-string">'none'</span>;
    <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'#errorDiv'</span>).textContent = <span class="hljs-string">`Error Status: <span class="hljs-subst">${status}</span>`</span>;
}

<span class="hljs-comment">//Invoke the fetch data function &amp; pass the userId as a parameter</span>
<span class="hljs-comment">//then function is invoked upon success</span>
<span class="hljs-comment">//catch function will be invoked upon error</span>
fetchData(userId)
    .then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> displayUserPicture(response))
    .catch(<span class="hljs-function"><span class="hljs-params">err</span> =&gt;</span> onError(err));
</code></pre>
<p>Things that have changed from the previous example:</p>
<ul>
<li>The XMLHttpRequest is wrapped within a promise.</li>
<li>Upon Success, the promise is resolved &amp; the response data is passed as a parameter to the displayUserPicture function.</li>
<li>Upon Error, the promise is rejected &amp; the error is passed to the onError function.</li>
</ul>
<p>You can play around with the code <a target="_blank" href="https://codepen.io/skaytech/pen/BajRxRj">over here</a></p>
<h2 id="promise-chaining">Promise Chaining</h2>
<p>One last concept, before we are done and dusted with Promises. If you remember, we talked about how asynchronous programming generally isn't naturally tuned to the way we think. Chaining takes care of that and it is easier to explain with the following example.</p>
<pre><code class="lang-js"><span class="hljs-comment">/*
    A function that returns a resolved Promise after 2 seconds
    After a duration of 2 seconds, 'Wake up in the morning' is displayed on the console
*/</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getPromise</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =&gt;</span> {
        <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
            <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Wake up in the morning'</span>);
            resolve();
        }, <span class="hljs-number">2000</span>);
    });
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">workout</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Workout'</span>);
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">breakfast</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Breakfast'</span>);
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">college</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'College'</span>);
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sleep</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Sleep'</span>);

    <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>();
}

<span class="hljs-comment">/*
    Promise Chaining in action
    Each then resolves and invokes the next function one by one
    For e.g. If getPromise() is successful, then workout() is invoked and only if
    workout() is successful, then breakfast() is invoked and so on
*/</span>
getPromise()
    .then(workout)
    .then(breakfast)
    .then(college)
    .then(sleep)
    .catch(<span class="hljs-function"><span class="hljs-params">err</span> =&gt;</span> <span class="hljs-built_in">console</span>.log(err));

<span class="hljs-comment">//Output</span>
<span class="hljs-comment">/*
Wake up in the morning
 Workout
 Breakfast
 College
 Sleep
 Error
    at sleep 
*/</span>
</code></pre>
<p>As you can see, chaining improves readability a lot and it's a lot easier to follow the code and it appears sequentially processing, while it is actually asynchronous in nature.</p>
<h2 id="conclusion">Conclusion</h2>
<p>A quick recap on what we've covered in this article:</p>
<ul>
<li>What is a Promise?</li>
<li>What are the execution states in a promise?</li>
<li>How to create and modify a promise?</li>
<li>The 'Then' &amp; 'Catch' blocks of a promise.</li>
<li>Promise Chaining.</li>
</ul>
<p>Hope you enjoyed the article. Don't forget to subscribe to my newsletter and you can follow me on Twitter <a target="_blank" href="https://twitter.com/skay_tech">@skaytech</a></p>
<h3 id="you-will-also-like-the-following-articles">You will also like the following articles:</h3>
<ul>
<li><a target="_blank" href="https://blog.skay.dev/javascript-functions-everything-you-must-know-as-a-javascript-newbie">JavaScript Functions</a></li>
<li><a target="_blank" href="https://blog.skay.dev/es6-higher-order-functions">ES6 - Higher-Order Functions</a></li>
<li><a target="_blank" href="https://blog.skay.dev/what-is-currying-in-javascript">What is currying?</a></li>
<li><a target="_blank" href="https://blog.skay.dev/introduction-to-big-o-notation-time-space-complexity">A Guide to Big O, Time &amp; Space Complexity</a></li>
<li><a target="_blank" href="https://blog.skay.dev/understanding-hoisting">Understanding Hoisting</a></li>
<li><a target="_blank" href="https://blog.skay.dev/es6-spread-operator">ES6 - Spread Operator</a></li>
<li><a target="_blank" href="https://blog.skay.dev/how-to-make-an-argument-required-in-javascript">How to make an argument "required" in JavaScript?</a></li>
<li><a target="_blank" href="https://blog.skay.dev/5-must-read-tips-to-write-a-killer-blog-article">5 Must-Read Tips to write a killer blog article</a></li>
<li><a target="_blank" href="https://blog.skay.dev/what-are-git-hooks">What are Git Hooks?</a></li>
<li><a target="_blank" href="https://blog.skay.dev/javascript-event-loop-explained">What is Event Loop in JavaScript?</a></li>
<li><a target="_blank" href="https://blog.skay.dev/a-basic-introduction-to-webpack">A Basic introduction to Webpack</a></li>
<li><a target="_blank" href="https://blog.skay.dev/es6-arrow-functions">ES6 =&gt; Arrow Functions</a></li>
</ul>
]]></content:encoded></item><item><title><![CDATA[JS Functions - Everything you must know as a JavaScript Newbie!!]]></title><description><![CDATA[Introduction
Functions are one of the most fundamental concepts of JavaScript that you must ensure to get a good understanding of. It could be a little challenging for Newbies since a JS function can be defined in multiple forms. In this article, I'l...]]></description><link>https://blog.skay.dev/javascript-functions-everything-you-must-know-as-a-javascript-newbie</link><guid isPermaLink="true">https://blog.skay.dev/javascript-functions-everything-you-must-know-as-a-javascript-newbie</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[100DaysOfCode]]></category><category><![CDATA[programming]]></category><category><![CDATA[Web Development]]></category><dc:creator><![CDATA[Skay]]></dc:creator><pubDate>Thu, 15 Oct 2020 06:29:12 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1602699285764/JgOyH3wrv.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="introduction">Introduction</h2>
<p>Functions are one of the most fundamental concepts of JavaScript that you must ensure to get a good understanding of. It could be a little challenging for Newbies since a JS function can be defined in multiple forms. In this article, I'll be covering the various ways you can define a JavaScript function and its relevant use-cases.</p>
<p>Before you dive in, if you haven't read my article on <a target="_blank" href="https://blog.skay.dev/all-you-need-to-about-javascript-objects">JavaScript Objects</a>, I would strongly recommend you do so before we proceed. Since it provides you the right foundation to build upon.</p>
<h2 id="what-is-a-function">What is a function?</h2>
<p>On the lighter side, whenever I think about a JavaScript function, I visualize a Chameleon. In a sense, it can essentially be defined in numerous ways.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1602743233316/GTW8KvF7b.jpeg" alt="claudel-rheault-nMJKAXHBLLI-unsplash.jpg" /></p>
<p>If you are to define a function, it is simply a set of statements defined in a certain order to perform an action. Let us look at the various ways a function can be defined with an example.</p>
<h3 id="a-simple-function">A Simple Function</h3>
<p>A simple function will contain the 'function' keyword followed by the function name and a set of angular brackets () which can accept optional parameters. The parameters passed within the angular brackets can be used inside the function body. The content within the function's curly braces {} is referenced as the function body. Let us look at a few examples below.</p>
<pre><code class="lang-js"><span class="hljs-comment">//FUNCTION DECLARATION - No Parameters</span>
<span class="hljs-comment">//Function (keyword) followed by the name of the function (sayHello)</span>
<span class="hljs-comment">//Followed by a set of '()' that can optionally accept parameters</span>
<span class="hljs-comment">//The statements within the '{}' is the function body</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sayHello</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Hello'</span>);
}

<span class="hljs-comment">//Function can be invoked using the Function Name</span>
sayHello(); <span class="hljs-comment">//Output -&gt; Hello</span>

<span class="hljs-comment">//FUNCTION DECLARATION - 1 Parameter</span>
<span class="hljs-comment">//The '()' accepts the name parameter</span>
<span class="hljs-comment">//Using the backticks `` we can reference the variable 'name' using the syntax ${}</span>
<span class="hljs-comment">//Use of ${variable} was introduced with ES6</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greet</span>(<span class="hljs-params">name</span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Hello <span class="hljs-subst">${name}</span>`</span>);
}

<span class="hljs-comment">//Invoking the function 'greet'</span>
greet(<span class="hljs-string">'Skay'</span>); <span class="hljs-comment">//Output -&gt; Hello Skay</span>

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">displayFullName</span>(<span class="hljs-params">firstName, lastName</span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`The Full Name is <span class="hljs-subst">${firstName}</span> <span class="hljs-subst">${lastName}</span>`</span>);
}

<span class="hljs-comment">//Invoking the function 'displayFullName'</span>
displayFullName(<span class="hljs-string">'John'</span>, <span class="hljs-string">'Smith'</span>); <span class="hljs-comment">//Output -&gt; The Full Name is John Smith</span>
</code></pre>
<h3 id="a-function-that-can-return-values">A Function that can return values</h3>
<p>The above examples demonstrated functions that execute the set of statements within the function body. Let us look at examples of functions that can return a value or a set of values to the invoking statement.</p>
<pre><code class="lang-js"><span class="hljs-comment">//A simple function that accepts 'color' as a parameter</span>
<span class="hljs-comment">//The function checks the color and returns a String with the name of a fruit matching the color</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">nameFruitByColor</span>(<span class="hljs-params">color</span>) </span>{
    <span class="hljs-keyword">if</span>(color === <span class="hljs-string">'red'</span>) {
        <span class="hljs-keyword">return</span> <span class="hljs-string">'apple'</span>;
    } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (color === <span class="hljs-string">'yellow'</span>) {
        <span class="hljs-keyword">return</span> <span class="hljs-string">'banana'</span>;
    } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (color === <span class="hljs-string">'green'</span>) {
        <span class="hljs-keyword">return</span> <span class="hljs-string">'watermelon'</span>;
    }
}

<span class="hljs-comment">//Display the value on console returned by the function 'nameFruitByColor'</span>
<span class="hljs-built_in">console</span>.log(nameFruitByColor(<span class="hljs-string">'red'</span>));
<span class="hljs-comment">//Output -&gt; apple</span>
</code></pre>
<p>The above example shows that the function returns a string. In fact, anything can be returned from a function such as a string, number, boolean, object, etc. </p>
<p>Up until now, we've seen some relatively simple examples of functions. Now, let's look at some complex variations of function declarations.</p>
<h3 id="anonymous-functions">Anonymous Functions</h3>
<p>A JavaScript function is referred to as an anonymous function when you omit the 'Function Name' from the declaration. But, the catch is that it must be assigned to a variable. Let us look at the code below.</p>
<pre><code class="lang-js"><span class="hljs-comment">//Main things to note in the function declaration</span>
<span class="hljs-comment">//Function Name is omitted</span>
<span class="hljs-comment">//The function is assigned to a variable 'fullName'</span>
<span class="hljs-keyword">const</span> fullName = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">firstName, lastName</span>) </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-string">`The Full Name is <span class="hljs-subst">${firstName}</span> <span class="hljs-subst">${lastName}</span>`</span>;
}

<span class="hljs-comment">//If you console.log the 'fullName' variable as is then</span>
<span class="hljs-comment">//it returns the entire function</span>
<span class="hljs-built_in">console</span>.log(fullName);

<span class="hljs-comment">//If you console.log without any parameters</span>
<span class="hljs-comment">//It displays 'The Full Name is undefined undefined'</span>
<span class="hljs-built_in">console</span>.log(fullName());

<span class="hljs-comment">//If you console.log with parameters passed to the function</span>
<span class="hljs-comment">//It displays </span>
<span class="hljs-built_in">console</span>.log(fullName(<span class="hljs-string">'John'</span>, <span class="hljs-string">'Smith'</span>));
</code></pre>
<p>The above syntax is also referred to as a function expression. You can treat 'fullName' as the function name and hence it is used to invoke the function.</p>
<p>Now, function expressions are handy when you need to pass them as parameters to other functions.</p>
<p>Let us look at the following example in detail:</p>
<h4 id="step-1">Step 1:</h4>
<p>Define two function expressions, one to add two numbers and one to subtract two numbers. The functions also return the value of addition and subtraction to the invoking statement.</p>
<pre><code class="lang-js"><span class="hljs-comment">//Function 'add' returns sum of two numbers</span>
<span class="hljs-keyword">const</span> add = <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 + b;
}

<span class="hljs-comment">//Function 'subtract' returns difference of two numbers</span>
<span class="hljs-keyword">const</span> subtract = <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 - b;
}
</code></pre>
<h4 id="step-2">Step 2:</h4>
<p>Watch this declaration closely, the function 'calculate' has a simple function syntax, but it also accepts 'func' function as a parameter. In the return statement, when the code 'func(a, b)' runs, the function 'func' is invoked.</p>
<pre><code class="lang-js">
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">calculate</span>(<span class="hljs-params">func, a, b</span>) </span>{
  <span class="hljs-keyword">return</span> func(a, b);
}
</code></pre>
<h4 id="step-3">Step 3</h4>
<p>In the code below, we have two function expressions, calculateSum and calculateDifference.</p>
<p>In the first line, the 'calculate' function is called with the 'add' function and the numbers 6 and 4 are passed as parameters. The output of the function will be number 10.</p>
<p>In the second line, the 'calculate' function is called with the 'subtract' function and the numbers 6 and 4 are passed as parameters. The output of the function will be number 2.</p>
<pre><code class="lang-js"><span class="hljs-comment">//Two functions are made over here</span>
<span class="hljs-comment">//First call is to the 'calculate' function with the parameters 'add', 6 and 4</span>
<span class="hljs-comment">//The second call is to the 'add' function that is passed as a parameter</span>
<span class="hljs-keyword">const</span> calculateSum = calculate(add, <span class="hljs-number">6</span>, <span class="hljs-number">4</span>);

<span class="hljs-built_in">console</span>.log(calculateSum); <span class="hljs-comment">//10</span>

<span class="hljs-comment">//Two functions are made over here</span>
<span class="hljs-comment">//First call is to the 'calculate' function with the parameters 'subtract', 6 and 4</span>
<span class="hljs-comment">//The second call is to the 'subtract' function that is passed as a parameter</span>
<span class="hljs-keyword">const</span> calculateDifference =  calculate(subtract, <span class="hljs-number">6</span>, <span class="hljs-number">4</span>);

<span class="hljs-built_in">console</span>.log(calculateDifference); <span class="hljs-comment">//2</span>
</code></pre>
<p>Hope you were able to follow the above example. This pattern is heavily used in AJAX when you pass callback functions to handle success or failure scenarios.</p>
<h3 id="nested-functions">Nested Functions</h3>
<p>Nested functions are functions that contain one or more functions inside them. The inner functions can further contain functions and so on. Let us look at the code below to understand better.</p>
<pre><code class="lang-js"><span class="hljs-comment">//A Simple Function called myWorld that contains two inner functions</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">myWorld</span>(<span class="hljs-params"></span>) </span>{

    <span class="hljs-comment">//Inner Function that displays My Hobbies</span>
    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">myHobbies</span>(<span class="hljs-params"></span>) </span>{
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Music &amp; Programming'</span>);
    }

    <span class="hljs-comment">//Inner Function that displays My Bank Balance</span>
    <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">myBankBalance</span>(<span class="hljs-params"></span>) </span>{
        <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Not enough money to diplay balance!!!'</span>);
    }

    myHobbies();

}

<span class="hljs-comment">//Invoking the outer function will invoke the inner function myHobbies() defined within it's body</span>
<span class="hljs-comment">//Output -&gt; Music &amp; Programming</span>
myWorld();

<span class="hljs-comment">//Will display an error - Cannot read property, since myBankBalance() is a private function</span>
myWorld().myBankBalance();
</code></pre>
<p>Couple of things to note from the above code:</p>
<ul>
<li>The myWorld function contains 2 inner functions myHobbies and myBankBalance.</li>
<li>When myWorld function is invoked, it will in turn invoke the myHobbies function defined in its body.</li>
<li>The inner functions myHobbies &amp; myBankBalance have access to all the variables &amp; parameters of the outer function myWorld.</li>
<li>However, inner functions are like private implementations. They cannot be invoked from outside the function. Hence, the statement myWorld().myBankBalance() will display an error.</li>
</ul>
<p>The use of Inner functions is sort of a good starting point to understand a very important concept in JavaScript called 'Closures'. I'll discuss that in a separate article.</p>
<h2 id="immediately-invoked-function-expression-iife-pronounced-iffy">Immediately Invoked Function Expression (IIFE, pronounced 'iffy')</h2>
<p>An IIFE is an anonymous function expression that is invoked immediately. You can define an IIFE as shown in the code below.</p>
<pre><code class="lang-js"><span class="hljs-comment">//Syntax-1</span>
(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">param</span>)</span>{
    <span class="hljs-comment">//Functional Code</span>
}());

<span class="hljs-comment">//Syntax-2</span>
(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">param</span>)</span>{
    <span class="hljs-comment">//Functional Code</span>
})();
</code></pre>
<pre><code class="lang-js">(<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">'Say Hello'</span>);
}());
</code></pre>
<p>The above function will be self-invoked and will display the statement 'Say Hello'. You can read more about IIFE <a target="_blank" href="https://dev.to/skaytech/iife-immediately-invoking-function-expressions-1164">over here</a>.</p>
<h3 id="constructor-functions">Constructor Functions</h3>
<p>One of the features of object-oriented is the use of a constructor to create objects. JavaScript supports this feature through constructor functions. A constructor function can be used to create many objects with predefined properties and methods. Let us look at the below example to understand it better. </p>
<pre><code class="lang-js"><span class="hljs-comment">//Constructor Function Phone that accepts three parameters make, model and color </span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Phone</span>(<span class="hljs-params">make, model, color</span>) </span>{
    <span class="hljs-comment">//All parameters passed to the function are assigned as properties to the Phone object</span>
    <span class="hljs-built_in">this</span>.make = make;
    <span class="hljs-built_in">this</span>.model = model;
    <span class="hljs-built_in">this</span>.color = color;

    <span class="hljs-comment">//Method that will display the Phone's model clicking a selfie</span>
    <span class="hljs-built_in">this</span>.clickSelfie = <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">`<span class="hljs-subst">${<span class="hljs-built_in">this</span>.model}</span> is clicking a selfie`</span>);
    }

    <span class="hljs-comment">//Displays the color of the phone</span>
    <span class="hljs-built_in">this</span>.displayColor = <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">`The color of the phone is <span class="hljs-subst">${<span class="hljs-built_in">this</span>.color}</span>`</span>);
    }
}

<span class="hljs-keyword">const</span> iPhoneX = <span class="hljs-keyword">new</span> Phone(<span class="hljs-string">'Apple'</span>, <span class="hljs-string">'iPhoneX'</span>, <span class="hljs-string">'Red'</span>);
<span class="hljs-keyword">const</span> onePlus7 = <span class="hljs-keyword">new</span> Phone(<span class="hljs-string">'One Plus'</span>, <span class="hljs-string">'One Plus 7'</span>, <span class="hljs-string">'Blue'</span>);

iPhoneX.clickSelfie();
onePlus7.clickSelfie();

iPhoneX.displayColor();
onePlus7.displayColor();
</code></pre>
<p>Couple of things to note from the above example:</p>
<ul>
<li>The function 'Phone' accepts 3 parameters and when a 'new' Phone object is created, it sets the parameters to the object's properties.</li>
<li>To create an object using the Constructor Function, you must use the 'new' keyword.</li>
<li>The 'this' keyword refers to the 'Phone' instance. So, when the statement iPhoneX = new Phone('Apple', 'iPhoneX', 'Red') is executed, the parameter 'Apple' will be set to the iPhoneX's property called 'make'. Whereas in the case of onePlus7, the make property will be One Plus. Hope that makes sense.</li>
<li>Further, you can invoke all methods defined inside the function using the dot-operator. In the above example, iPhoneX.clickSelfie(); will output 'iPhoneX is clicking a selfie'. Whereas onePlus7.clickSelfie() will output 'One Plus 7 is clicking a selfie'.</li>
<li>Also, it is considered best practice to name constructor functions using the Capital letter.</li>
</ul>
<h4 id="a-word-of-caution">A Word of Caution!</h4>
<p>Always remember to use the 'new' keyword to create objects from constructor functions. Forgetting the 'new' keyword and trying to create an object like the code shown below, will result in the object being created in the global window object which is <strong>really really</strong> bad.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> samsungGalaxy = Phone(<span class="hljs-string">'Samsung'</span>, <span class="hljs-string">'Galaxy S20'</span>, <span class="hljs-string">'Gray'</span>);
</code></pre>
<p>By default, the keyword 'this' points to the global window object unless specified explicitly and hence when the 'new' keyword was not used, the object was being created as a part of the global window object.</p>
<p>There's a way to circumvent the above problem using the 'strict' mode on. Strict mode enforces coding guidelines and throws an error whenever it encounters unsafe code. You can use 'strict' mode as shown below.</p>
<pre><code class="lang-js"><span class="hljs-meta">'use strict'</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Phone</span>(<span class="hljs-params">make, model, color</span>) </span>{
    ......
    ......
}
</code></pre>
<h2 id="arrow-functions">Arrow Functions</h2>
<p>With ES6, JavaScript introduced Arrow Functions. It is a topic that needs a dedicated article and you can read more about it <a target="_blank" href="https://blog.skay.dev/es6-arrow-functions">over here.</a></p>
<h2 id="conclusion">Conclusion</h2>
<p>I hope you enjoyed the article. I hope I have covered everything there's to know about JavaScript functions. Please leave your comments, likes and share it with other JavaScript newbies out there.</p>
<p>Don't forget to subscribe to my newsletter and follow me on twitter <a target="_blank" href="https://twitter.com/skay_tech">@skaytech</a>.</p>
<h3 id="you-might-also-be-interested-in">You might also be interested in:</h3>
<ul>
<li><a target="_blank" href="https://blog.skay.dev/what-is-currying-in-javascript">What is currying?</a></li>
<li><a target="_blank" href="https://blog.skay.dev/introduction-to-big-o-notation-time-space-complexity">A Guide to Big O, Time &amp; Space Complexity</a></li>
<li><a target="_blank" href="https://blog.skay.dev/understanding-hoisting">Understanding Hoisting</a></li>
<li><a target="_blank" href="https://blog.skay.dev/es6-spread-operator">ES6 - Spread Operator</a></li>
<li><a target="_blank" href="https://blog.skay.dev/how-to-make-an-argument-required-in-javascript">How to make an argument "required" in JavaScript?</a></li>
<li><a target="_blank" href="https://blog.skay.dev/5-must-read-tips-to-write-a-killer-blog-article">5 Must-Read Tips to write a killer blog article</a></li>
<li><a target="_blank" href="https://blog.skay.dev/what-are-git-hooks">What are Git Hooks?</a></li>
<li><a target="_blank" href="https://blog.skay.dev/javascript-event-loop-explained">What is Event Loop in JavaScript?</a></li>
<li><a target="_blank" href="https://blog.skay.dev/a-basic-introduction-to-webpack">A Basic introduction to Webpack</a></li>
<li><a target="_blank" href="https://blog.skay.dev/es6-arrow-functions">ES6 =&gt; Arrow Functions</a></li>
</ul>
]]></content:encoded></item><item><title><![CDATA[ES6 - Higher-Order Functions]]></title><description><![CDATA[Introduction
In this article, we will first understand what a higher-order function is and then look at a few code examples of the popular higher-order functions such as forEach, map, filter, reduce, etc.
What are Higher Order Functions?
It is import...]]></description><link>https://blog.skay.dev/es6-higher-order-functions</link><guid isPermaLink="true">https://blog.skay.dev/es6-higher-order-functions</guid><category><![CDATA[100DaysOfCode]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[webdev]]></category><dc:creator><![CDATA[Skay]]></dc:creator><pubDate>Wed, 14 Oct 2020 06:05:13 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1602620023523/eBV61raeg.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="introduction">Introduction</h2>
<p>In this article, we will first understand what a higher-order function is and then look at a few code examples of the popular higher-order functions such as forEach, map, filter, reduce, etc.</p>
<h2 id="what-are-higher-order-functions">What are Higher Order Functions?</h2>
<p>It is important to first understand what first-class citizens are before we move to higher-order functions.</p>
<h2 id="first-class-citizens">First-Class Citizens</h2>
<p>In JavaScript, functions are treated as 'First Class' citizens. The reason is that in JavaScript a function is fundamentally an object.</p>
<p>Let us take a quick example to explain this better. The below code is an example of a simple function.</p>
<pre><code class="lang-js"><span class="hljs-comment">//A simple function</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sayHello</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Hello'</span>);
}

<span class="hljs-comment">//Invoke the function</span>
sayHello(); <span class="hljs-comment">//output -&gt; Hello</span>
</code></pre>
<p>When we say that Functions are objects, we can assign properties to the function similar to an object as shown below.</p>
<pre><code class="lang-js"><span class="hljs-comment">//Since the function is essentially an object, you can add properties to it</span>
sayHello.greet = <span class="hljs-string">'Namaste'</span>;

<span class="hljs-built_in">console</span>.log(sayHello.greet); <span class="hljs-comment">// Output -&gt; Namaste</span>
</code></pre>
<p><strong><em>Note: While we can assign an attribute to a function. It is generally considered a bad practice. If you must add an attribute, then ensure you use an object.</em></strong></p>
<p>You can also assign variables to a function as the code example shown below: </p>
<pre><code class="lang-js"><span class="hljs-comment">//A simple function</span>
<span class="hljs-keyword">const</span> sayHello = <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">'Hello'</span>);
}

<span class="hljs-comment">//Invoke the function</span>
sayHello(); <span class="hljs-comment">//output -&gt; Hello</span>
</code></pre>
<p>The above examples are that of 'First-Class' functions.</p>
<h2 id="higher-order-functions">Higher-Order Functions</h2>
<p>Higher-order functions are functions that take other functions as arguments or functions that return a function as their result.</p>
<p>The below code example will hopefully make the above explanation more clear.</p>
<pre><code class="lang-js"><span class="hljs-comment">//Function Sum of two arguments a &amp; b</span>
<span class="hljs-keyword">const</span> sum = <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 + b;
};

<span class="hljs-comment">//Higher order function - takes 'func' as an argument &amp; returns a 'func' for execution</span>
<span class="hljs-keyword">const</span> higherOrderFunction = <span class="hljs-function">(<span class="hljs-params">func</span>) =&gt;</span> <span class="hljs-function">(<span class="hljs-params">a, b</span>) =&gt;</span> {
  <span class="hljs-keyword">return</span> func(a, b);
};
<span class="hljs-keyword">const</span> sumFor = higherOrderFunction(sum);

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

<span class="hljs-comment">/**
 *  The Output of sumFor (HigherOrderFunction) is
 *  (a, b) =&gt; {
 *     return func(a, b);
 *  }
 * 
 */</span>

<span class="hljs-built_in">console</span>.log(sumFor(<span class="hljs-number">2</span>, <span class="hljs-number">3</span>)); <span class="hljs-comment">//Output -&gt; 5</span>
</code></pre>
<p>Things to note:</p>
<ul>
<li>The function 'higherOrderFunction' accepts a function 'func' as a parameter.</li>
<li>The function 'func' that is passed in as a parameter is referred to as a callback.</li>
</ul>
<p>Array.prototype.forEach, Array.prototype.map, Array.prototype.filter are few examples of high-order functions introduced with ES5.</p>
<p>Let's dive into the actual functions.</p>
<h2 id="arrayforeach">Array.forEach</h2>
<p>The forEach function was introduced with ES5 as Array.prototype.forEach and with ES6, it's simply referenced as Array.forEach.</p>
<p><strong><em>Syntax: Array.forEach( callback( currentValue, currentIndex, array));</em></strong></p>
<p>The callback function receives three parameters:</p>
<ul>
<li>The current element value - Mandatory</li>
<li>The current element index - Optional</li>
<li>The array that is being traversed.</li>
</ul>
<p>Let us look at a code example:</p>
<pre><code class="lang-js"><span class="hljs-comment">//An array of Marvel Movies with the title &amp; year of release</span>
<span class="hljs-keyword">const</span> marvelMovies = [
  {
    <span class="hljs-attr">title</span>: <span class="hljs-string">"Iron Man"</span>,
    <span class="hljs-attr">year</span>: <span class="hljs-number">2008</span>,
  },
  {
    <span class="hljs-attr">title</span>: <span class="hljs-string">"The Avengers"</span>,
    <span class="hljs-attr">year</span>: <span class="hljs-number">2012</span>,
  },
  {
    <span class="hljs-attr">title</span>: <span class="hljs-string">"Doctor Strange"</span>,
    <span class="hljs-attr">year</span>: <span class="hljs-number">2016</span>,
  },
  {
    <span class="hljs-attr">title</span>: <span class="hljs-string">"Avengers: Infinity War"</span>,
    <span class="hljs-attr">year</span>: <span class="hljs-number">2018</span>,
  },
  {
    <span class="hljs-attr">title</span>: <span class="hljs-string">"Avengers: End Game"</span>,
    <span class="hljs-attr">year</span>: <span class="hljs-number">2019</span>,
  },
];

<span class="hljs-comment">//forEach loops through each movie &amp; prints the name of the title &amp; year it was released on the console</span>
<span class="hljs-comment">//The anonymous function accepts 'movie' as an argument which matches with the current element</span>
marvelMovies.forEach(<span class="hljs-function">(<span class="hljs-params">movie</span>) =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`The title of the movie is $<span class="hljs-subst">${movie.title}</span>`</span>);
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`<span class="hljs-subst">${movie.year}</span> is the year the movie was released.`</span>);
});

<span class="hljs-comment">/*
Output
---------
The title of the movie is $Iron Man
2008 is the year the movie was released.
The title of the movie is $The Avengers
2012 is the year the movie was released.
The title of the movie is $Doctor Strange
2016 is the year the movie was released.
The title of the movie is $Avengers: Infinity War
2018 is the year the movie was released.
The title of the movie is $Avengers: End Game
2019 is the year the movie was released.
---------
*/</span>
</code></pre>
<p>Things to note:</p>
<ul>
<li>The callback function is an anonymous function. It is used in conjunction with an arrow function. If you would like a refresher on arrow function, you can read <a target="_blank" href="https://blog.skay.dev/es6-arrow-functions">over here</a>.</li>
<li>I have used 'movie' to reference the current element that is passed in as the argument. In reality, you can use any name to the variable you are referencing the current element.</li>
<li>The forEach loops through the 'marvelMovies' array and displays the title and the year of release on the console.</li>
</ul>
<h2 id="arraymap">Array.map</h2>
<p>The map function was introduced with ES5 as Array.prototype.map and with ES6, it's simply referenced as Array.map.</p>
<p><strong><em>Syntax: Array.map( callback( currentValue, currentIndex, array));</em></strong></p>
<p>The callback function receives three parameters:</p>
<ul>
<li>The current element value - Mandatory</li>
<li>The current element index - Optional</li>
<li>The array that is being traversed.</li>
</ul>
<p>The important thing to note here is that the 'map' function returns a 'new' array with the results of the callback function applied to every element of the original array, in the same order.</p>
<p>Let us take the same marvelMovies array and use the map function to rate only the movies with the title 'Avengers'.</p>
<pre><code class="lang-js"><span class="hljs-comment">//An array of Marvel Movies with the title &amp; year of release</span>
<span class="hljs-keyword">const</span> marvelMovies = [
  {
    <span class="hljs-attr">title</span>: <span class="hljs-string">"Iron Man"</span>,
    <span class="hljs-attr">year</span>: <span class="hljs-number">2008</span>,
  },
  {
    <span class="hljs-attr">title</span>: <span class="hljs-string">"The Avengers"</span>,
    <span class="hljs-attr">year</span>: <span class="hljs-number">2012</span>,
  },
  {
    <span class="hljs-attr">title</span>: <span class="hljs-string">"Doctor Strange"</span>,
    <span class="hljs-attr">year</span>: <span class="hljs-number">2016</span>,
  },
  {
    <span class="hljs-attr">title</span>: <span class="hljs-string">"Avengers: Infinity War"</span>,
    <span class="hljs-attr">year</span>: <span class="hljs-number">2018</span>,
  },
  {
    <span class="hljs-attr">title</span>: <span class="hljs-string">"Avengers: End Game"</span>,
    <span class="hljs-attr">year</span>: <span class="hljs-number">2019</span>,
  },
];

<span class="hljs-comment">//map Function</span>
<span class="hljs-comment">//marvelMovies.map function will return a new array that'll be assigned to newMarvelMovies</span>
<span class="hljs-keyword">const</span> newMarvelMovies = marvelMovies.map(<span class="hljs-function">(<span class="hljs-params">marvelMovie</span>) =&gt;</span> {

        <span class="hljs-comment">//Check if the title contains 'Avengers'</span>
    <span class="hljs-keyword">if</span>(marvelMovie.title.includes(<span class="hljs-string">'Avengers'</span>)) {
                <span class="hljs-comment">//Add the 'rating' atrribute to the current element</span>
        marvelMovie[<span class="hljs-string">'rating'</span>] = <span class="hljs-number">5</span>;
    }
        <span class="hljs-comment">//the element will be returned as a part of the anonymous function</span>
        <span class="hljs-comment">//the element will be added as a part of the new array being returned from the map function</span>
    <span class="hljs-keyword">return</span> marvelMovie;
});

<span class="hljs-comment">//Display the value of the new Array 'newMarvelMovies'</span>
<span class="hljs-built_in">console</span>.log(newMarvelMovies);

<span class="hljs-comment">/*
Output -&gt;
0: {title: "Iron Man", year: 2008}
1: {title: "The Avengers", year: 2012, rating: 5}
2: {title: "Doctor Strange", year: 2016}
3: {title: "Avengers: Infinity War", year: 2018, rating: 5}
4: {title: "Avengers: End Game", year: 2019, rating: 5}
*/</span>
</code></pre>
<p>Things to Note:</p>
<ul>
<li>The 'map' function returns a 'new' array.</li>
<li>In this example, I've used 'marvelMovie' name for the current element, just to demonstrate that any name can be used for referencing the current element.</li>
<li>The main use-case for a 'map' function is to edit or manipulate the elements of the array.</li>
</ul>
<h2 id="arrayfilter">Array.filter</h2>
<p>The filter function was introduced with ES5 as Array.prototype.filter and with ES6, it's simply referenced as an Array.filter.</p>
<p><strong><em>Syntax: Array.filter( callback( currentValue, currentIndex, array));</em></strong></p>
<p>The callback function receives three parameters:</p>
<ul>
<li>The current element value - Mandatory</li>
<li>The current element index - Optional</li>
<li>The array that is being traversed.</li>
</ul>
<p>The filter function creates a new array with all the elements that pass the condition check specified in the callback function.</p>
<p>Let us look at the following code example:</p>
<pre><code class="lang-js"><span class="hljs-comment">//An array of Marvel Movies with the title &amp; year of release</span>
<span class="hljs-keyword">const</span> marvelMovies = [
  {
    <span class="hljs-attr">title</span>: <span class="hljs-string">"Iron Man"</span>,
    <span class="hljs-attr">year</span>: <span class="hljs-number">2008</span>,
  },
  {
    <span class="hljs-attr">title</span>: <span class="hljs-string">"The Avengers"</span>,
    <span class="hljs-attr">year</span>: <span class="hljs-number">2012</span>,
  },
  {
    <span class="hljs-attr">title</span>: <span class="hljs-string">"Doctor Strange"</span>,
    <span class="hljs-attr">year</span>: <span class="hljs-number">2016</span>,
  },
  {
    <span class="hljs-attr">title</span>: <span class="hljs-string">"Avengers: Infinity War"</span>,
    <span class="hljs-attr">year</span>: <span class="hljs-number">2018</span>,
  },
  {
    <span class="hljs-attr">title</span>: <span class="hljs-string">"Avengers: End Game"</span>,
    <span class="hljs-attr">year</span>: <span class="hljs-number">2019</span>,
  },
];

<span class="hljs-comment">//filter Function</span>
<span class="hljs-comment">//filteredMarvelMovies is a new array</span>
<span class="hljs-comment">//marvelMovies.filter function will return only the elements who's title does not contain 'Avengers'</span>
<span class="hljs-keyword">const</span> filteredMarvelMovies = marvelMovies.filter(<span class="hljs-function">(<span class="hljs-params">marvelMovie</span>) =&gt;</span> {
    <span class="hljs-keyword">return</span> !marvelMovie.title.includes(<span class="hljs-string">'Avengers'</span>);
});

<span class="hljs-comment">//Display the value of the new Array 'filteredMarvelMovies'</span>
<span class="hljs-built_in">console</span>.log(filteredMarvelMovies);

<span class="hljs-comment">/*
Output -&gt;
0: {title: "Iron Man", year: 2008}
1: {title: "Doctor Strange", year: 2016}
*/</span>
</code></pre>
<p>Things to Note:</p>
<ul>
<li>The 'filter' function returns a 'new' array.</li>
<li>The main use-case for a 'filter' function is to extract a specific sub-set of elements of the array matching a specific condition.</li>
</ul>
<h2 id="arraysome">Array.some</h2>
<p>The 'some' function was introduced with ES5 as Array.prototype.filter and with ES6, it's simply referenced as Array.some.</p>
<p><strong><em>Syntax: Array.some( callback( currentValue, currentIndex, array));</em></strong></p>
<p>The callback function receives three parameters:</p>
<ul>
<li>The current element value - Mandatory</li>
<li>The current element index - Optional</li>
<li>The array that is being traversed.</li>
</ul>
<p>The 'some' function tests for whether at least one element in the array passes the test condition specified in the callback function. It returns a boolean value.</p>
<p>Let us look at the following code example:</p>
<pre><code class="lang-js"><span class="hljs-comment">//An array of Marvel Movies with the title &amp; year of release</span>
<span class="hljs-keyword">const</span> marvelMovies = [
  {
    <span class="hljs-attr">title</span>: <span class="hljs-string">"Iron Man"</span>,
    <span class="hljs-attr">year</span>: <span class="hljs-number">2008</span>,
  },
  {
    <span class="hljs-attr">title</span>: <span class="hljs-string">"The Avengers"</span>,
    <span class="hljs-attr">year</span>: <span class="hljs-number">2012</span>,
  },
  {
    <span class="hljs-attr">title</span>: <span class="hljs-string">"Doctor Strange"</span>,
    <span class="hljs-attr">year</span>: <span class="hljs-number">2016</span>,
  },
  {
    <span class="hljs-attr">title</span>: <span class="hljs-string">"Avengers: Infinity War"</span>,
    <span class="hljs-attr">year</span>: <span class="hljs-number">2018</span>,
  },
  {
    <span class="hljs-attr">title</span>: <span class="hljs-string">"Avengers: End Game"</span>,
    <span class="hljs-attr">year</span>: <span class="hljs-number">2019</span>,
  },
];

<span class="hljs-comment">//some function</span>
<span class="hljs-comment">//Checks &amp; return a true if any one element title of the marvelMovies array </span>
<span class="hljs-comment">//matches with the string 'Thor'</span>
<span class="hljs-keyword">const</span> checkTitle = marvelMovies.some(<span class="hljs-function"><span class="hljs-params">movie</span> =&gt;</span> {
    <span class="hljs-keyword">return</span> movie.title === <span class="hljs-string">'Thor'</span>; 
});

<span class="hljs-comment">//Display the boolean value returned from the 'some' function</span>
<span class="hljs-built_in">console</span>.log(checkTitle); <span class="hljs-comment">//output -&gt; false</span>
</code></pre>
<p>I believe that the above code with the comments above is self-explanatory. Basically, the 'some' function checks if any one of the values in the array matches the condition (title matching 'Thor') and returns the value 'false', since there's no matching value in the marvelMovies array.</p>
<h2 id="arrayevery">Array.every</h2>
<p>The 'every' function was introduced with ES5 as Array.prototype.every and with ES6, it's simply referenced as Array.every.</p>
<p><strong><em>Syntax: Array.every( callback( currentValue, currentIndex, array));</em></strong></p>
<p>The callback function receives three parameters:</p>
<ul>
<li>The current element value - Mandatory</li>
<li>The current element index - Optional</li>
<li>The array that is being traversed.</li>
</ul>
<p>The 'every' function tests whether all the elements in the array pass the condition specified in the callback function. It returns a boolean value.</p>
<p>Let us look at the code example below:</p>
<pre><code class="lang-js"><span class="hljs-comment">//An array of Marvel Movies with the title, year of release &amp; rating</span>
<span class="hljs-keyword">const</span> marvelMovies = [
  {
    <span class="hljs-attr">title</span>: <span class="hljs-string">"Iron Man"</span>,
    <span class="hljs-attr">year</span>: <span class="hljs-number">2008</span>,
    <span class="hljs-attr">rating</span>: <span class="hljs-number">5</span>
  },
  {
    <span class="hljs-attr">title</span>: <span class="hljs-string">"The Avengers"</span>,
    <span class="hljs-attr">year</span>: <span class="hljs-number">2012</span>,
    <span class="hljs-attr">rating</span>: <span class="hljs-number">5</span>
  },
  {
    <span class="hljs-attr">title</span>: <span class="hljs-string">"Doctor Strange"</span>,
    <span class="hljs-attr">year</span>: <span class="hljs-number">2016</span>,
    <span class="hljs-attr">rating</span>: <span class="hljs-number">4</span>
  },
  {
    <span class="hljs-attr">title</span>: <span class="hljs-string">"Avengers: Infinity War"</span>,
    <span class="hljs-attr">year</span>: <span class="hljs-number">2018</span>,
    <span class="hljs-attr">rating</span>: <span class="hljs-number">5</span>
  },
  {
    <span class="hljs-attr">title</span>: <span class="hljs-string">"Avengers: End Game"</span>,
    <span class="hljs-attr">year</span>: <span class="hljs-number">2019</span>,
    <span class="hljs-attr">rating</span>: <span class="hljs-number">5</span>
  },
];

<span class="hljs-comment">//every function</span>
<span class="hljs-comment">//Checks &amp; returns a 'true' if all of elements in the marvelMovies array have a rating above 3</span>
<span class="hljs-keyword">const</span> checkRating = marvelMovies.every(<span class="hljs-function"><span class="hljs-params">movie</span> =&gt;</span> {
    <span class="hljs-keyword">return</span> movie.rating &gt; <span class="hljs-number">3</span>; 
});

<span class="hljs-comment">//Display the boolean value returned from the 'every' function</span>
<span class="hljs-built_in">console</span>.log(checkRating); <span class="hljs-comment">//output -&gt; true</span>
</code></pre>
<h2 id="arrayfind-and-arrayfindindex">Array.find &amp; Array.findIndex</h2>
<p>The find &amp; findIndex were introduced with ES5 as Array.prototype.find &amp; Array.prototype.findIndex. With ES6, they can be used as Array.find &amp; Array.findIndex.</p>
<p>The Array.find function returns the first matching element based on the condition specified in the callback function.</p>
<p>The Array.findIndex function returns the index of the first matching element based on the condition specified in the callback function.</p>
<p>The code example below gives a quick example of how to use find &amp; findIndex functions.</p>
<pre><code class="lang-js"><span class="hljs-comment">//An array of Marvel Movies with the title, year of release &amp; rating</span>
<span class="hljs-keyword">const</span> marvelMovies = [
  {
    <span class="hljs-attr">title</span>: <span class="hljs-string">"Iron Man"</span>,
    <span class="hljs-attr">year</span>: <span class="hljs-number">2008</span>,
    <span class="hljs-attr">rating</span>: <span class="hljs-number">4</span>
  },
  {
    <span class="hljs-attr">title</span>: <span class="hljs-string">"The Avengers"</span>,
    <span class="hljs-attr">year</span>: <span class="hljs-number">2012</span>,
    <span class="hljs-attr">rating</span>: <span class="hljs-number">3</span>
  },
  {
    <span class="hljs-attr">title</span>: <span class="hljs-string">"Doctor Strange"</span>,
    <span class="hljs-attr">year</span>: <span class="hljs-number">2016</span>,
    <span class="hljs-attr">rating</span>: <span class="hljs-number">4</span>
  },
  {
    <span class="hljs-attr">title</span>: <span class="hljs-string">"Avengers: Infinity War"</span>,
    <span class="hljs-attr">year</span>: <span class="hljs-number">2018</span>,
    <span class="hljs-attr">rating</span>: <span class="hljs-number">5</span>
  },
  {
    <span class="hljs-attr">title</span>: <span class="hljs-string">"Avengers: End Game"</span>,
    <span class="hljs-attr">year</span>: <span class="hljs-number">2019</span>,
    <span class="hljs-attr">rating</span>: <span class="hljs-number">5</span>
  },
];

<span class="hljs-comment">//find function</span>
<span class="hljs-comment">//Checks &amp; returns the first element that matches with the condition 'rating' equals 5</span>
<span class="hljs-keyword">const</span> found = marvelMovies.find(<span class="hljs-function"><span class="hljs-params">movie</span> =&gt;</span> {
    <span class="hljs-keyword">return</span> movie.rating === <span class="hljs-number">5</span>; 
});

<span class="hljs-comment">//Display the value of 'found' in the Console</span>
<span class="hljs-built_in">console</span>.log(found); 

<span class="hljs-comment">//output -&gt; {title: "Avengers: Infinity War", year: 2018, rating: 5}</span>
<span class="hljs-comment">//Even though the movie 'Avengers: End Game' also contains the rating 5,</span>
<span class="hljs-comment">//the first matching element is returned</span>

--------------------------------------------------------------------------

<span class="hljs-comment">//findIndex function</span>
<span class="hljs-comment">//Checks &amp; returns the first element that matches with the condition 'rating' equals 4</span>

<span class="hljs-keyword">const</span> foundIndex = marvelMovies.findIndex(<span class="hljs-function"><span class="hljs-params">movie</span> =&gt;</span> {
    <span class="hljs-keyword">return</span> movie.rating === <span class="hljs-number">4</span>; 
});

<span class="hljs-comment">//Display the value of 'foundIndex' in the Console</span>
<span class="hljs-built_in">console</span>.log(foundIndex); <span class="hljs-comment">//Output -&gt; 0 (Array index starts from 0)</span>
<span class="hljs-comment">//The first matching element with a rating 4 is present in Array Index location 0</span>
</code></pre>
<h2 id="arrayreduce">Array.reduce</h2>
<p>The 'reduce' function was introduced with ES5 as Array.prototype.reduce. With ES6, it's simplified as Array.reduce.</p>
<p><strong><em>Syntax: Array.reduce( callback( accumulator, currentValue, currentIndex, array));</em></strong></p>
<p>The callback function receives four parameters:</p>
<ul>
<li>The accumulator - Mandatory</li>
<li>The current element value - Mandatory</li>
<li>The current element index - Optional</li>
<li>The array that is being traversed.</li>
</ul>
<p>The reducer function executes the callback function specified over each element of the array to finally return a single value.</p>
<p>In simplified words, through each iteration, the value returned by the callback function is assigned to the 'accumulator' and ultimately becomes the final single resulting value.</p>
<p>The reduce function is the one that's most often not well understood. Hence, I'll take an example without reducer and then use a reducer to explain the code flow.</p>
<pre><code class="lang-js"><span class="hljs-comment">//The marvelMovies array contains the title &amp; profit each movie has made</span>
<span class="hljs-keyword">const</span> marvelMovies = [
    {
      <span class="hljs-attr">title</span>: <span class="hljs-string">"Iron Man"</span>,
      <span class="hljs-attr">profit</span>: <span class="hljs-number">100000</span>
    },
    {
      <span class="hljs-attr">title</span>: <span class="hljs-string">"The Avengers"</span>,
      <span class="hljs-attr">profit</span>: <span class="hljs-number">200000</span>
    },
    {
      <span class="hljs-attr">title</span>: <span class="hljs-string">"Doctor Strange"</span>,
      <span class="hljs-attr">profit</span>: <span class="hljs-number">200000</span>
    },
];    

<span class="hljs-comment">//Initialize the totalProfit variable</span>
<span class="hljs-keyword">let</span> totalProfit = <span class="hljs-number">0</span>;

<span class="hljs-comment">//Use forEach function to loop through the iteration &amp; add the profit of each movie</span>
<span class="hljs-comment">//to the totalProfit variable</span>
marvelMovies.forEach(<span class="hljs-function"><span class="hljs-params">movie</span> =&gt;</span> {
    totalProfit += movie.profit;
});

<span class="hljs-comment">//Display the value of totalProfit on console</span>
<span class="hljs-built_in">console</span>.log(totalProfit);
</code></pre>
<p>Let us see how the above code can be simplified using the reduce function.</p>
<pre><code class="lang-js"><span class="hljs-comment">//The marvelMovies array contains the title &amp; profit each movie has made</span>
<span class="hljs-keyword">const</span> marvelMovies = [
    {
      <span class="hljs-attr">title</span>: <span class="hljs-string">"Iron Man"</span>,
      <span class="hljs-attr">profit</span>: <span class="hljs-number">100000</span>
    },
    {
      <span class="hljs-attr">title</span>: <span class="hljs-string">"The Avengers"</span>,
      <span class="hljs-attr">profit</span>: <span class="hljs-number">200000</span>
    },
    {
      <span class="hljs-attr">title</span>: <span class="hljs-string">"Doctor Strange"</span>,
      <span class="hljs-attr">profit</span>: <span class="hljs-number">200000</span>
    },
];

<span class="hljs-comment">//Use reduce function to loop through the iteration &amp; add the movie's profit</span>
<span class="hljs-comment">//to the accumulator &amp; return it to the 'totalProfit' variable</span>
<span class="hljs-keyword">const</span> totalProfit = marvelMovies.reduce(<span class="hljs-function">(<span class="hljs-params">accumulator, movie</span>) =&gt;</span> {
    <span class="hljs-keyword">return</span> accumulator + movie.profit;
}, <span class="hljs-number">0</span>);

<span class="hljs-comment">//Display the value of totalProfit on console</span>
<span class="hljs-built_in">console</span>.log(totalProfit);
</code></pre>
<p>Things to note:</p>
<ul>
<li>The 'reduce' function takes in an 'accumulator' variable which holds the return value after every iteration.</li>
<li>In the example, the movie's profit is added to the 'accumulator' exactly as how 'total' did in the previous example.</li>
<li>The main use case of a reduce function is whenever any computation in an array needs to result in a singular value.</li>
</ul>
<h2 id="conclusion">Conclusion</h2>
<p>To summarize, we started with understanding what higher-order functions are and then saw a few code examples for functions such as forEach, map, filter, reduce, same &amp; every.</p>
<p>The important thing to remember is that both the functions map &amp; filter return 'new' arrays.</p>
<p>The 'map' function is primarily used to manipulate the values of elements of the array based on a condition, whereas, a filter function is used to generally filter out few elements from the array based on a condition. They are very heavily used in actual real-world applications especially with the React framework.</p>
<p>I hope you enjoyed this article. Don't forget to connect with me on Twitter <a target="_blank" href="https://twitter.com/skay_tech">@skaytech.</a></p>
<h3 id="you-will-also-enjoy-the-following-articles">You will also enjoy the following articles:</h3>
<ul>
<li><a target="_blank" href="https://blog.skay.dev/what-is-currying-in-javascript">What is currying?</a></li>
<li><a target="_blank" href="https://blog.skay.dev/introduction-to-big-o-notation-time-space-complexity">A Guide to Big O, Time &amp; Space Complexity</a></li>
<li><a target="_blank" href="https://blog.skay.dev/understanding-hoisting">Understanding Hoisting</a></li>
<li><a target="_blank" href="https://blog.skay.dev/es6-spread-operator">ES6 - Spread Operator</a></li>
<li><a target="_blank" href="https://blog.skay.dev/how-to-make-an-argument-required-in-javascript">How to make an argument "required" in JavaScript?</a></li>
<li><a target="_blank" href="https://blog.skay.dev/5-must-read-tips-to-write-a-killer-blog-article">5 Must-Read Tips to write a killer blog article</a></li>
<li><a target="_blank" href="https://blog.skay.dev/what-are-git-hooks">What are Git Hooks?</a></li>
<li><a target="_blank" href="https://blog.skay.dev/javascript-event-loop-explained">What is Event Loop in JavaScript?</a></li>
<li><a target="_blank" href="https://blog.skay.dev/a-basic-introduction-to-webpack">A Basic introduction to Webpack</a></li>
<li><a target="_blank" href="https://blog.skay.dev/es6-arrow-functions">ES6 =&gt; Arrow Functions</a></li>
</ul>
]]></content:encoded></item><item><title><![CDATA[A Gentle Introduction to the Big O Notation, Time & Space Complexity]]></title><description><![CDATA[Introduction
I have been in Software Engineering for a decade and a half and I am not a Computer Science graduate. Hence, I've never truly been taught Data Structures or Algorithms as a part of the course curriculum. Having said that, it did not stop...]]></description><link>https://blog.skay.dev/introduction-to-big-o-notation-time-space-complexity</link><guid isPermaLink="true">https://blog.skay.dev/introduction-to-big-o-notation-time-space-complexity</guid><category><![CDATA[data structures]]></category><category><![CDATA[algorithms]]></category><category><![CDATA[100DaysOfCode]]></category><category><![CDATA[programming]]></category><dc:creator><![CDATA[Skay]]></dc:creator><pubDate>Tue, 13 Oct 2020 16:19:28 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1602601249827/hsGCOWGoY.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="introduction">Introduction</h2>
<p>I have been in Software Engineering for a decade and a half and I am not a Computer Science graduate. Hence, I've never truly been taught Data Structures or Algorithms as a part of the course curriculum. Having said that, it did not stop me from being a good software engineer. </p>
<p>However, I was always curious to find out what it was all about and finally got some time to understand the absolute fundamentals. I'm hoping I can share my learnings in a way most of the non-computer science graduates can relate to.</p>
<p>In this article, we will look at the following three concepts:</p>
<ol>
<li>Big O Notation</li>
<li>Time Complexity</li>
<li>Space Complexity</li>
</ol>
<h2 id="big-o-notation">Big O Notation</h2>
<p>Big O notation is used in computer science to describe the performance or complexity of an algorithm. In simple words, it is used to denote how long an algorithm takes to run and how much memory it takes as the input to the algorithm grows over time.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1602601563285/XMy-vGguV.jpeg" alt="greg-nunes-mTNftwxCWCg-unsplash (1).jpg" /></p>
<p>With Big O Notation we express the runtime in terms of <em>how quickly it grows relative to the input, as the input gets larger</em>.</p>
<p>Let's expand on the words highlighted in 'italics' above:</p>
<ol>
<li><p>How quickly the runtime grows - It is generally hard to pin down the exact runtime used by your program, since, it is dependent on the processor speed and the other programs running on the computer at the moment. So, instead of talking about the 'runtime' directly, we use Big O Notation to talk about how quickly the runtime grows.</p>
</li>
<li><p>Relative to the input - If we were measuring our runtime directly, we could express our speed in seconds and minutes. Since we are measuring how quickly our runtime grows, we need to express our speed in terms of something else. With Big O, the size of the input is denoted as 'n'. So, we can say that as the runtime grows “on the order of the size of the input” (O(n)) or “on the order of the square of the size of the input” (O(n²)).</p>
</li>
<li><p>As the input gets larger - Our algorithm may have steps that seem expensive when the input size 'n' is small but is eclipsed eventually by other steps as '<em>n'</em> gets larger. For Big O Notation analysis, we care more about the stuff that grows fastest as the input grows, because everything else is quickly eclipsed as '<em>n'</em> gets very large.</p>
</li>
</ol>
<h2 id="time-complexity">Time Complexity</h2>
<p>We have sort of defined time complexity in the above section while introducing Big O Notation.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1602601605405/o4jH0_RgV.jpeg" alt="nathan-dumlao-5Hl5reICevY-unsplash.jpg" /></p>
<p>Time complexity is a function describing the amount of time an algorithm takes in terms of the amount of input to the algorithm. In layman’s terms, We can say time complexity is the sum of the number of times each statement gets executed.</p>
<p>There are three different types of time complexity:</p>
<ol>
<li>Constant Time ⇒ O(1) - The runtime does not change irrespective of the input size.</li>
<li>Linear Time ⇒ O(n) - The runtime grows linearly as the input 'n' grows.</li>
<li>Quadratic Time ⇒ O(n²) - The time it takes to complete a function increases like a quadratic function.</li>
</ol>
<p>Let us look at a few code examples to understand time complexity in a better way.</p>
<h3 id="constant-time-o1">Constant Time - O(1)</h3>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">displayFirstItem</span>(<span class="hljs-params">inpArray</span>) </span>{
    <span class="hljs-built_in">console</span>.log(inpArray[<span class="hljs-number">0</span>]);
}
</code></pre>
<p>The above function runs in <strong>O(1) time (or “constant time”)</strong> relative to its input. This means that the input array could be 1 item or 1,000 items, but this function would still run once and display the first item in the array.</p>
<h3 id="linear-time-on">Linear Time ⇒ O(n)</h3>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">displayAllItems</span>(<span class="hljs-params">inpArray</span>) </span>{
    inpArray.forEach(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">item</span>) </span>{
            <span class="hljs-built_in">console</span>.log(item);
  });
}
</code></pre>
<p>The above function runs in O(n) time (or “linear time”), where '<em>n</em>' is the number of items in the array. This means that if the array has 10 items, the function will run 10 times. If it has 1,000 items, the function will run 1,000 times.</p>
<h3 id="quadratic-time-on">Quadratic Time ⇒ O(n²)</h3>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">displayAllPossibleOrderedPairs</span>(<span class="hljs-params">inpArray</span>) </span>{
  inpArray.forEach(<span class="hljs-function"><span class="hljs-params">firstItem</span> =&gt;</span> {
    inpArray.forEach(<span class="hljs-function"><span class="hljs-params">secondItem</span> =&gt;</span> {
      <span class="hljs-built_in">console</span>.log(firstItem, secondItem);
    });
  });
}
</code></pre>
<p>In the above example, there are two loops nested. If the array has '<em>n'</em> items, the outer loop runs '<em>n'</em> times, and the inner loop runs '<em>n' times for each iteration of the outer loop</em>, giving us n² total prints. </p>
<p>Thus, the function runs in <strong>O(n²) time (or “quadratic time”)</strong>. If the array has 10 items, the function will run 100 times. If it has 1,000 items, it will run 1,000,000 times.</p>
<h2 id="the-worst-case-scenario">The Worst-Case Scenario</h2>
<p>The worst-case scenario is generally discussed with Big O Notation, since, there are often cases when the worst-case runtime is significantly worse than the best case runtime.</p>
<pre><code class="lang-jsx"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">contains</span>(<span class="hljs-params">haystack, needle</span>) </span>{

  <span class="hljs-comment">// Does the haystack contain the needle?</span>
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; haystack.length; i++) {
    <span class="hljs-keyword">if</span> (haystack[i] === needle) {
      <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
    }
  }

  <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;
}
</code></pre>
<p>In the above example, there might be 100 items in the haystack, but the first item might be the needle, in which case I would return in just 1 iteration of the loop. In such a case, it would appear O(1) to the runtime. </p>
<p>However, if the needle was to be found in the last iteration, then the runtime would be O(n). Hence, to be more specific, we could always say that the best-case scenario would have an O(1) runtime, and the worst-case scenario would be O(n) runtime.</p>
<h2 id="space-complexity">Space Complexity</h2>
<p>Space complexity is a function describing the amount of memory (space) an algorithm takes in terms of the amount of input to the algorithm. When we say “this algorithm takes constant extra space,” because the amount of extra memory needed doesn’t vary with the number of items processed.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1602601664268/K5H2Hm-Oh.jpeg" alt="patrick-mcmanaman-LN_g3qA8ohg-unsplash.jpg" /></p>
<p>So, the question is when would we compromise the speed of execution? A simple answer to that is the availability of resources that you can allocate to the running program.</p>
<p>Let us look at a few code examples:</p>
<h3 id="o1-fixed-space-for-a-fixed-input-size">O(1) - Fixed Space (For a fixed input size)</h3>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greet</span>(<span class="hljs-params">inpArray</span>) </span>{ 
 <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; inpArray.length; i++) {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Hello'</span>);
  }                                          
}
</code></pre>
<p>In the above example, the function takes O(1) i.e. fixed space, since the size of the input array does not change and we are only printing a String on the console.</p>
<h3 id="on-space-takes-grows-linearly">O(n) - Space takes grows linearly</h3>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greetNTimes</span>(<span class="hljs-params">n</span>) </span>{
  <span class="hljs-keyword">const</span> greetArray = [];
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; n; i++) {
    greetArray[i] = <span class="hljs-string">'Hello'</span>;
  }
  <span class="hljs-keyword">return</span> greetArray;
}
</code></pre>
<p>In the above function, as the size of input 'n' grows, the size of greetArray also grows. This requires additional memory resources to be allocated to accommodate the larger array.</p>
<h3 id="o1-fixed-space-for-a-variable-input-size">O(1) - Fixed Space (For a variable input size)</h3>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getLargestItem</span>(<span class="hljs-params">items</span>) </span>{
  <span class="hljs-keyword">let</span> largest = -<span class="hljs-built_in">Number</span>.MAX_VALUE;
  items.forEach(<span class="hljs-function"><span class="hljs-params">item</span> =&gt;</span> {
    <span class="hljs-keyword">if</span> (item &gt; largest) {
      largest = item;
    }
  });
  <span class="hljs-keyword">return</span> largest;
}
</code></pre>
<p>In the above example, while it the size of 'items' might change, it does not result in any allocation of memory resources. Hence, the function takes a fixed space or O(1) and does not depend on the input.</p>
<h2 id="conclusion">Conclusion</h2>
<h3 id="so-how-to-optimize-our-code">So how to optimize our code?</h3>
<p>Before optimizing the code, we should first understand the goal behind the optimization. Are we optimizing the code that is running a part of a batch job or are we optimizing a code that is being used in real-time while being accessed by thousands of users?</p>
<p>The goal is very important, since, then we can work towards finding out alternate solutions for the problem, and we can compare their runtimes to satisfy our goal. </p>
<p>While it might appear that constant time O(1) is probably better than linear time O(n), you must consider other factors such as is the code readable enough and is the code easy to maintain, how much memory is it consuming overall, etc. </p>
<p>I hope you enjoyed the article. I sincerely hope this article can act as a useful guide especially for the non-computer science graduates who want to venture into the world of Software development.</p>
<p>You can follow me on twitter <a target="_blank" href="https://twitter.com/skay_tech">@skaytech</a></p>
<h3 id="you-will-also-enjoy-the-following-articles">You will also enjoy the following articles:</h3>
<ul>
<li><a target="_blank" href="https://blog.skay.dev/es6-arrow-functions">ES6 - Arrow Functions</a></li>
<li><a target="_blank" href="https://blog.skay.dev/a-basic-introduction-to-webpack">A Basic Introduction to Webpack</a></li>
<li><a target="_blank" href="https://blog.skay.dev/es6-var-vs-let-and-const">ES6 - var, let &amp; const</a></li>
<li><a target="_blank" href="https://blog.skay.dev/understanding-closures">Understanding Closures</a></li>
<li><a target="_blank" href="https://blog.skay.dev/when-to-use-settimeout-vs-setinterval">setTimeout vs setInterval</a></li>
<li><a target="_blank" href="https://blog.skay.dev/what-is-this-in-javascript">What is 'this' in JavaScript?</a></li>
<li><a target="_blank" href="https://blog.skay.dev/iife-immediately-invoked-function-expressions">IIFE - Immediately Invoked Function Expressions</a></li>
<li><a target="_blank" href="https://blog.skay.dev/docker-fundamentals">Docker Fundamentals</a></li>
<li><a target="_blank" href="https://blog.skay.dev/history-of-ecma-es5-es6-and-beyond">History of ECMAScript</a></li>
<li><a target="_blank" href="https://blog.skay.dev/js-design-patterns-module-and-revealing-module-pattern">JS Design Patterns-Module &amp; Revealing Module Pattern</a></li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Understanding Hoisting]]></title><description><![CDATA[Introduction
Before we talk about hoisting, I think it is important to understand how the JavaScript engine looks at the code, interprets, and runs it. Once we understand this, hoisting becomes straightforward to explain.
Execution Context
JavaScript...]]></description><link>https://blog.skay.dev/understanding-hoisting</link><guid isPermaLink="true">https://blog.skay.dev/understanding-hoisting</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[100DaysOfCode]]></category><category><![CDATA[General Programming]]></category><dc:creator><![CDATA[Skay]]></dc:creator><pubDate>Mon, 12 Oct 2020 06:53:19 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1602470237190/0Tay1Yg07.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="introduction">Introduction</h2>
<p>Before we talk about hoisting, I think it is important to understand how the JavaScript engine looks at the code, interprets, and runs it. Once we understand this, hoisting becomes straightforward to explain.</p>
<h2 id="execution-context">Execution Context</h2>
<p>JavaScript engine breaks up the code into smaller segments to manage the complexity of interpreting and running it. If I have to explain this easier, think about a scenario where you attempt to write a web application. Your application typically would comprise of modules, functions, variable declarations, etc. Essentially, you have broken down the application into logical pieces in order to understand, maintain, and debug it.</p>
<p>Just like how modules, functions, etc. allow you to manage program complexity, Execution Context is the JavaScript engine's way to manage the complexity of interpreting the code. Hope makes things a little clearer.</p>
<h3 id="global-execution-context">Global Execution Context</h3>
<p>The first execution context that gets created when the JavaScript engine runs your code is called the “Global Execution Context”. Initially, this Execution Context will consist of two things - a global object and a variable called 'this'.</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/i/6x235t57veklvzeb335j.png" alt="Execution Context" /></p>
<p>The above image represents the global execution in the most basic form. The 'this' keyword references the global object which is the 'window' object.</p>
<h3 id="creation-and-execution-phases">Creation &amp; Execution Phases</h3>
<p>Now that we understand the global execution context, let us understand the two phases that exist while running any JavaScript program.</p>
<p>Let us consider the following code example:</p>
<pre><code class="lang-js"><span class="hljs-keyword">var</span> fruit = apple;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getFruit</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">return</span> fruit;
}
</code></pre>
<h4 id="creation-phase">Creation Phase</h4>
<p>The below diagram depicts how the Global Execution Context looks during the creation phase.</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/i/nsda0kz15oa6o0q2q56q.png" alt="Creation Phase" /></p>
<p>In the Global <code>Creation</code> phase, the JavaScript engine will:</p>
<ol>
<li>Create a global object.</li>
<li>Create an object called “this”.</li>
<li>Set up memory space for variables and functions.</li>
<li>Assign variable declarations a default value of “undefined” while placing any function declarations in memory.</li>
</ol>
<h4 id="execution-phase">Execution Phase</h4>
<p>The below diagram depicts how the Global Execution Context looks during the execution phase.</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/i/do5sic88x8iypp0yv55w.png" alt="Execution Phase" /></p>
<p>In the Global <code>Execution</code> Phase, the JavaScript engine will:</p>
<ol>
<li>Starts running the code line by line.</li>
<li>Assigns the 'real' values to the variables already present in the memory.</li>
</ol>
<p>Now that we've understood the creation &amp; execution phases, let us take another example and look at the output on the console.</p>
<pre><code class="lang-js"><span class="hljs-built_in">console</span>.log(<span class="hljs-string">`The fruit is <span class="hljs-subst">${fruit}</span>`</span>);
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">`The color is <span class="hljs-subst">${color}</span>`</span>);

<span class="hljs-keyword">var</span> fruit = <span class="hljs-string">'apple'</span>;
<span class="hljs-keyword">var</span> color = <span class="hljs-string">'red'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getFruit</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">return</span> fruit;
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getColor</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">return</span> color;
}

<span class="hljs-comment">//Output</span>
<span class="hljs-comment">//The fruit is undefined</span>
<span class="hljs-comment">//The color is undefined</span>
</code></pre>
<p>Things to note:</p>
<ul>
<li>During the creation phase, the variables 'fruit' &amp; 'color' are initialized with the values 'undefined'.</li>
<li>Hence when the console.log statement is encountered, the value 'undefined' is printed on the console.</li>
</ul>
<h2 id="hoisting">Hoisting</h2>
<p>The process of assigning variable declarations a default value of 'undefined' during the creation phase is called Hoisting.</p>
<p>The thing that’s confusing about “hoisting” is that nothing is actually “hoisted” or moved around. A lot of other explanations out there talk about how the code variables and functions are moved up the stack before execution without clearly talking about the creation and execution phases in the execution context.</p>
<p>A quick example of the below code will make sense after understanding hoisting.</p>
<pre><code class="lang-js"><span class="hljs-comment">//The Variable x is initialized</span>
x = <span class="hljs-number">5</span>;

<span class="hljs-comment">//Output the value of x multiplied by 2 on the console</span>
<span class="hljs-built_in">console</span>.log(x * <span class="hljs-number">2</span>);

<span class="hljs-comment">//The variable x is declared over here</span>
<span class="hljs-keyword">var</span> x;

<span class="hljs-comment">//Output -&gt; 10</span>
</code></pre>
<p>In the above code example, you would notice that the variable 'x' is initialized in the first statement and then in the last statement there's a declaration of x. But, when the JavaScript engine is in the creation phase, it moves up the declaration statement to the top of the stack and hence the above program would look like below when the JavaScript engine runs it.</p>
<pre><code class="lang-js"><span class="hljs-comment">//The variable x is declared over here</span>
<span class="hljs-keyword">var</span> x;

<span class="hljs-comment">//The Variable x is initialized</span>
x = <span class="hljs-number">5</span>;

<span class="hljs-comment">//Output the value of x multiplied by 2 on the console</span>
<span class="hljs-built_in">console</span>.log(x * <span class="hljs-number">2</span>);

<span class="hljs-comment">//Output -&gt; 10</span>
</code></pre>
<p>Ideally, I would have expected the JavaScript engine to throw an error for using a variable before it has been declared, but thanks to ES6, this problem has been addressed with let &amp; const. You can learn more about let &amp; const <a target="_blank" href="https://blog.skay.dev/es6-var-vs-let-and-const">over here</a>.</p>
<h2 id="what-is-not-hoisted">What is not Hoisted?</h2>
<p>While it might appear that the variable declarations using let &amp; const are not hoisted. There is a subtle difference, which I will try to explain.</p>
<p>The Variable declarations (variable name bindings to memory) with let and const are hoisted, but not their definitions (i.e. function definitions). Hence, they cannot be accessed for any read/write operations before their first assignment (initialization).</p>
<p>Let me try and explain the above concept using the code example below:</p>
<pre><code class="lang-js"><span class="hljs-comment">// console will return Uncaught ReferenceError: randomVar is not defined</span>
<span class="hljs-built_in">console</span>.log(randomVar); 

<span class="hljs-comment">// console will return Uncaught ReferenceError: Cannot access 'hoistedVar' before initialization</span>
<span class="hljs-built_in">console</span>.log(hoistedVar); 

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">log</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-comment">// console will not return any error as this line isn't actually executed yet, so hoistedVar is not being accessed</span>
  <span class="hljs-built_in">console</span>.log(hoistedVar); 
}

<span class="hljs-comment">// console will return Uncaught ReferenceError: Cannot access 'hoistedVar' before initialization</span>
log(); 

<span class="hljs-comment">// The hoistedVar is initialized here</span>
<span class="hljs-keyword">let</span> hoistedVar = <span class="hljs-string">"Hi"</span>;

<span class="hljs-comment">// console will log "Hi"</span>
log();
</code></pre>
<p>Important to note:</p>
<ul>
<li>The ReferenceError from trying to access the hoisted "let" variable declaration is different than the ReferenceError from trying to access a variable that has not been declared.</li>
</ul>
<p>To reiterate, all variable declarations are hoisted, but the 'let' and 'const' variable declarations will give a ReferenceError if the variable is accessed before being initialized.</p>
<p>In addition, 'Arrow Functions' are not hoisted by the JavaScript engine.</p>
<h2 id="conclusion">Conclusion</h2>
<p>Hoisting is nothing but the process of assigning variable declarations a default value of 'undefined' during the creation phase.</p>
<p>I would suggest that now that you immediately jump to my article on Closures since it's a continuation of the concepts described in this article. You can read it <a target="_blank" href="https://blog.skay.dev/understanding-closures">over here</a>.</p>
<p>I hope you enjoyed this article. Do connect with me on Twitter <a target="_blank" href="https://twitter.com/skay_tech">@skaytech</a></p>
<h3 id="you-may-also-be-interested-in">You may also be interested in:</h3>
<ul>
<li><a target="_blank" href="https://blog.skay.dev/understanding-closures">Understanding Closures</a></li>
<li><a target="_blank" href="https://blog.skay.dev/what-is-this-in-javascript">What is 'this' in JavaScript?</a></li>
<li><a target="_blank" href="https://blog.skay.dev/es6-var-vs-let-and-const">The WAR - var vs let vs const</a></li>
<li><a target="_blank" href="https://blog.skay.dev/when-to-use-settimeout-vs-setinterval">When to use setTimeout vs setInterval</a></li>
<li><a target="_blank" href="https://blog.skay.dev/javascript-event-loop-explained">What is Event Loop in JavaScript?</a></li>
<li><a target="_blank" href="https://blog.skay.dev/docker-fundamentals">Docker Fundamentals</a></li>
<li><a target="_blank" href="https://blog.skay.dev/iife-immediately-invoked-function-expressions">IIFE - Immediately Invoked Function Expressions</a></li>
<li><a target="_blank" href="https://blog.skay.dev/history-of-ecma-es5-es6-and-beyond">History of ECMA/ES6/ES2015</a></li>
<li><a target="_blank" href="https://blog.skay.dev/es6-arrow-functions">ES6 - Arrow Functions</a></li>
<li><a target="_blank" href="https://blog.skay.dev/es6-understanding-destructuring">ES6 - Destructuring</a></li>
</ul>
]]></content:encoded></item><item><title><![CDATA[What is Currying in JavaScript?]]></title><description><![CDATA[Introduction
In this article, we will first look at what first-class citizens and higher-order functions are to lay the foundation to explain 'Currying' in JavaScript. The code samples provided along with the explanation should make it easy to follow...]]></description><link>https://blog.skay.dev/what-is-currying-in-javascript</link><guid isPermaLink="true">https://blog.skay.dev/what-is-currying-in-javascript</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[General Programming]]></category><category><![CDATA[100DaysOfCode]]></category><category><![CDATA[Web Development]]></category><dc:creator><![CDATA[Skay]]></dc:creator><pubDate>Fri, 09 Oct 2020 14:23:34 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1602253037727/PGwUKqoHU.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="introduction">Introduction</h2>
<p>In this article, we will first look at what first-class citizens and higher-order functions are to lay the foundation to explain 'Currying' in JavaScript. The code samples provided along with the explanation should make it easy to follow and understand the concepts.</p>
<h2 id="first-class-citizens">First-Class Citizens</h2>
<p>In JavaScript, the functions are treated as 'First Class' citizens. What this means is that any function can be returned to another function, since a function is fundamentally an object.</p>
<p>Let us take a quick example to explain this better. The below code is an example of a simple function.</p>
<pre><code class="lang-js"><span class="hljs-comment">//A Simple Arrow Function returning a value '50'</span>
<span class="hljs-keyword">const</span> sum = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">return</span> <span class="hljs-number">50</span>;
};

<span class="hljs-comment">//Invoke the function and display the value on the console.</span>
<span class="hljs-built_in">console</span>.log(sum()); <span class="hljs-comment">//Output -&gt; 50</span>
</code></pre>
<p>In the above example, the number 50 is returned when the function sum() is invoked.</p>
<p>As per the definition of a First-Class citizen, we can return the function sum() instead of the value 50 as shown in the code example below.</p>
<pre><code class="lang-js"><span class="hljs-comment">//Return the Function sum() instead of returning the value by adding the additional ()</span>
<span class="hljs-keyword">const</span> sum = <span class="hljs-function">() =&gt;</span> <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">return</span> <span class="hljs-number">50</span>;
};

<span class="hljs-comment">//Invoke the function and display the value on the console.</span>
<span class="hljs-built_in">console</span>.log(sum());

<span class="hljs-comment">/*
Output
-------
() =&gt; {
  return 50;
}
*/</span>
</code></pre>
<h2 id="higher-order-functions">Higher-Order Functions</h2>
<p>Higher-order functions are functions that take other functions as arguments or functions that return a function as their result.</p>
<p>The below code example will make the above explanation more clear.</p>
<pre><code class="lang-js"><span class="hljs-comment">//Callback Function - Returns the sum of a &amp; b</span>
<span class="hljs-keyword">const</span> sum = <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 + b;
}

<span class="hljs-comment">//Higher order function - takes 'func' as an argument &amp; returns a 'func' for execution</span>
<span class="hljs-keyword">const</span> higherOrderFunction = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">func, a, b</span>) </span>{
    <span class="hljs-keyword">return</span> func(a, b);
}

<span class="hljs-comment">//Invoke the higherOrderFunction and pass 'sum' function as an argument with the digits 2 &amp; 3</span>
<span class="hljs-built_in">console</span>.log(higherOrderFunction(sum, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>)); <span class="hljs-comment">//Output -&gt; 5</span>
</code></pre>
<p>Things to note:</p>
<ul>
<li>The function 'higherOrderFunction' accepts a function 'func' as a parameter.</li>
<li>The function 'func' that is passed in as a parameter is referred to as a callback.</li>
</ul>
<p>Array.forEach, Array.map, Array.filter are some examples of high-order functions.</p>
<h2 id="currying">Currying</h2>
<p>Currying a function is the process of taking a single function of multiple arguments and decomposing it into a sequence of functions that each take a single argument.</p>
<p>Let us take the following simple example:</p>
<pre><code class="lang-js"><span class="hljs-comment">//An Arrow function taking in arguments x &amp; y and returning the sum</span>
<span class="hljs-keyword">const</span> sum = <span class="hljs-function">(<span class="hljs-params">x, y</span>) =&gt;</span> {
  <span class="hljs-keyword">return</span> x + y;
};

<span class="hljs-comment">//Output -&gt; 5</span>
<span class="hljs-built_in">console</span>.log(sum(<span class="hljs-number">3</span>, <span class="hljs-number">2</span>));
</code></pre>
<pre><code class="lang-js"><span class="hljs-comment">//By applying Currying the same can be broken into a function returning another function</span>
<span class="hljs-keyword">const</span> sum = <span class="hljs-function">(<span class="hljs-params">x</span>) =&gt;</span> {
  <span class="hljs-keyword">return</span> <span class="hljs-function">(<span class="hljs-params">y</span>) =&gt;</span> {
    <span class="hljs-keyword">return</span> x + y;
  };
}; 

<span class="hljs-comment">//Output -&gt; 5</span>
<span class="hljs-built_in">console</span>.log(sum(<span class="hljs-number">3</span>)(<span class="hljs-number">2</span>));
</code></pre>
<p>Using ES6 Arrow Functions, the above code can further be written in a simple manner as shown below.</p>
<pre><code class="lang-js"><span class="hljs-comment">//Simplified way to write the function using ES6 - Arrow Functions</span>
<span class="hljs-keyword">const</span> sum = <span class="hljs-function">(<span class="hljs-params">x</span>) =&gt;</span> <span class="hljs-function">(<span class="hljs-params">y</span>) =&gt;</span> x + y;

<span class="hljs-comment">//Output -&gt; 5</span>
<span class="hljs-built_in">console</span>.log(sum(<span class="hljs-number">3</span>)(<span class="hljs-number">2</span>));
</code></pre>
<p>That's all there is to currying. Let us look at a practical use-case of where it can be applied.</p>
<h2 id="a-practical-use-case">A Practical Use-Case</h2>
<p>Let us assume we have to read entries from a database of an e-commerce application that has the entities, user, product, and ratings. </p>
<p>To query a single product from the database, we can write a function 'getProductById' as shown below.</p>
<pre><code class="lang-js"><span class="hljs-comment">//Simplified way to write the function using ES6 - Arrow Functions</span>
<span class="hljs-keyword">const</span> getProductById = <span class="hljs-function">(<span class="hljs-params">connection, id</span>) =&gt;</span> {
    connection.select(<span class="hljs-string">'products'</span>).where({ id })    
}

<span class="hljs-comment">//Invoke the function getProductById by passing the connection object &amp; the product Id</span>
getProductById(connection, <span class="hljs-number">1</span>);
</code></pre>
<p>By applying the 'currying' concept, we can simplify the above code as shown below.</p>
<pre><code class="lang-js"><span class="hljs-comment">//By applying Currying -&gt; The function productById will return a function that'll query the products table by 'id'.</span>
<span class="hljs-keyword">const</span> getProductById = <span class="hljs-function">(<span class="hljs-params">connection</span>) =&gt;</span> <span class="hljs-function">(<span class="hljs-params">id</span>) =&gt;</span> {
    connection.select(<span class="hljs-string">'products'</span>).where({ id })
}

<span class="hljs-comment">//Invoke the function getProductById by passing the connection object &amp; the product Id</span>
<span class="hljs-keyword">const</span> getProductByIdQuery = getProductById(connection);

<span class="hljs-comment">/**
 * The Output of the above function 'getProductById' will be
 * 
 * (id) =&gt; {
 *    connection.select('products').where({ id })
 * }
 * 
 * and it will be assigned to getProductByIdQuery function
 */</span>

<span class="hljs-comment">//getProductByIdQuery can be simply invoked to fetch the product by it's Id</span>
<span class="hljs-keyword">const</span> product = getProductByIdQuery(<span class="hljs-number">1</span>); <span class="hljs-comment">//Ouput -&gt; Return product matching the 'id' 1</span>
</code></pre>
<p>The advantages of the above approach:</p>
<ul>
<li>The above approach obviously simplifies the code by avoiding the calling method to pass the 'connection' object repeatedly.</li>
<li>Further, the biggest advantage is that we can encapsulate the 'connection' object by modifying the access level to the getProductById() function as private. In simple words, nobody should know about the 'connection' object who is querying for products.</li>
</ul>
<p>We can further apply the 'currying' concept to the above example and take it to the next level and make it even more generic, so that, you can query for products, users, and reviews table.</p>
<pre><code class="lang-js"><span class="hljs-comment">//By applying Currying -&gt; The function productById will return a function that'll query the products table by 'id'.</span>
<span class="hljs-keyword">const</span> getConnection = <span class="hljs-function">(<span class="hljs-params">connection</span>) =&gt;</span> <span class="hljs-function">(<span class="hljs-params">table</span>) =&gt;</span> <span class="hljs-function">(<span class="hljs-params">id</span>) =&gt;</span> {
    connection.select(table).where({ id })
}

<span class="hljs-comment">//While we initialize the application - Get the Database connection</span>
<span class="hljs-keyword">const</span> getTableQuery = getConnection(connection);

<span class="hljs-comment">/**
 * The Output of the above function 'getConnection' will be
 * (table) =&gt; {
 *    (id) =&gt; {
 *        connection.select('products').where({ id })
 *     }
 * }
 * and it will be assigned to getTableQuery function
 */</span>

<span class="hljs-comment">//Pass the table name 'products' to get the 'getProductById' query</span>
<span class="hljs-keyword">const</span> getProductByIdQuery = getTableQuery(<span class="hljs-string">'products'</span>);

<span class="hljs-comment">/**
 * The Output of the above function 'getTableQuery' will be
 * 
 * (id) =&gt; {
 *    connection.select('products').where({ id })
 * }
 * 
 * and it will be assigned to getProductByIdQuery function
 */</span>

<span class="hljs-comment">//getProductByIdQuery can be simply invoked to fetch the product by it's Id</span>
<span class="hljs-keyword">const</span> product = getProductByIdQuery(<span class="hljs-number">1</span>); <span class="hljs-comment">//Ouput -&gt; Return product matching the 'id' 1</span>
</code></pre>
<p>Now that we have found a way to generalize querying any table, querying users and reviews are as simple as the code shown below.</p>
<pre><code class="lang-js"><span class="hljs-comment">/**
* Pass the table name to get the 'getUserById' and 'getReviewById' query
*/</span>
<span class="hljs-keyword">const</span> getUserByIdQuery = getTableQuery(<span class="hljs-string">'users'</span>);
<span class="hljs-keyword">const</span> getReviewByIdQuery = getTableQuery(<span class="hljs-string">'reviews'</span>);

<span class="hljs-comment">//Fetch the user with the 'id' 5 using getUserByIdQuery</span>
<span class="hljs-keyword">const</span> user = getUserByIdQuery(<span class="hljs-number">5</span>);

<span class="hljs-comment">//Fetch the review with the 'id' 10 using getReviewByIdQuery</span>
<span class="hljs-keyword">const</span> review = getReviewByIdQuery(<span class="hljs-number">10</span>);
</code></pre>
<p>As you can see, using the above code simplifies things, promotes reuse, and overall encourages the use of encapsulation.</p>
<h2 id="conclusion">Conclusion</h2>
<p>I hope you enjoyed the article. Do connect with me on twitter <a target="_blank" href="https://twitter.com/skay_tech">@skaytech.</a></p>
<h3 id="you-will-also-love-the-following">You will also love the following:</h3>
<ul>
<li><a target="_blank" href="https://blog.skay.dev/es6-arrow-functions">ES6 - Arrow Functions</a></li>
<li><a target="_blank" href="https://blog.skay.dev/a-basic-introduction-to-webpack">A Basic Introduction to Webpack</a></li>
<li><a target="_blank" href="https://blog.skay.dev/es6-var-vs-let-and-const">ES6 - var, let &amp; const</a></li>
<li><a target="_blank" href="https://blog.skay.dev/understanding-closures">Understanding Closures</a></li>
<li><a target="_blank" href="https://blog.skay.dev/when-to-use-settimeout-vs-setinterval">setTimeout vs setInterval</a></li>
<li><a target="_blank" href="https://blog.skay.dev/what-is-this-in-javascript">What is 'this' in JavaScript?</a></li>
<li><a target="_blank" href="https://blog.skay.dev/iife-immediately-invoked-function-expressions">IIFE - Immediately Invoked Function Expressions</a></li>
<li><a target="_blank" href="https://blog.skay.dev/docker-fundamentals">Docker Fundamentals</a></li>
<li><a target="_blank" href="https://blog.skay.dev/history-of-ecma-es5-es6-and-beyond">History of ECMAScript</a></li>
<li><a target="_blank" href="https://blog.skay.dev/js-design-patterns-module-and-revealing-module-pattern">JS Design Patterns-Module &amp; Revealing Module Pattern</a></li>
</ul>
]]></content:encoded></item><item><title><![CDATA[ES6 - Spread Operator]]></title><description><![CDATA[Introduction
In this article, let us look at a very powerful yet simple feature introduced with ES6 or ES2015 version of JavaScript, the Spread Operator.
Spread Operator
The spread operator expands an iterable object into its individual elements. An ...]]></description><link>https://blog.skay.dev/es6-spread-operator</link><guid isPermaLink="true">https://blog.skay.dev/es6-spread-operator</guid><category><![CDATA[100DaysOfCode]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[ES6]]></category><category><![CDATA[Web Development]]></category><dc:creator><![CDATA[Skay]]></dc:creator><pubDate>Mon, 05 Oct 2020 05:46:29 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1601833243697/O2QS-RrEZ.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="introduction">Introduction</h2>
<p>In this article, let us look at a very powerful yet simple feature introduced with ES6 or ES2015 version of JavaScript, the Spread Operator.</p>
<h2 id="spread-operator">Spread Operator</h2>
<p>The spread operator expands an iterable object into its individual elements. An iterable object is anything that you can loop over such as Array, Map, Set, DOM NodeList, etc.</p>
<p>A quick and easy example of the spread operator is shown below:</p>
<pre><code class="lang-js"><span class="hljs-comment">//An Array of fruits</span>
<span class="hljs-keyword">const</span> fruits = [<span class="hljs-string">'Apple'</span>, <span class="hljs-string">'Banana'</span>, <span class="hljs-string">'Watermelon'</span>];

<span class="hljs-comment">//Output the value of the array using the spread operator</span>
<span class="hljs-built_in">console</span>.log(...fruits);

<span class="hljs-comment">//Output -&gt; Apple Banana Watermelon</span>
</code></pre>
<p>The spread syntax is denoted by three periods before the object. In the above example, the spread operator is used with the 'fruits' array and the values of the array are printed in a single line using the console.log statement.</p>
<h2 id="use-cases-of-spread-operator">Use-Cases of Spread Operator</h2>
<h3 id="copy-arrays">Copy Arrays</h3>
<p>I think this is one of the most practical examples that you'll come across while programming using ES6 syntax. </p>
<p>The important thing to note from the below code example is that a shallow copy of the elements of the array 'animals' array is made while assigning to the array 'animalsCopy. This means they do not hold the same reference, which you can verify using the 'triple equals check' operator.</p>
<pre><code class="lang-js"><span class="hljs-comment">//animals array initialized</span>
<span class="hljs-keyword">const</span> animals = [<span class="hljs-string">'dog'</span>, <span class="hljs-string">'sheep'</span>, <span class="hljs-string">'goat'</span>];

<span class="hljs-comment">//animalsCopy array is created with a Shallow copy of animals array values</span>
<span class="hljs-keyword">const</span> animalsCopy = [...animals];

<span class="hljs-comment">//Display value on the console</span>
<span class="hljs-built_in">console</span>.log(animalsCopy);

<span class="hljs-comment">//Output -&gt; Array(3) ["dog", "sheep", "goat"]</span>

<span class="hljs-built_in">console</span>.log(animals === animalsCopy); <span class="hljs-comment">//Output -&gt; false</span>

<span class="hljs-comment">//Important thing to note here is that animals !== animalsCopy (Only a Shallow copy is made)</span>
</code></pre>
<h3 id="copy-objects">Copy Objects</h3>
<p>This is exactly the same as copying arrays, except that we are using objects.</p>
<pre><code class="lang-js"><span class="hljs-comment">//Person object</span>
<span class="hljs-keyword">const</span> person = 
{ <span class="hljs-attr">name</span> : <span class="hljs-string">'Skay'</span>, 
  <span class="hljs-attr">age</span> : <span class="hljs-number">38</span> 
}

<span class="hljs-comment">//Shallow copy Person object using spread operator to create personCopy object</span>
<span class="hljs-keyword">const</span> personCopy = {...person};

<span class="hljs-built_in">console</span>.log(personCopy); <span class="hljs-comment">//Output -&gt; { name: "Skay", age: 38 }</span>

<span class="hljs-built_in">console</span>.log(person === personCopy); <span class="hljs-comment">//Output -&gt; false (Shallow copy)</span>
</code></pre>
<h3 id="merging-arrays">Merging Arrays</h3>
<p>The Spread operator provides a simple and effective way to merge arrays without the need to loop through them.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> maleActors = [<span class="hljs-string">'Brad Pitt'</span>, <span class="hljs-string">'Chris Evans'</span>, <span class="hljs-string">'Matt Damon'</span>];

<span class="hljs-keyword">const</span> femaleActors = [<span class="hljs-string">'Jennifer Aniston'</span>, <span class="hljs-string">'Jennifer Lawrence'</span>, <span class="hljs-string">'Emma Stone'</span>]; 

<span class="hljs-keyword">const</span> movieActors = [...maleActors, ...femaleActors];

<span class="hljs-built_in">console</span>.log(movieActors); 
<span class="hljs-comment">//Output -&gt; Array(6) [ "Brad Pitt", "Chris Evans", "Matt Damon", "Jennifer Aniston", "Jennifer Lawrence", "Emma Stone" ]</span>
</code></pre>
<h3 id="merging-objects">Merging Objects</h3>
<p>Merging Objects is similar to merging arrays except that there's a 'key' or an 'attribute' in the picture.</p>
<p>There are 2 possibilities when the two objects are merged:</p>
<ul>
<li>key is unique - The key/value will be copied over to the new object.</li>
<li>key is common in both the objects - The value of the last object will replace the value of the previous object during the merge.</li>
</ul>
<p>The code example below will help in understanding the scenario in a better way.</p>
<pre><code class="lang-js"><span class="hljs-comment">//Person1 Object containing the attributes name &amp; age</span>
<span class="hljs-keyword">const</span> person1 = 
{ 
  <span class="hljs-attr">name</span> : <span class="hljs-string">"Skay"</span>, 
  <span class="hljs-attr">age</span> : <span class="hljs-number">32</span> 
};

<span class="hljs-comment">//Person2 Object containing the attributes name, age &amp; occupation</span>
<span class="hljs-keyword">const</span> person2 = 
{ 
    <span class="hljs-attr">name</span> : <span class="hljs-string">"Skay"</span>, 
    <span class="hljs-attr">age</span>: <span class="hljs-number">38</span>,
    <span class="hljs-attr">occupation</span>: <span class="hljs-string">"Web Developer"</span> 
};

<span class="hljs-comment">//Both objects are merged using the spread operator</span>
<span class="hljs-comment">//If key is not common between person1 &amp; person2, then it's copied to the newPerson object</span>
<span class="hljs-comment">//However, for the age attribute, the value of 'person2' will be replaced with the value of 'person1'</span>
<span class="hljs-keyword">const</span> newPerson = {...person1, ...person2};
<span class="hljs-built_in">console</span>.log(newPerson) ; <span class="hljs-comment">// Output -&gt; {name: "Skay", age: 38, occupation: "Web Developer"}</span>
</code></pre>
<h3 id="spread-operator-with-strings">Spread Operator - With Strings</h3>
<p>The spread operator also works with strings. One practical example is extracting characters from a string.</p>
<pre><code class="lang-js"><span class="hljs-comment">//'name' variable</span>
<span class="hljs-keyword">const</span> name = <span class="hljs-string">'Skay'</span>;

<span class="hljs-comment">//Spread Operator extracts the characters from the String and assigns to an array</span>
<span class="hljs-keyword">const</span> chars = [...name];

<span class="hljs-built_in">console</span>.log(chars); <span class="hljs-comment">//Output -&gt; Array (4) ["S", "k", "a", "y"]</span>
</code></pre>
<h3 id="spread-operator-argument-to-a-function">Spread Operator - Argument to a Function</h3>
<p>This is another great practical example of passing an array into an argument of a function. Though, code readability becomes a topic of discussion when seeing spread operators as parameters to functions.</p>
<p>In the code example below, the spread operator spreads the variables into the argument in the same order they appeared in the array. So 1 is passed into a, 2 is passed into b, and 3 is passed into c. </p>
<pre><code class="lang-js"><span class="hljs-comment">//Array of numbers</span>
<span class="hljs-keyword">const</span> arr = [<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>];

<span class="hljs-comment">//Arrow Function to add numbers</span>
<span class="hljs-keyword">const</span> add = <span class="hljs-function">(<span class="hljs-params">a,b,c</span>) =&gt;</span> a+b+c;

<span class="hljs-comment">//Passing the array as a spread operator to the function 'add'</span>
<span class="hljs-comment">//The values of the array are spread across the variables in the same order </span>
<span class="hljs-comment">//they appeared in the array</span>
<span class="hljs-built_in">console</span>.log(add(...arr)); <span class="hljs-comment">//Output -&gt; 6</span>
</code></pre>
<h3 id="spread-operator-with-destructuring">Spread Operator with Destructuring</h3>
<p>Another common use-case which you will come across in several places is combining spread operator while destructuring.</p>
<p>Destructuring is another powerful feature introduced with ES6. You can read more about it <a target="_blank" href="https://blog.skay.dev/es6-understanding-destructuring">over here</a>.</p>
<p>In the code example below, the attributes 'occupation', 'skills' are by default assigned to the 'others' variable when the spread operator is used.</p>
<pre><code class="lang-js"><span class="hljs-comment">//Person Object</span>
<span class="hljs-keyword">const</span> person = 
{
    <span class="hljs-attr">name</span> : <span class="hljs-string">'Skay'</span>,
  <span class="hljs-attr">age</span>: <span class="hljs-number">38</span>,
  <span class="hljs-attr">occupation</span>: <span class="hljs-string">'Web Developer'</span>,
    <span class="hljs-attr">skills</span>: <span class="hljs-string">'HTML, CSS, JavaScript'</span>
};

<span class="hljs-comment">//Destructuring the Person object and assigning the values to name &amp; age</span>
<span class="hljs-comment">//The attributes occupation &amp; skills are automatically assigned to 'others'</span>
<span class="hljs-comment">//By using the spread operator</span>
<span class="hljs-keyword">const</span> { name, age, ...others } = person;

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Name is <span class="hljs-subst">${name}</span>`</span>); <span class="hljs-comment">//Output -&gt; Name is Skay</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Age is <span class="hljs-subst">${age}</span>`</span>); <span class="hljs-comment">//Output -&gt; Age is 38</span>
<span class="hljs-built_in">console</span>.log(others); 
<span class="hljs-comment">// Output -&gt; {occupation: "Web Developer", skills: "HTML, CSS, JavaScript"}</span>
</code></pre>
<h3 id="convert-nodelist-to-array">Convert NodeList to Array</h3>
<p>This is another common example where you can use a spread operator. Typically, if we need to do any DOM manipulation of lists in a page, we will choose the elements from the DOM using a 'querySelectorAll' command.</p>
<p>When the 'querySelectorAll' command is used, it returns a NodeList. NodeList is similar to an array, but do not have the high-order methods of an array such as forEach, map, filter, etc.</p>
<p>However, with the spread operator, we can convert a NodeList into an Array in a single line.</p>
<pre><code class="lang-js"><span class="hljs-comment">/* Note: This is a sample code &amp; will run with HTML code*/</span>
<span class="hljs-comment">//Assuming there's a number of list items with the className of 'items'</span>
<span class="hljs-comment">//It will return a NodeList </span>
<span class="hljs-keyword">let</span> nodeList = <span class="hljs-built_in">document</span>.querySelectorAll(<span class="hljs-string">'.items'</span>);

<span class="hljs-comment">//Using the spread operator, the nodeList is converted to an array</span>
<span class="hljs-comment">//This gives us the flexibility to use high-order array methods such as map, filter, etc.</span>
<span class="hljs-keyword">var</span> nodeArray = [...nodeList]
</code></pre>
<h2 id="conclusion">Conclusion</h2>
<p>As we can see, the 'spread' syntax is a great convenience feature of JavaScript. We have seen the following features of the spread operator in this article:</p>
<ul>
<li>Combines 2 arrays into one.</li>
<li>Pass arrays into a function as arguments with a single line of code. Very useful, when there are a larger number of arguments exist for a function.</li>
<li>Can be combined with destructuring to extract specific values and assign the rest of the values to a single variable.</li>
<li>Shallow copying of arrays &amp; objects is possible.</li>
<li>Practical use-cases such as extracting characters from a string or converting a NodeList into an array can be achieved in a single line.</li>
</ul>
<p>I hope you enjoyed this article. Don't forget to subscribe to my newsletter and connect with me on Twitter <a target="_blank" href="https://twitter.com/skay_tech">@skaytech.</a></p>
<h3 id="you-might-also-like-the-following-articles">You might also like the following articles:</h3>
<ul>
<li><a target="_blank" href="https://blog.skay.dev/a-basic-introduction-to-webpack">A Basic Introduction to Webpack</a></li>
<li><a target="_blank" href="https://blog.skay.dev/how-to-make-an-argument-required-in-javascript">How to make an argument 'required' in JavaScript?</a></li>
<li><a target="_blank" href="https://blog.skay.dev/es6-var-vs-let-and-const">ES6 - var, let &amp; const</a></li>
<li><a target="_blank" href="https://blog.skay.dev/es6-understanding-destructuring">ES6 - Destructuring</a></li>
<li><a target="_blank" href="https://blog.skay.dev/es6-arrow-functions">ES6 - Arrow Functions</a></li>
<li><a target="_blank" href="https://blog.skay.dev/what-are-git-hooks">What are Git Hooks?</a></li>
<li><a target="_blank" href="https://blog.skay.dev/custom-spa-router-vanillajs">Build a Custom SPA Router with VanillaJS</a></li>
<li><a target="_blank" href="https://blog.skay.dev/javascript-event-loop-explained">What is Eventloop in JavaScript?</a></li>
<li><a target="_blank" href="https://blog.skay.dev/understanding-closures">Understanding Closures</a></li>
<li><a target="_blank" href="https://blog.skay.dev/what-is-this-in-javascript">What is 'this' in JavaScript?</a></li>
</ul>
]]></content:encoded></item><item><title><![CDATA[How to make an argument "required" in JavaScript?]]></title><description><![CDATA[Introduction
My friend Simon Hoiberg, had recently made a super cool video tweet and provided an excellent tip on how to make an argument in JavaScript as a "required" field.
https://twitter.com/hashnode/status/1286185777513345024?s=20
In this articl...]]></description><link>https://blog.skay.dev/how-to-make-an-argument-required-in-javascript</link><guid isPermaLink="true">https://blog.skay.dev/how-to-make-an-argument-required-in-javascript</guid><category><![CDATA[100DaysOfCode]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[webdev]]></category><dc:creator><![CDATA[Skay]]></dc:creator><pubDate>Fri, 02 Oct 2020 12:43:43 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1601642605960/rJy08QdU1Y.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="introduction">Introduction</h2>
<p>My friend <a target="_blank" href="https://www.silind.com/">Simon Hoiberg</a>, had recently made a super cool video tweet and provided an excellent tip on how to make an argument in JavaScript as a "required" field.</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://twitter.com/hashnode/status/1286185777513345024?s=20">https://twitter.com/hashnode/status/1286185777513345024?s=20</a></div>
<p>In this article, I have provided an explanation with some code examples on Codepen to explore the concept further.</p>
<h2 id="arguments-passed-to-a-javascript-function-is-optional-by-default">Arguments passed to a JavaScript function is Optional by default</h2>
<p>The arguments passed to a JavaScript function is optional by default. Let us look at the code example below to understand the default behavior.</p>
<pre><code class="lang-js"><span class="hljs-comment">//someFunction is an ES6 Arrow function that accepts 'name' as a parameter and returns the string</span>
<span class="hljs-comment">//By default, the parameter name is optional</span>
<span class="hljs-keyword">const</span> someFunction = <span class="hljs-function">(<span class="hljs-params">name</span>) =&gt;</span> {
  <span class="hljs-keyword">return</span> <span class="hljs-string">`My name is <span class="hljs-subst">${name}</span>`</span>;
};

<span class="hljs-comment">//Invoking the 'someFunction()'</span>
<span class="hljs-keyword">const</span> output = someFunction();

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

<span class="hljs-comment">//Output -&gt; My name is undefined</span>
</code></pre>
<p>Things to note:</p>
<ul>
<li>Since no argument is passed to the function 'someFunction()', a default value of 'undefined' is assigned to the 'name' argument by the JavaScript engine.</li>
<li>Hence, the value of the 'output' variable outputs to the console as 'My name is undefined'</li>
</ul>
<p>You can play with the code <a target="_blank" href="https://codepen.io/skaytech/pen/jOWdjBy">over here.</a></p>
<h2 id="how-to-make-the-argument-passed-to-a-javascript-function-mandatory">How to make the Argument passed to a JavaScript function mandatory?</h2>
<p>A very simple technique is to assign a default value to the argument. This default value will be a function that will simply throw an error with the message 'Argument is required'.</p>
<p>Let us look at the code example below, to see that in action.</p>
<pre><code class="lang-js"><span class="hljs-comment">//The function isRequired() throws an Error with the msg 'Argument is required'</span>
<span class="hljs-keyword">const</span> isRequired = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">throw</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">'Argument is required'</span>);
};

<span class="hljs-comment">//someFunction is an ES6 Arrow function that accepts 'name' as a parameter and returns the string</span>
<span class="hljs-comment">//The parameter name is 'Mandatory' by assigning a default value of the function 'isRequired()'</span>
<span class="hljs-keyword">const</span> someFunction = <span class="hljs-function">(<span class="hljs-params">name = isRequired()</span>) =&gt;</span> {
  <span class="hljs-keyword">return</span> <span class="hljs-string">`My name is <span class="hljs-subst">${name}</span>`</span>;
};

<span class="hljs-keyword">try</span> {
  <span class="hljs-comment">//Invoking the 'someFunction()'</span>
  <span class="hljs-keyword">const</span> output = someFunction();

  <span class="hljs-comment">//Append the value of output to the HTML</span>
  <span class="hljs-built_in">document</span>
    .querySelector(<span class="hljs-string">'#output'</span>)
    .appendChild(<span class="hljs-built_in">document</span>.createTextNode(output));
} <span class="hljs-keyword">catch</span> (err) {
  <span class="hljs-built_in">console</span>.log(err.message);
}

<span class="hljs-comment">// Output -&gt; Argument is required</span>
</code></pre>
<p>Things to note:</p>
<ul>
<li>When the someFunction() is invoked without passing the arguments, the default value assigned to the 'name' argument is invoked.</li>
<li>The default value assigned to the 'name' argument is the function 'isRequired()'.</li>
<li>When the function 'isRequired()' is invoked, the error 'Argument is required' is thrown.</li>
<li>The error is caught within the catch block and the output 'Argument is required' displays on the console.</li>
</ul>
<p>You can play with the code <a target="_blank" href="https://codepen.io/skaytech/pen/PoZVMJK">over here.</a></p>
<h2 id="conclusion">Conclusion</h2>
<p>Thanks to my friend <a target="_blank" href="https://www.silind.com/">Simon</a> for this simple, yet, powerful tip on how to make JavaScript argument mandatory when passing it to a function.</p>
<p>Hope you enjoyed the simple article. Don't forget to subscribe to my newsletter and follow me on Twitter <a target="_blank" href="https://twitter.com/skay_tech">@skaytech</a></p>
<p>You might also be interested in the following:</p>
<ul>
<li><a target="_blank" href="https://blog.skay.dev/docker-fundamentals">Docker Fundamentals</a></li>
<li><a target="_blank" href="https://blog.skay.dev/understanding-closures">Understanding Closures</a></li>
<li><a target="_blank" href="https://blog.skay.dev/5-must-read-tips-to-write-a-killer-blog-article">5 Must-Read Tips to write a Killer Blog Article</a></li>
<li><a target="_blank" href="https://blog.skay.dev/custom-spa-router-vanillajs">Build a Custom SPA Router using VanillaJS</a></li>
<li><a target="_blank" href="https://blog.skay.dev/guide-organised-and-productive">A Practical Guide to stay more productive and organized</a></li>
<li><a target="_blank" href="https://blog.skay.dev/iife-immediately-invoked-function-expressions">IIFE - Immediately Invoked Function Expressions</a></li>
<li><a target="_blank" href="https://blog.skay.dev/js-design-patterns-module-and-revealing-module-pattern">JS Design Patterns: Module &amp; Revealing Module Pattern</a></li>
<li><a target="_blank" href="https://blog.skay.dev/es6-var-vs-let-and-const">ES6 - var, let &amp; const</a></li>
<li><a target="_blank" href="https://blog.skay.dev/when-to-use-settimeout-vs-setinterval">ES6 - setTimeout vs setInterval</a></li>
</ul>
]]></content:encoded></item><item><title><![CDATA[5 Must-Read Tips to write a Killer Blog Article!]]></title><description><![CDATA[KISS - Keep it Simple, Stupid
KISS is an acronym coined by the U.S Navy in 1960 (source wikipedia) and it is also a very famous design principle in the technology world. I cannot stress how much it also applies while writing your blog.

It is recomme...]]></description><link>https://blog.skay.dev/5-must-read-tips-to-write-a-killer-blog-article</link><guid isPermaLink="true">https://blog.skay.dev/5-must-read-tips-to-write-a-killer-blog-article</guid><category><![CDATA[100DaysOfCode]]></category><category><![CDATA[General Advice]]></category><category><![CDATA[Blogging]]></category><category><![CDATA[Developer Blogging]]></category><dc:creator><![CDATA[Skay]]></dc:creator><pubDate>Wed, 30 Sep 2020 09:30:05 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1601458029952/aHcgGPJgB.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="kiss-keep-it-simple-stupid">KISS - Keep it Simple, Stupid</h2>
<p>KISS is an acronym coined by the U.S Navy in 1960 (<a target="_blank" href="https://en.wikipedia.org/wiki/KISS_principle">source wikipedia</a>) and it is also a very famous design principle in the technology world. I cannot stress how much it also applies while writing your blog.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1601457050165/c-0b_Sl4e.jpeg" alt="tim-mossholder-7aBrZmwEQtg-unsplash.jpg" /></p>
<p>It is recommended to have a simple introduction, telling the audience what they can expect from your blog article and what how the reader will benefit if they read the article. This sets up a good premise to capture the engagement of the reader.</p>
<p>Likewise, a good conclusion summarizing the points that you've covered in your article, along with any reference links for further reading will be a good way to conclude the article.</p>
<p>A bonus tip is to have your subscription and the twitter handle at the end of the post to ensure your reader has the ability to connect with you to increase your overall engagement.</p>
<h2 id="kic-keep-it-concise">KIC - Keep it Concise</h2>
<p>It is highly recommended to keep it to the point and concise. The simple reason being that your readers are generally very busy. Ask yourself if your reader could ready your entire article during a 5-10 coffee/tea break.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1601457401780/GAbZVBPsX.jpeg" alt="annie-spratt-GNQV8xrXUis-unsplash.jpg" /></p>
<p>As a rule of thumb, the ideal length for an article is the length occupied when you press the 'Page Down' key 4 times. If you feel you want to explain more, then evaluate if you can make it into a series of articles vs one blog post.</p>
<p>Regarding the content, break it down into points and turn them into sub-headings. Each sub-heading should have a logical start and end. As a bonus, it'll be good to conclude your sub-heading by introducing the next topic in your article. This improves your overall continuity and increases reader engagement.</p>
<h2 id="count-the-number-of-yous-in-the-article">Count the number of "You"s in the Article.</h2>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1601457551050/3jrmBnpJT.jpeg" alt="ben-robbins-S20PlUJRviI-unsplash.jpg" /></p>
<p>While this might sound silly, this is very important. Why? The simple reason is that I'm writing to you, the reader, and not for myself. So I'll comb through the article and change as many self-references as possible from "me" or "I" to "you"s in the article. </p>
<p>If I'm not able to change it, it's a good indication that the article will never work in terms of engagement, since the readers will not be able to relate to the article nor the topic.</p>
<h2 id="use-illustrations-images-and-code-examples">Use Illustrations, Images &amp; Code Examples</h2>
<p>To the age-old saying of 'A picture is worth a 1000 words', it's cannot be more true especially when it comes to your blog article. If you are explaining an article, completing it with illustrations ensures that the concepts are reinforced in your brain.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1601457813033/SXgcrlCHZ.jpeg" alt="vivek-kumar-riAKT8Z7ifE-unsplash.jpg" /></p>
<p>Images with the text help the readers consume content easily, as compared to just text, which can tend to get monotonous. Placing the images strategically within your article is important and care should be taken to not break the reader's flow while placing the images.</p>
<p>A good rule of thumb is to either read out your article yourself or give it to a friend and ask them where it kind of gets monotonous or the attention slip away and place the image around those portions.  </p>
<p>The above can be extended while embedding code snippets while writing your technical article. It is easier with code snippets, since, your article would naturally go about explaining the code.</p>
<h2 id="show-and-tell">Show and Tell</h2>
<p>Finally, you'll need to tell your reader how they've benefited from your article in a way they can identify. A good way to do this is by providing them with a bunch of actionable items, for example, you can provide them with the required resources to take the knowledge they have gained from your article and move forward.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1601457934850/hkT0vNVvS.jpeg" alt="thought-catalog-xHaZ5BW9AY0-unsplash.jpg" /></p>
<p>For a technical article, providing a demo to your work and possibly the Github repository greatly increases engagement and is very satisfying to the reader.</p>
<h2 id="conclusion">Conclusion</h2>
<p>In simple words, write from your heart. Write about the things you are most passionate about and the rest will follow. Start writing consistently and you'll improve leaps and bounds.</p>
<p>I hope you've enjoyed this article and I would like to recommend two more excellent articles on blogging tips:</p>
<p><a target="_blank" href="https://iamshadmirza.com/how-to-write-blog-without-motivation">How to write a blog without motivation?</a> by @iamshadmirza</p>
<p><a target="_blank" href="https://blog.greenroots.info/how-to-write-consistently-a-guide-for-technical-writers">A Guide for writing consistently for technical writers!</a> by @atapas</p>
<p>If you enjoy my articles, don't forget to Subscribe. You can also find me on Twitter <a target="_blank" href="https://twitter.com/skay_tech">@skaytech</a></p>
<h3 id="you-may-also-enjoy-the-following-articles">You may also enjoy the following articles:</h3>
<ul>
<li><a target="_blank" href="https://blog.skay.dev/iife-immediately-invoked-function-expressions">IIFE</a></li>
<li><a target="_blank" href="https://blog.skay.dev/custom-spa-router-vanillajs">Build a custom SPA router using VanillaJS</a></li>
<li><a target="_blank" href="https://blog.skay.dev/history-of-ecma-es5-es6-and-beyond">History of ECMAScript</a></li>
<li><a target="_blank" href="https://blog.skay.dev/es6-arrow-functions">ES6 =&gt; Arrow Functions</a></li>
<li><a target="_blank" href="https://blog.skay.dev/docker-fundamentals">Docker Fundamentals</a></li>
<li><a target="_blank" href="https://blog.skay.dev/what-are-git-hooks">What are Git Hooks?</a></li>
<li><a target="_blank" href="https://blog.skay.dev/guide-organised-and-productive">A Practical Guide to help you stay organized and productive</a></li>
<li><a target="_blank" href="https://blog.skay.dev/javascript-event-loop-explained">What is Event Loop in JavaScript?</a></li>
<li><a target="_blank" href="https://blog.skay.dev/a-basic-introduction-to-webpack">A Basic Introduction to Webpack</a></li>
<li><a target="_blank" href="https://blog.skay.dev/understanding-closures">Understanding Closures</a></li>
<li><a target="_blank" href="https://blog.skay.dev/what-is-this-in-javascript">What is 'this' in JavaScript?</a></li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Build a custom SPA Router using VanillaJS]]></title><description><![CDATA[Introduction
In this article, I will explain how I had built a custom SPA router using Vanilla JavaScript. I had to build a UI project without any using framework and had to figure out how to handle routing and discovered that you can build your own ...]]></description><link>https://blog.skay.dev/custom-spa-router-vanillajs</link><guid isPermaLink="true">https://blog.skay.dev/custom-spa-router-vanillajs</guid><category><![CDATA[100DaysOfCode]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[webdevelopment]]></category><category><![CDATA[routing]]></category><dc:creator><![CDATA[Skay]]></dc:creator><pubDate>Sat, 26 Sep 2020 07:40:09 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1601105400394/RFYqh4NVZ.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="introduction">Introduction</h2>
<p>In this article, I will explain how I had built a custom SPA router using Vanilla JavaScript. I had to build a UI project without any using framework and had to figure out how to handle routing and discovered that you can build your own router using Vanilla JavaScript quiet easily.</p>
<h3 id="disclaimer">Disclaimer</h3>
<p><em>I agree with the philosophy that we should not reinvent the wheel. And with the advent of frameworks such as ReactJS, Vue, each of them has its own custom routing library and I'll recommend you using them rather than building something ground up. However, the intent of this article is to explain that it is possible to write a custom router using VanillaJS and it also gives an opportunity to find out what happens under the hood.</em></p>
<h2 id="window-history-and-location-objects">Window - History &amp; Location Objects</h2>
<p>In order to build a custom router, we need to first understand the 'history' and the 'location' objects of the 'window' object and few methods that are required to handle the page navigation.</p>
<h3 id="history-object">History Object</h3>
<p>The <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/History_API">window.history</a> object provides the details regarding the browser's session history. It contains methods &amp; properties that help you navigate back and forth through the user's history.</p>
<p>You can open your browser console and type history, and you'll see all the methods and properties of the history object listed as shown below.</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/i/r934l0pwiwvj3puwl7zf.png" alt="Alt Text" /></p>
<h3 id="location-object">Location Object</h3>
<p>The <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/Location">window.location</a> contains all the information related to the current location such as the origin, pathname, etc.</p>
<p>You can open your browser console and type location, and you'll see all the various properties and methods associated with the location object as shown below.</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/i/p9l4tl541d43e5y04cx8.png" alt="Alt Text" /></p>
<h3 id="history-pushstate">History - pushState()</h3>
<p>The method <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/History/pushState">pushState</a> is used to add a state to the browser's session history stack.</p>
<blockquote>
<p><strong><em>Syntax: history.pushState(state, title, [, url]);</em></strong></p>
</blockquote>
<ul>
<li>state - The JavaScript object associated with the new history entry. The state object can be anything that can be serialized.</li>
<li>title - The title is actually not used by Modern browsers yet. it is safe to pass an empty string or the title you wish you refer your state.</li>
<li>URL - The new history entry's URL is specified by this parameter.</li>
</ul>
<p>We will be using the pushState method to update the browser's URL during page navigation.</p>
<h3 id="window-popstate-event">Window - popstate event</h3>
<p>The <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/Window/popstate_event">popstate event</a>) is fired when the active history changes when the user navigates the session history.</p>
<p>In other words, whenever a back or a forward button is pressed on the browser, then the history changes and at that moment the 'popstate' event is fired. </p>
<p>We will be using the 'popstate' event to handle logic whenever the history changes.</p>
<h2 id="implementing-the-router">Implementing the Router</h2>
<p>Now that we've got the fundamentals in place, we will look at a step-by-step approach to implementing the router using VanillaJS.</p>
<h3 id="the-view">The View</h3>
<p>The index.html is a very simple page which contains an unordered list of links for the pages:</p>
<ul>
<li>home</li>
<li>about</li>
<li>contact</li>
</ul>
<p>In addition, there are 3 separate HTML for the home, about, and contact views.</p>
<h4 id="indexhtml">index.html</h4>
<pre><code class="lang-js">&lt;!DOCTYPE html&gt;
<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">html</span> <span class="hljs-attr">lang</span>=<span class="hljs-string">"en"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"UTF-8"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"viewport"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"width=device-width, initial-scale=1.0"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>Vanilla JS Router<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">ul</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"navbar-list"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">li</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"navbar-item"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"#"</span> <span class="hljs-attr">onclick</span>=<span class="hljs-string">"onNavClick('/about'); return false;"</span>&gt;</span>About<span class="hljs-tag">&lt;/<span class="hljs-name">a</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> <span class="hljs-attr">class</span>=<span class="hljs-string">"navbar-item"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"#"</span> <span class="hljs-attr">onclick</span>=<span class="hljs-string">"onNavClick('/'); return false;"</span>&gt;</span>Home<span class="hljs-tag">&lt;/<span class="hljs-name">a</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> <span class="hljs-attr">class</span>=<span class="hljs-string">"navbar-item"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"#"</span> <span class="hljs-attr">onclick</span>=<span class="hljs-string">"onNavClick('/contact'); return false;"</span>&gt;</span>Contact<span class="hljs-tag">&lt;/<span class="hljs-name">a</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">ul</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"root"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"./js/app.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span></span>
</code></pre>
<h4 id="homehtml">home.html</h4>
<pre><code class="lang-js">&lt;div&gt;
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>******Welcome to the Home Page*****<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span></span>
&lt;/div&gt;
</code></pre>
<h4 id="abouthtml">about.html</h4>
<pre><code class="lang-js">&lt;div&gt;
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>******Welcome to the About Page*****<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span></span>
&lt;/div&gt;
</code></pre>
<h4 id="contacthtml">contact.html</h4>
<pre><code class="lang-js">&lt;div&gt;
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>******Welcome to the Contact Page*****<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span></span>
&lt;/div&gt;
</code></pre>
<h3 id="load-the-html-pages-async">Load the HTML pages (Async)</h3>
<p>I have used the async/await with 'fetch API' for asynchronous loading of pages and have used 'promise' to assign the values to home, about and contact variables.</p>
<pre><code class="lang-js"><span class="hljs-comment">//Declare the variables for home, about &amp; contact html pages</span>
<span class="hljs-keyword">let</span> home = <span class="hljs-string">''</span>;
<span class="hljs-keyword">let</span> about = <span class="hljs-string">''</span>;
<span class="hljs-keyword">let</span> contact = <span class="hljs-string">''</span>;

<span class="hljs-comment">/**
 *
 * @param {String} page - Represents the page information that needs to be retrieved
 * @returns {String} resHtml - The Page's HTML is returned from the async invocation
 */</span>

<span class="hljs-keyword">const</span> loadPage = <span class="hljs-keyword">async</span> (page) =&gt; {
  <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> fetch(page);
  <span class="hljs-keyword">const</span> resHtml = <span class="hljs-keyword">await</span> response.text();
  <span class="hljs-keyword">return</span> resHtml;
};

<span class="hljs-comment">/**
 * The Async function loads all HTML to the variables 'home', 'about' &amp; 'contact'
 */</span>
<span class="hljs-keyword">const</span> loadAllPages = <span class="hljs-keyword">async</span> () =&gt; {
  home = <span class="hljs-keyword">await</span> loadPage(<span class="hljs-string">'home.html'</span>);
  about = <span class="hljs-keyword">await</span> loadPage(<span class="hljs-string">'about.html'</span>);
  contact = <span class="hljs-keyword">await</span> loadPage(<span class="hljs-string">'contact.html'</span>);
};
</code></pre>
<p>Let us walk through the flow for one page:</p>
<ul>
<li>When the 'loadAllPages' function is invoked, the first function loadPage('home.html') first fired.</li>
<li>Inside the 'loadPage' function, the fetch('home.html') will be fired to load the home.html asynchronously.</li>
<li>The 'await' keyword ensures that the 'response' variable is populated and the 'resHtml' is assigned 'response.text()' since the text is returned in the API call.</li>
<li>The value of 'resHtml' is returned to the 'loadAllPages' function and assigned to the 'home' variable.</li>
</ul>
<p>Likewise, API calls are made for 'about' and 'contact' pages as well and the values are populated to the variables about &amp; contact.</p>
<h3 id="the-main-function-and-root-element">The Main Function &amp; Root Element</h3>
<p>Fetch the 'rootDiv' from the 'index.html' document.</p>
<p>The main function will be invoked on the Page load. Inside, the main function, we are first ensuring that all the HTML pages are loaded into the variables 'home', 'about' and 'contact'.</p>
<p>In order to ensure that the 'home' page is loaded to the root element upon page load, the rootDiv.innerHTML is set to 'home' variable.</p>
<p>Further, the 'routes' are set up with the corresponding page mapping in order to load the appropriate page when the routes are called.</p>
<pre><code class="lang-js"><span class="hljs-comment">//Get the Element with the Id 'root'</span>
<span class="hljs-keyword">const</span> rootDiv = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'root'</span>);

<span class="hljs-comment">/**
 * The Main Function is an async function that first loads All Page HTML to the variables
 * Once the variables are loaded with the contents, then they are assigned to the 'routes' variable
 */</span>
<span class="hljs-keyword">const</span> main = <span class="hljs-keyword">async</span> () =&gt; {
  <span class="hljs-keyword">await</span> loadAllPages();
  rootDiv.innerHTML = home;
  routes = {
    <span class="hljs-string">'/'</span>: home,
    <span class="hljs-string">'/contact'</span>: contact,
    <span class="hljs-string">'/about'</span>: about,
  };
};

<span class="hljs-comment">// Invoke the Main function</span>
main();
</code></pre>
<h3 id="routing-when-a-link-is-clicked-on-the-main-page">Routing - When a link is clicked on the Main page</h3>
<p>From the above index.html, we are invoking the 'onNavClick' method and passing in the 'route' upon clicking the 'a' link as shown in the code snippet below.</p>
<pre><code class="lang-js">&lt;li <span class="hljs-class"><span class="hljs-keyword">class</span></span>=<span class="hljs-string">"navbar-item"</span>&gt;
    <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"#"</span> <span class="hljs-attr">onclick</span>=<span class="hljs-string">"onNavClick('/about'); return false;"</span>&gt;</span>About<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span></span>
&lt;/li&gt;
</code></pre>
<pre><code class="lang-js"><span class="hljs-comment">/**
 *
 * <span class="hljs-doctag">@param <span class="hljs-type">{String}</span> <span class="hljs-variable">pathname</span></span> - Pass the 'pathname' passed from onClick function of the link (index.html)
 * The function is invoked when any link is clicked in the HTML.
 * The onClick event on the HTML invokes the onNavClick &amp; passes the pathname as param
 */</span>
<span class="hljs-keyword">const</span> onNavClick = <span class="hljs-function">(<span class="hljs-params">pathname</span>) =&gt;</span> {
  <span class="hljs-built_in">window</span>.history.pushState({}, pathname, <span class="hljs-built_in">window</span>.location.origin + pathname);
  rootDiv.innerHTML = routes[pathname];
};
</code></pre>
<p>The onNavClick method accepts the 'pathname' which is the 'route' link and uses the window.history.'pushState' method to alter the state.</p>
<p>The second line 'rootDiv.innerHTML = routes[pathname]' will render the appropriate page based on what is configured within the routes in the main function (see above).</p>
<p>At this point, you have a functional router that navigates to the appropriate page upon clicking a link and the corresponding link is also updated in the URL browser.</p>
<p>The only thing that you'll notice is that when you hit a 'back' or 'forward' button on the browser, the links are correctly updated on the URL, however, the contents on the page are not refreshed.</p>
<p>Let us take care of that in the last section of the article.</p>
<h3 id="handle-page-rendering-upon-state-change">Handle Page Rendering upon State Change</h3>
<p>If you would recall from the above definition of 'onpopstate event' method, it'll be invoked whenever the active history changes in the browser.</p>
<p>We are using that hook to ensure that the rootDiv is populated with the appropriate page based on the routes configured.</p>
<p>That's it!! You should now have a fully functional custom router built using Vanilla JavaScript.</p>
<pre><code class="lang-js"><span class="hljs-comment">/**
 * The Function is invoked when the window.history changes
 */</span>
<span class="hljs-built_in">window</span>.onpopstate = <span class="hljs-function">() =&gt;</span> {  
  rootDiv.innerHTML = routes[<span class="hljs-built_in">window</span>.location.pathname];
};
</code></pre>
<p>If you would like the complete code, you can find it on Github <a target="_blank" href="https://github.com/skaytech/vanillajsrouter">over here</a>.</p>
<h2 id="conclusion">Conclusion</h2>
<p>To summarize, we've covered how to build a basic custom router using VanillaJS. The router uses the window's history and location objects primarily and the methods pushState &amp; onpopstate event.</p>
<p>Hope you enjoyed this article. Don't forget to subscribe and connect with me on Twitter <a target="_blank" href="https://twitter.com/skay_tech">@skaytech</a></p>
<p><em>Cover Photo by <a target="_blank" href="https://unsplash.com/@jannerboy62">Nick Fewings</a> on <a target="_blank" href="https://unsplash.com/">Unsplash</a></em></p>
<h3 id="you-might-also-enjoy-the-following-articles">You might also enjoy the following articles:</h3>
<ul>
<li><a target="_blank" href="https://blog.skay.dev/iife-immediately-invoked-function-expressions">IIFE</a></li>
<li><a target="_blank" href="https://blog.skay.dev/history-of-ecma-es5-es6-and-beyond">History of ECMAScript</a></li>
<li><a target="_blank" href="https://blog.skay.dev/es6-arrow-functions">ES6 =&gt; Arrow Functions</a></li>
<li><a target="_blank" href="https://blog.skay.dev/docker-fundamentals">Docker Fundamentals</a></li>
<li><a target="_blank" href="https://blog.skay.dev/what-are-git-hooks">What are Git Hooks?</a></li>
<li><a target="_blank" href="https://blog.skay.dev/guide-organised-and-productive">A Practical Guide to help you stay organized and productive</a></li>
<li><a target="_blank" href="https://blog.skay.dev/javascript-event-loop-explained">What is Event Loop in JavaScript?</a></li>
<li><a target="_blank" href="https://blog.skay.dev/a-basic-introduction-to-webpack">A Basic Introduction to Webpack</a></li>
<li><a target="_blank" href="https://blog.skay.dev/understanding-closures">Understanding Closures</a></li>
<li><a target="_blank" href="https://blog.skay.dev/what-is-this-in-javascript">What is 'this' in JavaScript?</a></li>
</ul>
]]></content:encoded></item><item><title><![CDATA[What are Git Hooks?]]></title><description><![CDATA[Introduction
In this article, we'll look at what Git Hooks are, why using Git Hooks are beneficial, and some practical examples of how to use them for development.
What are Git Hooks?
Git hooks are scripts that run automatically every time a particul...]]></description><link>https://blog.skay.dev/what-are-git-hooks</link><guid isPermaLink="true">https://blog.skay.dev/what-are-git-hooks</guid><category><![CDATA[100DaysOfCode]]></category><category><![CDATA[Git]]></category><category><![CDATA[General Programming]]></category><category><![CDATA[GitHub]]></category><dc:creator><![CDATA[Skay]]></dc:creator><pubDate>Wed, 23 Sep 2020 05:14:51 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1600837609328/l9OpE_hP3.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="introduction">Introduction</h2>
<p>In this article, we'll look at what Git Hooks are, why using Git Hooks are beneficial, and some practical examples of how to use them for development.</p>
<h2 id="what-are-git-hooks">What are Git Hooks?</h2>
<p>Git hooks are scripts that run automatically every time a particular event occurs in a Git repository. Through the scripts, you can customize Git’s internal behavior and trigger customizable actions at key points in the development life cycle.</p>
<p>There are two kinds of hooks:</p>
<ul>
<li>Client-side (local) hooks - They are prompted by the events on the local repository. For example, when a developer commits or merges the code.</li>
<li>Server-side (remote) hooks - They are prompted by the events on the server hosting the repository. For example, when a developer pushes the code.</li>
</ul>
<h2 id="why-should-you-use-git-hooks">Why should you use Git Hooks?</h2>
<p>As a part of the learning process, the question of 'Why to use a certain piece of technology?' is very vital to understand it's true intent or purpose of existence.</p>
<p>In my opinion, the adoption of well-defined processes and the use of automation greatly enhances the team's productivity to deliver software in a predictable manner.</p>
<p>A developer in a typical day writes code and commits to the project repository. A senior developer, in general, adopts to writing meaningful commit messages when performing a code commit. However, the same cannot be expected of junior developers who have just come into the project.</p>
<p>As a check-point to this, the project lead could establish a standard commit message format and must ensure that it must be followed by other team members. A good example of that could be to ensure that every commit message should start with a JIRA task Id. This becomes an excellent use-case of a Git hook. All you have to do is customize the 'pre-commit' git hook, that can intercept any commits made by the developer and validate for a JIRA task Id to be present.</p>
<p>The above mentioned is one simple example. In reality, we can do much more with the hooks such as check for code style (run lint or some equivalent), run static code analyzer tools such as Sonarqube or an equivalent, check for documentation of API methods if they are newly introduced and so much more. The possibilities are quite endless.</p>
<h2 id="implementing-a-hook">Implementing a Hook</h2>
<p>Git hooks are a built-in feature that comes with every Git repository. Upon initializing a new project, Git automatically populates the hooks folder with template files.</p>
<p>Let us take a step-by-step approach:</p>
<h3 id="step-1-create-a-new-project-folder-and-initialize-git">Step 1 - Create a New Project folder &amp; Initialize Git</h3>
<ol>
<li>Go to any folder and create a new folder 'myproject'.</li>
<li>Cd into your project and initialize the git repository.</li>
<li>You'll see a message shown below &amp; a '.git' folder created.</li>
</ol>
<pre><code class="lang-js">$ mkdir myproject
$ cd myproject
$ git init

<span class="hljs-comment">//Ouput -&gt; Initialized empty Git repository in &lt;&lt;folder&gt;&gt;/myproject/.git/</span>
</code></pre>
<h3 id="step-2-locate-your-hooks-folder-and-view-the-files">Step 2 - Locate your Hooks folder &amp; view the files</h3>
<ol>
<li>Cd into your '.git' folder and you should see the following list of folders.</li>
</ol>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/i/qhlsj2mdsuf4vby2vay9.png" alt="Alt Text" /></p>
<ol>
<li>Cd into the 'hooks' folder, you should see the following list of files:</li>
</ol>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/i/2nsn71shlps8mvl6n9go.png" alt="Alt Text" /></p>
<ol>
<li><p>All the files with the extension '.sample' mean that they are present as a sample and they will not be executed by default.</p>
</li>
<li><p>Each file is triggered at a particular event during the git life cycle. A code of '1', signifies an error, and the process is exited at that point and a code of '0' signifies that the process went through fine.</p>
</li>
</ol>
<h3 id="step-3-installenable-the-git-hook-you-want-to-execute">Step 3 - Install/Enable the Git hook you want to execute</h3>
<p>To enable the hook, it is a simple as removing the extension of '.sample' from the file name. As soon as we do it, Git immediately will recognize that it should execute the file. In the above example, the file 'pre-commit.sample' is renamed to 'pre-commit'.</p>
<ul>
<li>Rename the file by removing the '.sample' extension.</li>
</ul>
<pre><code class="lang-js">$ mv pre-commit.sample pre-commit
</code></pre>
<ul>
<li>Change the permissions to make it executable</li>
</ul>
<pre><code class="lang-js">$ chmod +x pre-commit
</code></pre>
<h3 id="step-4-choose-the-language">Step 4 - Choose the language</h3>
<p>The default files are written in shell-scripts. You can use any scripting language as long as it can be run as an executable. The supported languages are Bash, Python, Ruby, Perl, Rust, Swift &amp; Go.</p>
<p>To choose the language of your choice, open up the file in your code editor and using the shebang (#!) sign indicate the language, so that, Git knows how to interpret the subsequent scripts.</p>
<p>For example:</p>
<p>To choose 'shell'</p>
<pre><code class="lang-js">#!<span class="hljs-regexp">/bin/</span>sh
</code></pre>
<p>To choose 'bash'</p>
<pre><code class="lang-js">#!<span class="hljs-regexp">/bin/</span>bash
</code></pre>
<h1 id="practical-examples">Practical Examples</h1>
<h2 id="check-for-a-valid-email-before-committing-the-code">Check for a valid email before committing the code</h2>
<p>It is very common for developers to have multiple Github accounts and one account could be linked to a personal email account and another one could be linked to the work email account.</p>
<p>Let us look at creating a 'pre-commit' Git Hook in order to ensure that any commits made by me are from the email Id 'skay@gmail.com'. (assuming this is the work email address)</p>
<h3 id="pre-commit-git-hook">Pre-Commit Git Hook</h3>
<p>The pre-commit Git hook to check if the user committing the file has the user email address set to 'skay@gmail.com'.</p>
<pre><code class="lang-js">#!<span class="hljs-regexp">/bin/</span>sh

# Make sure the email is set properly before committing the file
useremail=$(git config user.email)

# Check <span class="hljs-keyword">if</span> the git config useremail DOES NOT MATCH skay@gmail.com
<span class="hljs-keyword">if</span> [ <span class="hljs-string">"$useremail"</span> != <span class="hljs-string">"skay@gmail.com"</span> ]
then
        cat &lt;&lt;\EOF

# OUTPUT THE ERROR ON THE TERMINAL
<span class="hljs-attr">Error</span>: user.email not set to <span class="hljs-string">"skay@gmail.com"</span>
EOF

# EXIT WITH <span class="hljs-number">1</span> INDICATES ERROR
        exit <span class="hljs-number">1</span>
fi
</code></pre>
<p>Things to Note:</p>
<p>When the user attempts to commit the file, the script will be run. </p>
<p>The following steps are what happens in the file:</p>
<ul>
<li>The first line '#!' signifies that the script is a shell script.</li>
<li>Fetch the 'usermail' from git config user.email.</li>
<li>Check if the 'useremail' does not match 'skay@gmail.com', then throw an error on the terminal.</li>
</ul>
<h2 id="run-the-commit-to-verify-if-the-git-hook-is-invoked">Run the Commit to verify if the Git hook is invoked</h2>
<h3 id="step-1">Step 1</h3>
<p>Go to the 'myproject' folder</p>
<pre><code class="lang-js">$ cd myproject
</code></pre>
<h3 id="step-2">Step 2</h3>
<p>Create a new file</p>
<pre><code class="lang-js">$ nano demo.txt
</code></pre>
<h3 id="step-3">Step 3</h3>
<p>Enter some text &amp; save the file!</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/i/wtxrl9u7h0w4su65gx54.png" alt="Alt Text" /></p>
<h3 id="step-4">Step 4</h3>
<p>Check the current user email set in git-config</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/i/nyxjngcjtyt4q3cihd5u.png" alt="Alt Text" /></p>
<h3 id="step-5">Step 5</h3>
<p>Git add &amp; commit the file to the local repository.</p>
<pre><code class="lang-js">$ git add demo.txt

$ git commit -m <span class="hljs-string">"Testing Pre-Commit Git Hook"</span>
</code></pre>
<h3 id="step-6">Step 6</h3>
<p>If the Git 'pre-commit' Hook had fired correctly, then you should see the following error on the terminal, since the git config user email (skaytech30@gmail.com) does not match 'skay@gmail.com'.</p>
<p><img src="https://dev-to-uploads.s3.amazonaws.com/i/pjt2fw8j383ycky6lttg.png" alt="Alt Text" /></p>
<p>Congratulations! You've just created your first Git Hook and run it successfully.</p>
<h2 id="git-pre-push-hook">Git Pre-Push Hook</h2>
<p>Another great example explained of a Pre-Push hook is explained superbly by my friend Simon in the tweet below.</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://twitter.com/hashnode/status/1287621986433339393?s=20">https://twitter.com/hashnode/status/1287621986433339393?s=20</a></div>
<h2 id="bypassing-a-hook">Bypassing a Hook</h2>
<p>A Git Hook can be easily bypassed or over-ridden by the flag '--no-verify'. In the above example, if you would like to exempt running the 'pre-commit' hook, then you would have to include the no-verify flag as shown below.</p>
<pre><code class="lang-js">$ git commit -m <span class="hljs-string">"Testing Pre-Commit Git Hook"</span> --no-verify
</code></pre>
<h2 id="version-control-git-hooks">Version Control - Git Hooks</h2>
<p>As you would have observed, Git hooks are local to any repository. A simple workaround for this could be to create a 'scripts' folder in the project repository to enable version control of git hook files, so that, they can be extended to be used by the whole team.</p>
<h2 id="conclusion">Conclusion</h2>
<p>Adding Pre/Post Git Hooks is a simple way to ensure that there are checkpoints along the software development life cycle. In addition, hooks can be extended in any way to aid in repetitive testing that can be triggered upon specific file commits.</p>
<p>While it might take some time to set it up in the beginning, you would reap a lot of benefits, especially as the team grows.</p>
<p>If you would like to read further, here is a very good article by <a target="_blank" href="https://www.atlassian.com/git/tutorials/git-hooks">Atlassian on Git hooks</a>.</p>
<p>I hope you enjoyed the article. Do let me know your feedback and comments about the article.</p>
<h3 id="you-will-also-enjoy-the-following-articles">You will also enjoy the following articles:</h3>
<ul>
<li><a target="_blank" href="https://blog.skay.dev/javascript-event-loop-explained">What is Event Loop in JavaScript?</a></li>
<li><a target="_blank" href="https://blog.skay.dev/es6-arrow-functions">ES6-Arrow Functions</a></li>
<li><a target="_blank" href="https://blog.skay.dev/understanding-closures">Understanding Closures</a></li>
<li><a target="_blank" href="https://blog.skay.dev/es6-understanding-destructuring">ES6-Destructuring</a></li>
<li><a target="_blank" href="https://blog.skay.dev/a-basic-introduction-to-webpack">A Basic Introduction to Webpack</a></li>
<li><a target="_blank" href="https://blog.skay.dev/js-design-patterns-module-and-revealing-module-pattern">JS Design Patterns: Module &amp; Revealing Module Pattern</a></li>
<li><a target="_blank" href="https://blog.skay.dev/what-is-this-in-javascript">What is 'this' in JavaScript</a></li>
<li><a target="_blank" href="https://blog.skay.dev/es6-var-vs-let-and-const">ES6-var, let &amp; const</a></li>
<li><a target="_blank" href="https://blog.skay.dev/history-of-ecma-es5-es6-and-beyond">History of ECMAScript</a></li>
<li><a target="_blank" href="https://blog.skay.dev/docker-fundamentals">Docker Fundamentals</a></li>
</ul>
]]></content:encoded></item></channel></rss>