<?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[Nemotivity]]></title><description><![CDATA[Nemotivity focuses on trending design patterns while using the best-suited technologies while creating a website. Spreading knowledge at a beginner-friendly manner is also an aim here.]]></description><link>https://blog.nemotivity.dev</link><image><url>https://cdn.hashnode.com/res/hashnode/image/upload/v1657816696836/a02qIiRL6.png</url><title>Nemotivity</title><link>https://blog.nemotivity.dev</link></image><generator>RSS for Node</generator><lastBuildDate>Mon, 18 May 2026 00:32:39 GMT</lastBuildDate><atom:link href="https://blog.nemotivity.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[What to Check during JavaScript Code Review]]></title><description><![CDATA[(This article was primarily written for another blog. The language of this article is more formal. Please let me know your thoughts through the comments.)
Writing better and high-quality code is essential. Better code makes software stable and seamle...]]></description><link>https://blog.nemotivity.dev/what-to-check-during-javascript-code-review</link><guid isPermaLink="true">https://blog.nemotivity.dev/what-to-check-during-javascript-code-review</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[code review]]></category><category><![CDATA[best practices]]></category><dc:creator><![CDATA[Subha Chanda]]></dc:creator><pubDate>Sun, 17 Apr 2022 18:02:11 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1640855002953/FMYvMIGGo.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><em>(This article was primarily written for another blog. The language of this article is more formal. Please let me know your thoughts through the comments.)</em></p>
<p>Writing better and high-quality code is essential. Better code makes software stable and seamless. Better written codes are also scalable and maintainable. And to write better code, code review is one of the most critical tasks. Code review is an excellent opportunity of improving code quality. In code review, developers ask for feedback before merging or deploying code to production. Getting a look by another pair of eyes into your code helps eliminate the blind spots left by one, and it also helps to find vulnerabilities before the code moves into production.</p>
<p>But when reviewing someone else's code, you always don't have to be an expert. Having experience with the programming language and a checklist can help you get started. Here is a list of things to keep in mind during code review.</p>
<h2 id="heading-readability">Readability</h2>
<p><img src="https://images.pexels.com/photos/2733955/pexels-photo-2733955.jpeg?auto=compress&amp;cs=tinysrgb&amp;dpr=2&amp;h=650&amp;w=940" alt="Image from Pexels" /></p>
<p>Readable code is one of the essential features of good code. If a code is easy to read, it is easy to understand, making it easy to debug and maintain. Readable code means understanding what the piece of code does in the big picture by seeing the input and output of the code.</p>
<p>Unreadable code can make the work of finding a bug or maintaining a codebase lot more complicated. It is a huge technical debt. It can consume a lot of time for a developer or a team. In the long run, to make the codebase more readable, aka understandable, it is possible that they either break the system unintentionally while changing the code or delete the whole code and start from scratch.</p>
<p>Breaking down the codebase into smaller chunks can be a great way to start making a codebase understandable—separate codes by concerns. Long classes, functions, or methods can be tough to understand and hard to maintain. Break long classes, methods, or functions into smaller chunks of codes.</p>
<p>Another way to make code more readable is to naming correctly. Naming the methods or functions, classes or variables is a crucial thing to do. Names should be self-explanatory. It makes the code more understandable. If you are using abbreviations for any of your variables, ensure proper feedback is left for that.</p>
<h2 id="heading-functionality">Functionality</h2>
<p>Functionality is another major important thing. The code has to do what it is intended to do. If the code is not doing what was intended, there is no reason to keep the unnecessary code. When we write code, it is essential to keep in mind that the <em>end-user</em> is both the developer and the user. Because, in the future, the developer is also going to use the code.</p>
<p>When reading through the code, it is essential to care about the edge cases and check if any bug is visible to the naked eyes.</p>
<p>It is tough to understand just by reading a code when a code has user-facing changes, like UI changes. In such cases, it is good to ask for a demonstration of the code change.</p>
<p>It is also essential to think about functionality when some parallel programming is going on. Because, in such cases, that could cause deadlocks or race conditions. These kinds of issues are hard to find just by reading the code. It is important to think through such cases carefully and make sure that these cases are not introduced.</p>
<h2 id="heading-security">Security</h2>
<p>A security-centered mindset when writing code is very important. Prioritizing application security is very important. When reviewing the application code, check if the code covers the <a target="_blank" href="https://owasp.org/www-project-top-ten/">OWASP top ten</a>. Vulnerabilities can also be introduced through third-party libraries or modules. You have to be aware of that too. Don't use out-of-date tools or tools that have known security issues. A small security bug can cost a lot of harm to a company's reputation.</p>
<p>Security itself is a huge topic. And putting yourself in someone else's shoes can help here. You have to think about what paths you would've chosen to steal data from the application. Thinking in such a way can help you find vulnerabilities in the code when reviewing. Make sure you also check for some proper security handling like</p>
<ul>
<li>Proper exception handling</li>
<li>Security Logging</li>
<li>If data encryption is handled correctly or not</li>
</ul>
<h2 id="heading-maintainability">Maintainability</h2>
<p>The <a target="_blank" href="https://ieeexplore.ieee.org/document/159342">IEEE Standard Glossary of Software Engineering Terminology</a> defines maintainability as,</p>
<blockquote>
<p>The ease with which a software system or component can be modified to correct faults, improve performance or other attributes, or adapt to a changed environment.</p>
</blockquote>
<p>Maintainable software makes it easy to remove bugs or add features without introducing new bugs to it. Maintainable code improves usability. In the long run, if the codebase needs to be learned by a new developer, an unmaintained codebase can cost a huge amount of time and can add a lot of technical debt.</p>
<p>Maintainable code means it also implements architectural principles like <a target="_blank" href="https://en.wikipedia.org/wiki/Don%27t_repeat_yourself">DRY</a>, <a target="_blank" href="https://en.wikipedia.org/wiki/SOLID">SOLID</a>, etc. And it also uses design patterns and known algorithms to solve appropriate problems.</p>
<p>A maintainable code has to be well-documented. Check if the code README or the changelog is updated properly. If proper comments are utilized. When using comments, it is important to remember that comments must express <em>why a piece of code exists</em> rather than <em>what the code does.</em> The comments should always be made as simple as possible. However, in cases of exceptions like regular expressions or complex algorithms, we have to break this rule and explain the code. It is also essential to look for unnecessary comments that need to be removed.</p>
<p>Consistency is another thing to notice during the check of maintainability. Consistent code is maintainable. Check with the style guide of the company and be consistent with it. Consider the style guide as the absolute authority. And the code change should be followed by that. Though, there may be some cases where the style guide makes recommendations rather than declaring requirements. In such cases, it is good to be biased towards the style guide. And, if no rule is applied, then the code change should be made consistent with the existing code.</p>
<h2 id="heading-performance">Performance</h2>
<p>Checking for all the performance optimization is another important thing to have in your code review checklist. Performance has become one of the top-most priorities in building modern apps.</p>
<p>The first thing to check is, whether the code change is negatively impacting the performance of the existing code. Long database queries, unoptimized resources, or multiple unnecessary API calls can make the performance slower. Enabling lazy loading whenever possible is another performance optimization check. Also, caching should be properly used and optimized. You should also clearly check that none of the resources that are not used, is loaded, checking other than that make sure the code change relies on third-party-libraries as low as possible. Also, when working with the DOM, make sure the DOM reflow is minimized. Check the code for memory leaks. Memory leaks can be a huge contributor to performance issues. Loops are also a great contributor to performance. Making simple changes like calculating the array length outside a loop can help to boost performance. Look for such improvement areas.</p>
<p>Also, using tools like profilers can help to check for performance optimization checks.</p>
<h2 id="heading-anti-patterns">Anti-patterns</h2>
<p><img src="https://images.pexels.com/photos/3872487/pexels-photo-3872487.jpeg?auto=compress&amp;cs=tinysrgb&amp;dpr=2&amp;h=650&amp;w=940" alt="Image from Pexels" /></p>
<blockquote>
<p>An anti-pattern is a common response to a recurring problem that is usually ineffective and risks being highly counterproductive. The term, coined in 1995 by computer programmer Andrew Koenig, was inspired by the book Design Patterns, which highlights a number of design patterns in software development that its authors considered to be highly reliable and effective. (<a target="_blank" href="https://en.wikipedia.org/wiki/Anti-pattern">Wikipedia</a>)</p>
</blockquote>
<p>When working with junior developers, anti-patterns is a common pitfall that they fall for. Anti-patterns, as opposed to design patterns, is considered as bad practice in programming. For example, polluting the global namespace is an anti-pattern. When reviewing code change, you make sure that the code has no global variables. Polluting the global namespace can result in name collision. When the codebase becomes large, this can create a huge issue.</p>
<p>Extending the <code>Object</code> prototype in JavaScript is considered another bad anti-pattern. Extending the <code>Object.prototype</code> may seem helpful at times but when multiple teams start to manage the codebase, it becomes complicated and can create unknown side effects.</p>
<p>Knowing the <a target="_blank" href="https://deepsource.io/learn/software-engineering-guide/common-anti-patterns-in-javascript">possible anti-patterns</a> in JavaScript can be really beneficial during code review.</p>
<h2 id="heading-reliability">Reliability</h2>
<p>Reliability describes how fault-tolerant the code is. When things go south, reliable code shields the user experience from being ruined as much as possible. When writing code, we have to keep in mind that things will fail, resources will not load properly, API requests may return 500 requests occasionally. Writing codes keeping faults in mind can help build fault-tolerant code.</p>
<h2 id="heading-reusability">Reusability</h2>
<p>Code reuse is a development process geared towards reusing existing code. This reused-based development process has gained popularity because it can lower the maintenance cost and increase the code quality.</p>
<p>Code reusability has multiple benefits. Like, fast development speed. Reusable components can be easily used across the codebase that can increase the development speed.</p>
<p>Dependability is another benefit of having a reusable code. A reusable code component must be well tested and its bugs and faults have been fixed over time.</p>
<p>Though, having its own benefits, it's always not a good idea to make every component reusable. Abstraction only when necessary is very important otherwise making a component that is not reused can increase the maintainability burden. It also takes more time to build a reusable component. Keeping all this in mind, check if the code change has only necessary reusable code components, or if there is any scope to make a reusable component.</p>
<h2 id="heading-tests">Tests</h2>
<p>Testing plays a significant role in making a product successful. Because of this, writing good tests is extremely important. A flawed test can be more dangerous than carrying no tests. Passing tests makes a developer feel more confident to push the new code to the production repo. But it is important to check if the tests are written properly. There may be cases when the code is passing the test for the wrong reasons.</p>
<p>And when writing tests, the rules that apply for code review also apply. The tests should be readable, well-documented, maintainable, performant, and should follow patterns.</p>
<p>Also, don't just think about the test cases that are written. There may be edge cases for which test cases have been missed. Think about that too when reviewing.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Reviewing code properly is an important task because the code quality depends a lot on it. Following this checklist can help you better review the code. And also, appreciate the good things that you see in the code change. Tell the developer when they address your comments in a great way. Code reviewing should not just focus on mistakes, but also focus on appreciation and encouragement.</p>
]]></content:encoded></item><item><title><![CDATA[Build a Tic Tac Toe Game with JavaScript]]></title><description><![CDATA[This article is going to be a fun one. In this article, we'll be building a Tic Tac Toe game just by using HTML, CSS, and JavaScript. This is going to be an easy one. Both the inputs have to be placed by the user. But in another article, we will be c...]]></description><link>https://blog.nemotivity.dev/build-a-tic-tac-toe-game-with-javascript</link><guid isPermaLink="true">https://blog.nemotivity.dev/build-a-tic-tac-toe-game-with-javascript</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[HTML5]]></category><category><![CDATA[CSS]]></category><dc:creator><![CDATA[Subha Chanda]]></dc:creator><pubDate>Fri, 16 Jul 2021 14:59:03 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1626447506562/1jhHNSpHQ.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>This article is going to be a fun one. In this article, we'll be building a <strong>Tic Tac Toe game</strong> just by using HTML, CSS, and JavaScript. This is going to be an easy one. Both the inputs have to be placed by the user. But in another article, we will be covering a self-completing Tic Tac Toe game where the user will feel like he is playing with a real person. Before we jump into a tougher one, let's strengthen our base by building this one.</p>
<p><img src="https://lh5.googleusercontent.com/xi9lpQvZwaTKwvOzU54V8r1W7fNLvpz3tTiT6CVizdIxVp1ICZI0PPhkJKPeaq_eWAkdWbxnB9N97eLeCg-_VwmyBAunlAgK7ZymSQ3e7_N2NwVajzVf0hXlb9LeHdEDNe6Xzt_b" alt="building tic tac toe game in JS" /></p>
<p><strong>What Will We Learn?</strong></p>
<ul>
<li>How to add CSS Variables</li>
<li>How to add CSS styles using JavaScript</li>
<li>Real-life use of the <code>forEach</code> function</li>
</ul>
<p>The first step to start building our game is to build the markup. The markup styles are very basic. We will also not be focusing much on the CSS part because our main target from this article is to understand the JavaScript concepts behind it.</p>
<h2 id="tic-tac-toe-game-html-code">Tic Tac Toe Game - HTML Code:</h2>
<p>I will not be discussing each markup style here.</p>
<pre><code class="lang-html"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<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>Tic Tac Toe<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>

      <span class="hljs-tag">&lt;<span class="hljs-name">link</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">"stylesheet"</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"./styles.css"</span>&gt;</span>          
      <span class="hljs-tag">&lt;<span class="hljs-name">link</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">"preconnect"</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"https://fonts.gstatic.com"</span>&gt;</span>         
      <span class="hljs-tag">&lt;<span class="hljs-name">link</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"https://fonts.googleapis.com/css2?family=Nerko+One&amp;display=swap"</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">"stylesheet"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"./script.js"</span> <span class="hljs-attr">defer</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">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">class</span>=<span class="hljs-string">"container"</span>&gt;</span>

         <span class="hljs-tag">&lt;<span class="hljs-name">h1</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"heading"</span>&gt;</span>Play<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>               
         <span class="hljs-tag">&lt;<span class="hljs-name">h2</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"strategy"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
         <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"restart"</span>&gt;</span>Restart<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>

         <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"board"</span>&gt;</span>                      
            <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"box"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"0"</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">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"box"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"1"</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">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"box"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"2"</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">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"box"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"3"</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">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"box"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"4"</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">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"box"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"5"</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">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"box"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"6"</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">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"box"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"7"</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">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"box"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"8"</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">div</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">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p>As you can see, we are integrating the <strong>styles.css</strong> file and <strong>a google font</strong> at the head section. We are also adding the script file with the <code>defer</code> keyword so that the javascript loads after the HTML completes loading. We are using two headings that will show when a player wins a game and using which combination he/she won. After the heading, we are adding a <strong>restart button</strong> that will restart the board. The cells of a Tic Tac Toe are built using nine <code>div</code> tags. All the <code>div</code> tags are grouped into a single <code>div</code> tag <strong>with id board</strong>. We are also assigning an ID to each of the cells. We are using <strong>0</strong> based indexing here. You will understand the reason when we jump to the JavaScript section. So, this is it with our HTML. Now, let's jump to the CSS Part.</p>
<h2 id="tic-tac-toe-game-css-code">Tic Tac Toe Game - CSS Code</h2>
<p>Before we start writing any CSS code, you have to know about CSS <code>custom property</code>. CSS3 provides us the ability to declare custom properties and use them at multiple places in the CSS file. Any name starting with two hyphens(<code>--</code>) will be counted as a <code>custom property</code> in CSS. We can assign a value on the right-hand side of a custom property. It is like declaring variables and using their values at places. All the custom properties are declared in the <code>root</code> selector. For example,</p>
<pre><code class="lang-css"><span class="hljs-selector-pseudo">:root</span> {
  <span class="hljs-attribute">--text</span>: <span class="hljs-number">#dbdfac</span>;
  <span class="hljs-attribute">--bg</span>: <span class="hljs-number">#2a1e5c</span>;
  <span class="hljs-attribute">--btn-bg</span>: <span class="hljs-number">#d7f171</span>;
}
</code></pre>
<p>We are declaring all the custom properties here. You can see that all the properties start with two hyphens in front of them. Now to use these variables in our CSS file, we use the <code>var()</code> function to use them. See the snippet below to understand it.</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">h4</span> {
  <span class="hljs-attribute">color</span>: <span class="hljs-built_in">var</span>(--text);
  <span class="hljs-attribute">background-color</span>: <span class="hljs-built_in">var</span>(--bg);
}
</code></pre>
<p>You can see that we are <strong>passing the variable name</strong> inside the <code>var</code> function. Using this style, we can use CSS variables.</p>
<p>Now that you have understood what are CSS custom properties and how to use them, le's start styling the page.</p>
<pre><code class="lang-css"><span class="hljs-selector-pseudo">:root</span> {
  <span class="hljs-attribute">--text</span>: <span class="hljs-number">#dbdfac</span>;
  <span class="hljs-attribute">--bg</span>: <span class="hljs-number">#2a1e5c</span>;
  <span class="hljs-attribute">--btn-bg</span>: <span class="hljs-number">#d7f171</span>;
}

* {
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">0</span>;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">0</span>;
  <span class="hljs-attribute">box-sizing</span>: border-box;
}
</code></pre>
<p>As you can see from the above code, we are first declaring the colors in the <code>root</code> selector. We are also resetting the <code>margin</code> and <code>padding</code> of our document. After declaring the variables, we are using the <code>box-sizing: border-box</code> property in our universal selector. The <code>border-box</code> property helps us when working with boxes in CSS. It prevents the horizontal and vertical scrollbars. After we are done with resetting our document, we will move to style the rest of the document.</p>
<p>We are using a google font of <strong>Nerko One</strong> as you may have noticed before. Our next target is to style the body of the document. The styling is very simple. We will just add a <strong>background-color</strong>, a <strong>text color</strong>, and a <strong>font-family</strong> in this section.</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">body</span> {
  <span class="hljs-attribute">color</span>: <span class="hljs-built_in">var</span>(--text);
  <span class="hljs-attribute">background-color</span>: <span class="hljs-built_in">var</span>(--bg);
  <span class="hljs-attribute">font-family</span>: <span class="hljs-string">'Nerko One'</span>, cursive;
}
</code></pre>
<p>We are using our custom CSS properties here for the colors of the text and background color.</p>
<p>The next thing that we are going to style is the first heading. I will just paste the styles below and you will get an idea about what they do.</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">h1</span> {
  <span class="hljs-attribute">font-size</span>: <span class="hljs-number">80px</span>;
  <span class="hljs-attribute">margin-bottom</span>: <span class="hljs-number">0</span>;
  <span class="hljs-attribute">text-transform</span>: uppercase;
}
</code></pre>
<p>The <code>text-transform:uppercase</code> property will convert the text into uppercase characters. Let's jump to the container section now. The container section holds all the text, buttons and divs of our document.</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.container</span> {
  <span class="hljs-attribute">height</span>: <span class="hljs-number">100vh</span>;
  <span class="hljs-attribute">width</span>: <span class="hljs-number">100vw</span>;
  <span class="hljs-attribute">display</span>: flex;
  <span class="hljs-attribute">justify-content</span>: center;
  <span class="hljs-attribute">align-items</span>: center;
  <span class="hljs-attribute">flex-direction</span>: column;
}
</code></pre>
<p>We are giving the container a height and a width of <code>100vh</code> and <code>100vw</code> respectively so that the container <strong>covers the complete viewport height and width</strong>. Then, to center everything inside it, we are using CSS flexbox. The <code>display:flex</code> will invoke the flexbox. The <code>justify-content:center</code>, and <code>align-items:center</code> will center all the elements horizontally and vertically in the viewport.</p>
<p>But, after applying up to this style, you'll find that all the elements are set up aligned with the horizontal line. To correct it, the <code>flex-direction: column</code> property is used. It will align the items along the column.</p>
<p>The next element that we have to style is the <strong>board ID</strong>. The board ID consists of all the boxes inside it. Our strategy here to <strong>position only three boxes in a row</strong> is to give the board ID a width. Whenever the boxes reach the width, it’ll wrap the next boxes in a new line. The width of the board will be divided by three to get the width required by each box.</p>
<pre><code class="lang-css"><span class="hljs-selector-id">#board</span> {
  <span class="hljs-attribute">width</span>: <span class="hljs-number">60vw</span>;
  <span class="hljs-attribute">display</span>: flex;
  <span class="hljs-attribute">flex-wrap</span>: wrap;
  <span class="hljs-attribute">font-size</span>: <span class="hljs-number">100px</span>;
  <span class="hljs-attribute">margin-top</span>: <span class="hljs-number">40px</span>;
}
</code></pre>
<p>As you can see, we are giving the board, a <strong>width of 60 viewport</strong>. We are using <code>display: flex</code> and <code>flex-wrap: wrap</code> so that the boxes wrap after reaching the width. We are also giving a font-size and a margin for the top here.</p>
<p>Now comes the interesting part - <em>the boxes</em>. As I have just told you, we have to divide the total width of the board by three. So, dividing 60 by 3 will give us 20. This 20 will be the height and width of each box of our board. We are also specifying the height because otherwise, it'll look odd.</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.box</span> {
  <span class="hljs-attribute">height</span>: <span class="hljs-number">20vh</span>;
  <span class="hljs-attribute">width</span>: <span class="hljs-number">20vw</span>;
  <span class="hljs-attribute">display</span>: flex;
  <span class="hljs-attribute">justify-content</span>: center;
  <span class="hljs-attribute">align-items</span>: center;
  <span class="hljs-attribute">color</span>: <span class="hljs-built_in">var</span>(--text);
}
</code></pre>
<p>Here are the styles. Pretty similar to the container styles. I hope you get it. I know you can't see any output on the screen. For the lines, we will use JavaScript because it'll take less amount of time. The only thing that is left in styling our document is the restart button. I am not adding any hover effect or complicated styles. You can always edit and add your styles.</p>
<pre><code class="lang-css"><span class="hljs-selector-id">#restart</span> {
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">10px</span> <span class="hljs-number">20px</span>;
  <span class="hljs-attribute">background-color</span>: <span class="hljs-built_in">var</span>(--btn-bg);
  <span class="hljs-attribute">border</span>: none;
  <span class="hljs-attribute">border-radius</span>: <span class="hljs-number">20px</span>;
  <span class="hljs-attribute">color</span>: <span class="hljs-built_in">var</span>(--bg);
  <span class="hljs-attribute">font-size</span>: <span class="hljs-number">20px</span>;
  <span class="hljs-attribute">font-weight</span>: bold;
  <span class="hljs-attribute">cursor</span>: pointer;
  <span class="hljs-attribute">text-transform</span>: uppercase;
}
</code></pre>
<p>I hope you understand what the above styles do. We have completed our CSS stylings. Now let's jump to the most important part of our game, the JavaScript section.</p>
<h2 id="tic-tac-toe-game-javascript-code">Tic Tac Toe Game - JavaScript Code</h2>
<p>The first thing about writing our JavaScript file is to access the DOM elements in JavaScript. We will need a few things that will be manipulated in the game. Let's access the DOM.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> boxes = <span class="hljs-built_in">document</span>.querySelectorAll(<span class="hljs-string">'.box'</span>);
<span class="hljs-keyword">const</span> text = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'#heading'</span>);
<span class="hljs-keyword">const</span> strategy = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'#strategy'</span>);
<span class="hljs-keyword">const</span> restartBtn = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'#restart'</span>);
</code></pre>
<p>These four elements will be manipulated in our JavaScript. Now, let's move on to building our Tic Tac Toe board. Our aim to build the board is to add borders to the boxes. Now, which box should have which border? We will implement it using some logic.</p>
<p>In the first line of the above code, you can see that we are using the <code>querySelectorAll</code> property to access all the boxes. The <code>querySelectorAll</code> property returns an array of the elements. We will loop through each of the elements in the array and depending on some conditions we will add the borders to it. As you know, array indexes are zero-based. We will be creating a function that draws the board.</p>
<p>Let's call the function <code>drawBoard</code>. This function will not take any argument. It will <strong>add a bottom border</strong> to the elements whose <strong>indexes are less than 3</strong>. A <strong>right border will be added</strong> to those elements which are <strong>completely divisible by 3</strong>(index position 3, 6). The function will <strong>add a left border</strong> to those elements which <strong>give a modulus of 2</strong>(index position 2, 5, 8) and a <strong>top border will be added</strong> to all the elements that have an <strong>index position greater than 5</strong>. Now, if you look closely at the logic, you'll find that all of our required borders are covered using this theory. As I have mentioned earlier, we are going to create a function that will loop through each of the array elements. For this example, we will be using the <code>forEach</code> loop. We are using a <code>forEach</code> loop because while using a <code>forEach</code> loop to loop through an array, we can add a callback function to the loop. It can take three parameters. The first parameter is the current value, which is a required parameter, the second and third ones are the index and array.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> drawBoard = <span class="hljs-function">() =&gt;</span> {
  boxes.forEach(<span class="hljs-function">(<span class="hljs-params">box, i</span>) =&gt;</span> {
    <span class="hljs-keyword">let</span> styleString = <span class="hljs-string">''</span>;
    <span class="hljs-keyword">if</span> (i &lt; <span class="hljs-number">3</span>) {
      styleString += <span class="hljs-string">'border-bottom: 3px solid var(--text);'</span>;
    }
    <span class="hljs-keyword">if</span> (i % <span class="hljs-number">3</span> === <span class="hljs-number">0</span>) {
      styleString += <span class="hljs-string">'border-right: 3px solid var(--text);'</span>;
    }
    <span class="hljs-keyword">if</span> (i % <span class="hljs-number">3</span> === <span class="hljs-number">2</span>) {
      styleString += <span class="hljs-string">'border-left: 3px solid var(--text);'</span>;
    }
    <span class="hljs-keyword">if</span> (i &gt; <span class="hljs-number">5</span>) {
      styleString += <span class="hljs-string">'border-top: 3px solid var(--text);'</span>;
    }
    box.style = styleString;
    box.addEventListener(<span class="hljs-string">'click'</span>, boxClicked);
  });
};
</code></pre>
<p>In our loop, we are passing the current value using the box parameter and the index using the <code>i</code> parameter. After each iteration, we are resetting the value of a variable called <code>styleString</code>. This <code>styleString</code> variable will be used to add the CSS styles. You can see that we are using some if conditions to check our logic. Depending on the logic, we are adding borders. The styles are stored inside the <code>styleString</code> variable. And after a box meets a condition, the CSS style is added using the <code>box.style</code> method. The <code>style</code> method in JavaScript is used to add CSS styles from JavaScript. Now, after calling your function if you reload your document, you will find that our board now looks like a tic tac toe board. We also have to <strong>add an event listener for the boxes</strong>. So, we will add <code>box.addEventListener('click', boxClicked);</code> this line before our <code>forEach</code> loop closes. We are listening to a <code>click</code> event and whenever the event is listened to, we call the <code>boxClicked</code> function. We will be creating this function now.</p>
<p>Before moving to build the <code>boxClicked</code> event, we have to define a few more variables on the top of our script file.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> spaces = [];
<span class="hljs-keyword">const</span> tick_circle = <span class="hljs-string">'O'</span>;
<span class="hljs-keyword">const</span> tick_x = <span class="hljs-string">'X'</span>;
<span class="hljs-keyword">let</span> currentPlayer = tick_circle;
</code></pre>
<p>Here are the rest of the variables that we need now. The <code>spaces</code> variable is an empty array. You'll understand why we are declaring it in a little bit. Tic Tac Toe usually has an <code>X</code> and an <code>O</code> for playing. We are defining those two inside two separate variables. And a variable called <code>currentPlayer</code> that sets the <code>currentPlayer</code> to <code>O</code> at the start of a game.</p>
<p>Now, let's jump into building our <code>boxClicked</code> function. The <code>boxClicked</code> function will take the event as an argument. Let me first paste the code for you, then I'll explain it.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> boxClicked = <span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> id = e.target.id;
  <span class="hljs-keyword">if</span> (!spaces[id]) {
    spaces[id] = currentPlayer;
    e.target.innerText = currentPlayer;

    <span class="hljs-keyword">if</span> (playerWon()) {
      text.innerText = <span class="hljs-string">`<span class="hljs-subst">${currentPlayer}</span> has won!`</span>;
      restart();
      <span class="hljs-keyword">return</span>;
    }

    <span class="hljs-keyword">if</span> (playerDraw()) {
      <span class="hljs-keyword">return</span>;
    }
    currentPlayer = currentPlayer === tick_circle ? tick_x : tick_circle;
  }
};
</code></pre>
<p>So, first of all, we are assigning a variable called <code>id</code>, which will store the ID of the clicked box. The <code>event.target.id</code> gives us the ID of the <code>div</code>.</p>
<p>Then we are checking if the box is already filled. The <code>!spaces[id]</code> checks if the position is empty. And if it returns <code>true</code>, which means that the <strong>position is empty</strong>.</p>
<p>After finding that the position is empty, we assign the <code>currentPlayer</code> value to space. And then, inside the box, we assign the <code>currentPlayer</code> icon which can be "X" or "O". Once this condition is done, we check for another. This time we pass a function called <code>playerWon</code> inside the <code>if</code> statement, if the function returns <code>true</code> then we change the heading <code>innerText</code> depending on which player has won.</p>
<p>Then we call another function to restart our board. The <code>return</code> statement will take us out of the condition. Similarly, we also check depending on another function called <code>playeDraw</code>. In the last line of this function, we are just changing the <code>currentPlayer</code> icon depending on the last icon. It is checking if the <code>currentPlayer</code> icon is the circle, then we change it to "X", otherwise "O".</p>
<p>Let's now build the <code>playerWon</code> function. I have shown all the possible winning conditions in a Tic Tac Toe board.</p>
<p><img src="https://lh3.googleusercontent.com/-XQv1jxz8JZNe93ae_vuk3B2DPP-YkyL2lCoPSbCekthMChMcAYxyr7A0HE1_45gt5z0V-EmvMHHww_bCMEc4KV9LQprcX2H1xflqcYdG5t06vzithH2BIXYIJbVkWxxmBmvb6VE" alt="Tic tac toe game in javascript" /></p>
<p><img src="https://lh3.googleusercontent.com/NI6f-Zp5h-YM4BWk4jkjQ7g62OubUcmcSFitsZHF9diC2Cuf72SHbwdrdyNFNI6DD_ItlFL78IzCaHTm4HLnGjUZ7DxpT-6q9wY2gMSj0a01dSA6n_8UTfSkx9Lsigr5YJrCOlSZ" alt="Tic tac toe game in javascript" /></p>
<p><img src="https://lh3.googleusercontent.com/QNgko_hH9aKpLgPQVy58eeiBemA8BnrRLhBSd-HKVKzx0Qcpql5VnnygVQh8MSPIe4QKDZFfrvRfCp8WDZ4NsrINGxM0KZ8xneVBMqAegjf1KyYxvVYMIKB0pleYYGjxK4mMyMR8" alt="Tic tac toe game in javascript" /></p>
<p>We will be using these combinations to check if the player has won. So, for the first image our 0th index becomes constant. Then we can check if the player is also on index</p>
<ul>
<li>0, 1 and 2</li>
<li>0, 3 and 6</li>
<li>0, 4 and 8</li>
</ul>
<p>For the second image, the index position 8 becomes constant and the possible combinations will be</p>
<ul>
<li>2,5 and 8</li>
<li>6, 7 and 8</li>
<li>0, 4 and 8 is already covered</li>
</ul>
<p>And finally, for the index position 4, the combinations are</p>
<ul>
<li>2, 4 and 6</li>
<li>1, 4 and 7</li>
<li>3, 4 and 5</li>
</ul>
<p>Let's see the function now.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> playerWon = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">if</span> (spaces[<span class="hljs-number">0</span>] === currentPlayer) {
    <span class="hljs-keyword">if</span> (spaces[<span class="hljs-number">1</span>] === currentPlayer &amp;&amp; spaces[<span class="hljs-number">2</span>] === currentPlayer) {
      strategy.innerText = <span class="hljs-string">`<span class="hljs-subst">${currentPlayer}</span> wins up to top`</span>;
      <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
    }
    <span class="hljs-keyword">if</span> (spaces[<span class="hljs-number">3</span>] === currentPlayer &amp;&amp; spaces[<span class="hljs-number">6</span>] === currentPlayer) {
      strategy.innerText = <span class="hljs-string">`<span class="hljs-subst">${currentPlayer}</span> wins on the left`</span>;
      <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
    }
    <span class="hljs-keyword">if</span> (spaces[<span class="hljs-number">4</span>] === currentPlayer &amp;&amp; spaces[<span class="hljs-number">8</span>] === currentPlayer) {
      strategy.innerText = <span class="hljs-string">`<span class="hljs-subst">${currentPlayer}</span> wins diagonally`</span>;
      <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
    }
  }
  <span class="hljs-keyword">if</span> (spaces[<span class="hljs-number">8</span>] === currentPlayer) {
    <span class="hljs-keyword">if</span> (spaces[<span class="hljs-number">2</span>] === currentPlayer &amp;&amp; spaces[<span class="hljs-number">5</span>] === currentPlayer) {
      strategy.innerText = <span class="hljs-string">`<span class="hljs-subst">${currentPlayer}</span> wins on the right`</span>;
      <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
    }
    <span class="hljs-keyword">if</span> (spaces[<span class="hljs-number">6</span>] === currentPlayer &amp;&amp; spaces[<span class="hljs-number">7</span>] === currentPlayer) {
      strategy.innerText = <span class="hljs-string">`<span class="hljs-subst">${currentPlayer}</span> wins on the bottom`</span>;
      <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
    }
  }
  <span class="hljs-keyword">if</span> (spaces[<span class="hljs-number">4</span>] === currentPlayer) {
    <span class="hljs-keyword">if</span> (spaces[<span class="hljs-number">1</span>] === currentPlayer &amp;&amp; spaces[<span class="hljs-number">7</span>] === currentPlayer) {
      strategy.innerText = <span class="hljs-string">`<span class="hljs-subst">${currentPlayer}</span> wins vertically on middle`</span>;
      <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
    }
    <span class="hljs-keyword">if</span> (spaces[<span class="hljs-number">3</span>] === currentPlayer &amp;&amp; spaces[<span class="hljs-number">5</span>] === currentPlayer) {
      strategy.innerText = <span class="hljs-string">`<span class="hljs-subst">${currentPlayer}</span> wins horizontally on the middle`</span>;
      <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
    }
    <span class="hljs-keyword">if</span> (spaces[<span class="hljs-number">2</span>] === currentPlayer &amp;&amp; spaces[<span class="hljs-number">6</span>] === currentPlayer) {
      strategy.innerText = <span class="hljs-string">`<span class="hljs-subst">${currentPlayer}</span> wins diagonally`</span>;
      <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
    }
  }
};
</code></pre>
<p>As you can see, we are checking each of the conditions that I mentioned before. If a condition satisfies, then <strong>we are setting the H2 value</strong> with the condition by which a game is won and finally we are returning <strong>true</strong>. The<code>return true</code> value is important. Because, if you see the <code>boxClicked</code> function, we wait for the return value in our conditional statement.</p>
<p>Now let's create the <code>draw</code> function. The <code>draw</code> function that we are using here is very simple. If all the boxes are filled and no winning condition satisfies, then only we say that the match is drawn. I am using a different approach for this function. I am using a variable that will increment after each box is clicked. Because we have 8 boxes in total, if the counter becomes equal to 8, then we say that the match is drawn.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> playerDraw = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">let</span> draw = <span class="hljs-number">0</span>;
  spaces.forEach(<span class="hljs-function">(<span class="hljs-params">space, i</span>) =&gt;</span> {
    <span class="hljs-keyword">if</span> (spaces[i] !== <span class="hljs-literal">null</span>) draw++;
  });
  <span class="hljs-keyword">if</span> (draw === <span class="hljs-number">9</span>) {
    text.innerText = <span class="hljs-string">`Draw`</span>;
    restart();
  }
};
</code></pre>
<p>I think I don't have to explain any further here. The only thing that is left to our code now, is the <code>restart</code> function.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> restart = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
    spaces.forEach(<span class="hljs-function">(<span class="hljs-params">space, i</span>) =&gt;</span> {
      spaces[i] = <span class="hljs-literal">null</span>;
    });
    boxes.forEach(<span class="hljs-function">(<span class="hljs-params">box</span>) =&gt;</span> {
      box.innerText = <span class="hljs-string">''</span>;
    });
    text.innerText = <span class="hljs-string">`Play`</span>;
    strategy.innerText = <span class="hljs-string">``</span>;
  }, <span class="hljs-number">1000</span>);
};
</code></pre>
<p>Here is our <code>restart</code> function. I am wrapping all the code inside the function into a <code>setTimeout</code> method. The <code>setTimeout</code> function waits for a defined amount of time and then executes whatever function is created inside it. So, how do we restart our board? We assign all the spaces with a <code>null</code> value. This is done using a <code>forEach</code> loop here. You can also use a <code>for</code> or <code>for-of</code> loop. The next thing is to change all the box values to blank. This is also done using a <code>forEach</code> loop. And finally, we are changing the <code>h1</code> and <code>h4</code> text. The <code>1000</code> at the end will make sure that this function executes after one second.</p>
<p>We will add this <code>restart</code> function to the restart button also. The only downside is that it'll even after clicking the restart button, it'll execute after a second. This can be solved by using the <code>setTimeout</code> function individually to the restart function. But I won't be doing so here.</p>
<pre><code class="lang-javascript">restartBtn.addEventListener(<span class="hljs-string">'click'</span>, restart);
restart();
drawBoard();
</code></pre>
<p>After adding the function to a click event listener in the <code>restart</code> button, we are done. Finally, we are just calling the created functions.</p>
<ul>
<li><a target="_blank" href="https://codepen.io/nemo011/pen/vYmmKjg">Codepen</a></li>
</ul>
<p>The complete code is also available on this <em>Github <a target="_blank" href="https://github.com/nemo0/tic-tac-toe">repo</a></em>.</p>
<h1 id="conclusion">Conclusion</h1>
<p>The approach for this can be multiple. We can also create a complete array of possible combinations and then loop through and check if it satisfies any. You can also try to implement your logic for this game. In another article, we will be building a tic tac toe game that will give us an experience of playing against the computer.</p>
<p>If you liked this article or you have any suggestions, please leave a comment below.</p>
<p>Also checkout:</p>
<ul>
<li><strong><a target="_blank" href="https://nemotivity.dev/build-a-piano-app-using-javascript-ckpqfnqsg0ds5xis1eo5id8hd">Creating a Piano using JavaScript</a></strong></li>
<li><strong><a target="_blank" href="https://nemotivity.dev/build-a-weather-app-with-javascript-ckqcc7foq02opd6s1gj7l8039">Build a Weather App with JavaScript</a></strong></li>
</ul>
]]></content:encoded></item><item><title><![CDATA[How to Build an Animated Counter with JavaScript]]></title><description><![CDATA[I am sure at some point in your life while browsing the web, you have found a web page that shows an animated counter. A counter that starts from 0 and goes all the way up to some given number. Here is an example of how such a counter looks.

In this...]]></description><link>https://blog.nemotivity.dev/how-to-build-an-animated-counter-with-javascript</link><guid isPermaLink="true">https://blog.nemotivity.dev/how-to-build-an-animated-counter-with-javascript</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[HTML5]]></category><category><![CDATA[CSS]]></category><category><![CDATA[HTML]]></category><dc:creator><![CDATA[Subha Chanda]]></dc:creator><pubDate>Sat, 10 Jul 2021 12:54:19 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1625921612434/-ut4K1OiW.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>I am sure at some point in your life while browsing the web, you have found a web page that shows an animated counter. A <strong>counter</strong> that starts from 0 and goes all the way up to some given number. Here is an example of how such a counter looks.</p>
<p><img src="https://i.ibb.co/G56HY5M/Tab-1609130740310.gif" alt="javascript counter" /></p>
<p>In this article, we are going to build exactly a counter like this.</p>
<p>Prerequisites:</p>
<ul>
<li>Basic HTML</li>
<li>Basic CSS(including flexbox)</li>
<li>Basic JavaScript</li>
</ul>
<p>This article is going to be a shorter one. So, without wasting any more time, let’s get started.</p>
<h2 id="the-markup-html">The Markup (HTML)</h2>
<p>The markup for this example has one container. All our elements are going to be inside a parent container. All the individual counter elements, including the icons, text, and time, will be under another container. Let’s see the markup.</p>
<pre><code class="lang-html"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<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>Loading Counter<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">link</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">"stylesheet"</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"styles.css"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">link</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">"preconnect"</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"https://fonts.gstatic.com"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">link</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"https://fonts.googleapis.com/css2?family=Nunito:wght@400;900&amp;display=swap"</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">"stylesheet"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"script.js"</span> <span class="hljs-attr">defer</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">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">class</span>=<span class="hljs-string">"container"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"heading"</span>&gt;</span>
            Counting Upto the Limit
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"counter-container"</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"counter"</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">img</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"./icons/iconmonstr-time-19.svg"</span> <span class="hljs-attr">alt</span>=<span class="hljs-string">"timer"</span> <span class="hljs-attr">srcset</span>=<span class="hljs-string">""</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"icon"</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">h3</span> <span class="hljs-attr">data-target</span>=<span class="hljs-string">"15000"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"count"</span>&gt;</span>0<span class="hljs-tag">&lt;/<span class="hljs-name">h3</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">h6</span>&gt;</span>Work Hours<span class="hljs-tag">&lt;/<span class="hljs-name">h6</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">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"counter"</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">img</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"./icons/iconmonstr-coffee-11.svg"</span> <span class="hljs-attr">alt</span>=<span class="hljs-string">"Coffee"</span> <span class="hljs-attr">srcset</span>=<span class="hljs-string">""</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"icon"</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">h3</span> <span class="hljs-attr">data-target</span>=<span class="hljs-string">"1200"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"count"</span>&gt;</span>0<span class="hljs-tag">&lt;/<span class="hljs-name">h3</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">h6</span>&gt;</span>Cups of Coffee<span class="hljs-tag">&lt;/<span class="hljs-name">h6</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">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"counter"</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">img</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"./icons/iconmonstr-weather-112.svg"</span> <span class="hljs-attr">alt</span>=<span class="hljs-string">"night"</span> <span class="hljs-attr">srcset</span>=<span class="hljs-string">""</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"icon"</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">h3</span> <span class="hljs-attr">data-target</span>=<span class="hljs-string">"500"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"count"</span>&gt;</span>0<span class="hljs-tag">&lt;/<span class="hljs-name">h3</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">h6</span>&gt;</span>Sleepless Nights<span class="hljs-tag">&lt;/<span class="hljs-name">h6</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">div</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">body</span>&gt;</span>

<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p>As you can see, at the top, we include our stylesheet file and the scripts file. The <code>defer</code> tag in the script tag will ensure that the javascript loads after the HTML completes the loading. We are using the <em>Nunito google font</em>. All the icons in this tutorial are from <em><a target="_blank" href="https://iconmonstr.com/">iconmonstr</a></em>. I have downloaded these three icons for the sake of this tutorial. Inside the container <code>div</code>, we are adding a <code>div</code> that will hold the heading. We are calling this <code>div</code> <code>heading</code>. Then, we are creating another <code>div</code> called <code>counter-container</code>, that will keep all our counters. Each counter has a counter <code>div</code>. The counter <code>div</code> holds icon, an <code>H3</code> tag with 0 inside it, and an <code>H6</code> tag with some text inside. Look closely at the <code>H3</code> tag. This tag has a class of <code>count</code>and an attribute called <code>data-target</code>. The <code>data-*</code> attribute allows us to store extra information. Any user-defined name that starts with <code>data-</code> in front of it will be counted as a non-standard attribute.</p>
<p>These values can be used in JavaScript. Reading these values in JavaScript is also very simple. We can use the <code>getAttribute</code> method to read them. You’ll see it when we access it in JavaScript. In our code, these <code>data-target</code> attributes will say how much we want to count. For example, <code>15000</code> in the first attribute will count from 0 to 15000. Because our base value is zero, this is why we are adding 0 to the <code>H3</code>s.</p>
<p>So, our markup is done. Now, let’s jump to the CSS part.</p>
<h2 id="styling-the-counter-css">Styling the Counter (CSS)</h2>
<p>For this example, we are going to use extremely simple styles. Just a few flexboxes to get the positions we want.</p>
<p>Like all the other tutorials, our first thing in styling this is to reset the default values and change the <code>box-sizing</code> to <code>border-box</code>.</p>
<pre><code class="lang-css">* {
    <span class="hljs-attribute">box-sizing</span>: border-box;
    <span class="hljs-attribute">margin</span>: <span class="hljs-number">0</span>;
    <span class="hljs-attribute">padding</span>: <span class="hljs-number">0</span>;
}
</code></pre>
<p>Because we are going to use a google font <em>Nunito</em>, we have to define it in the body of our document. I am also going to add a background color.</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">body</span> {
    <span class="hljs-attribute">font-family</span>: <span class="hljs-string">'Nunito'</span>, sans-serif;
    <span class="hljs-attribute">background</span>: <span class="hljs-number">#fbf7f4</span>;
}
</code></pre>
<p>The next thing is the container.</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.container</span> {
    <span class="hljs-attribute">width</span>: <span class="hljs-number">80%</span>;
    <span class="hljs-attribute">margin</span>: auto;
}
</code></pre>
<p>These styles will restrict the container to a width of 80% of the parent. The <code>auto</code>margin will center the container. Now, let’s style the heading.</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.heading</span> {
    <span class="hljs-attribute">text-align</span>: center;
    <span class="hljs-attribute">font-size</span>: <span class="hljs-number">3.5rem</span>;
    <span class="hljs-attribute">font-weight</span>: bold;
    <span class="hljs-attribute">padding</span>: <span class="hljs-number">5rem</span> <span class="hljs-number">0</span>;
}
</code></pre>
<p>I don’t think that I have to explain anything here. The styles are pretty self-explanatory. Let’s move on to styling the <code>counter-container</code> now.</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.counter-container</span> {
    <span class="hljs-attribute">display</span>: flex;
    <span class="hljs-attribute">justify-content</span>: space-around;
    <span class="hljs-attribute">align-items</span>: center;
}
</code></pre>
<p>We want all the counters to be centered. To do this, we will take the help of flexbox. If you don’t know about flexboxes, here is a two-part article for you,</p>
<ul>
<li><strong><a target="_blank" href="https://nemotivity.dev/a-guide-to-css-flexbox-part-i-ckpw5u9az0d8uzls1c35j3f4q">Complete Guide to CSS Flexbox - Part I</a></strong></li>
<li><strong><a target="_blank" href="https://nemotivity.dev/a-guide-to-css-flexbox-part-ii-ckq7qa3pr09ouh4s15i937xak">Complete Guide to CSS Flexbox - Part II</a></strong></li>
</ul>
<p>Our counters are now centered. Let's center the texts inside the counters. We can use the <code>text-align</code> property here. Each counter is inside the <code>counter</code> <code>div</code>. Let's target the <code>div</code> and center the texts.</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.counter</span> {
    <span class="hljs-attribute">text-align</span>: center;
}
</code></pre>
<p>Now let's style the headings inside the counters. It is also very simple. I am going to paster the codes below.</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.counter</span> <span class="hljs-selector-tag">h3</span> {
    <span class="hljs-attribute">padding</span>: <span class="hljs-number">0.5rem</span> <span class="hljs-number">0</span>;
    <span class="hljs-attribute">font-size</span>: <span class="hljs-number">2.5rem</span>;
    <span class="hljs-attribute">font-weight</span>: <span class="hljs-number">800</span>;
}

<span class="hljs-selector-class">.counter</span> <span class="hljs-selector-tag">h6</span> {
    <span class="hljs-attribute">font-size</span>: <span class="hljs-number">2rem</span>;
    <span class="hljs-attribute">padding-bottom</span>: <span class="hljs-number">1rem</span>;
}
</code></pre>
<p>Finally, let's increase the icon size.</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.icon</span> {
    <span class="hljs-attribute">height</span>: <span class="hljs-number">5rem</span>;
    <span class="hljs-attribute">width</span>: auto;
}
</code></pre>
<p>We are extending the height only and setting the width to auto to adjust the width automatically.</p>
<p>And we are done with the CSS part.</p>
<h2 id="the-javascript">The JavaScript</h2>
<p>Inside our JavaScript, we only need to target a single DOM. If you go back to the HTML and check the counter <code>H3</code>, you’ll see that we have a class inside the <code>H3</code> tag. It is the <code>count</code> tag and is available on every counter header. So, in JavaScript, to target this DOM we can use the <code>querySelectorAll</code> property. This property will select all the <code>count</code> classes. Another thing that we need in our JavaScript is the speed variable. A speed variable will be used to control the counter’s speed, i.e., how fast it counts.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> counters = <span class="hljs-built_in">document</span>.querySelectorAll(<span class="hljs-string">'.count'</span>);
<span class="hljs-keyword">const</span> speed = <span class="hljs-number">200</span>;
</code></pre>
<p>Now, we will loop through each of the counters and execute a function. This function will do all the counting. Because we are going to run a function inside the loop, we can use the <code>forEach</code> loop. We have to pass in at least one parameter in a <code>forEach</code> loop. This element is the current value of the loop. Let’s say it <code>counter</code> for our app.</p>
<p>Inside the <code>forEach</code> loop, we will create a function that will do all the work. Let’s call this function <code>updateCount</code>.</p>
<pre><code class="lang-javascript">counters.forEach(<span class="hljs-function">(<span class="hljs-params">counter</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> updateCount = <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">const</span> target = <span class="hljs-built_in">parseInt</span>(counter.getAttribute(<span class="hljs-string">'data-target'</span>));
    <span class="hljs-keyword">const</span> count = <span class="hljs-built_in">parseInt</span>(counter.innerText);
    <span class="hljs-keyword">const</span> increment = <span class="hljs-built_in">Math</span>.trunc(target / speed);


  };
  updateCount();
});
</code></pre>
<p>Let’s first understand the code up to the above part. The <code>target</code> variable will hold the target that is defined using the <code>data-</code> attribute in our HTML. As you can see, to get the data values, we use the <code>getAttribute</code> method. And inside the method, we pass in the attribute's complete name, including <code>data-</code> tag. The <code>parseInt</code> in front of it will convert the value into an integer because, by default, the return value is of string type. Then we take the value of the text that is inside our <code>H3</code>. At the start, this value will be 0. So, why are we not using it directly? Because the way our counter works is that it adds a number to the inner text of the <code>H3</code> until it reaches the target value. For this, we have to keep track of the value that is generated each time by adding the increment value. We are also converting it to an integer. We can also use a <code>+</code> sign in place of the <code>parseInt</code>. The increment variable holds the number that is to be added after a specified time. We calculate it by dividing the target by speed. The <code>Math.trunc</code> will round off the value that we get by dividing. In JavaScript, there are multiple ways to round off a value. Here’s an <em><a target="_blank" href="https://nemo.hashnode.dev/lets-talk-about-mathceil-mathfloor-and-mathround-cke5vz93f013r9ds14gri50db">article</a></em> that talks about the different rounding methods.</p>
<p>The next thing is to check if we have reached the target value. And if the current value is less than the target value then we add up our increment value until we reach the target. This is a simple <code>if-else</code> statement.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">if</span> (count &lt; target) {
      counter.innerText = count + increment;
      <span class="hljs-built_in">setTimeout</span>(updateCount, <span class="hljs-number">1</span>);
    } <span class="hljs-keyword">else</span> {
      count.innerText = target;
    }
</code></pre>
<p>First, we are adding our <code>increment</code>value to the counter and changing the DOM value using <code>counter.innerText</code>. We are passing two parameters inside the <code>setTimeout</code> function. The <code>setTimeout</code> function executes a specific function after a given period of time. In our case, the first parameter is the <code>updateCount</code> function, and the 1 represents one millisecond. So, it will execute the <code>updateCount</code> function after every one millisecond until the count value is less than the target value. Otherwise, we set the inner text to the target value. The only step that is left, is to call our <code>updateCount</code> function. So, the complete JavaScript will look like this,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> counters = <span class="hljs-built_in">document</span>.querySelectorAll(<span class="hljs-string">'.count'</span>);
<span class="hljs-keyword">const</span> speed = <span class="hljs-number">200</span>;

counters.forEach(<span class="hljs-function">(<span class="hljs-params">counter</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> updateCount = <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-keyword">const</span> target = <span class="hljs-built_in">parseInt</span>(counter.getAttribute(<span class="hljs-string">'data-target'</span>));
    <span class="hljs-keyword">const</span> count = <span class="hljs-built_in">parseInt</span>(counter.innerText);
    <span class="hljs-keyword">const</span> increment = <span class="hljs-built_in">Math</span>.trunc(target / speed);

    <span class="hljs-keyword">if</span> (count &lt; target) {
      counter.innerText = count + increment;
      <span class="hljs-built_in">setTimeout</span>(updateCount, <span class="hljs-number">1</span>);
    } <span class="hljs-keyword">else</span> {
      counter.innerText = target;
    }
  };
  updateCount();
});
</code></pre>
<p>And our counter is done. Here is a complete working version of our counter.</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://codepen.io/nemo011/pen/NWjRjGy">https://codepen.io/nemo011/pen/NWjRjGy</a></div>
<p>You can also find the complete code on this Github <a target="_blank" href="https://github.com/nemo0/animated-counter">repo</a>.</p>
<h1 id="conclusion">Conclusion</h1>
<p>So, this was a pretty easy tutorial. It is a great one to practice your basic JavaScript knowledge. I hope you enjoyed building this one. Here are two more such projects that will help you to grow your JavaScript knowledge.</p>
<ul>
<li><strong><a target="_blank" href="https://nemotivity.dev/build-a-password-generator-with-javascript-ckqnqtp0b0gnnt6s1bp5r69k8">Building a Password Generator with JavaScript</a></strong></li>
<li><strong><a target="_blank" href="https://nemotivity.dev/build-a-piano-app-using-javascript-ckpqfnqsg0ds5xis1eo5id8hd">Build a Piano App using JavaScript</a></strong></li>
</ul>
<p>For more such tutorials and projects, keep visiting <strong><em><a target="_blank" href="https://nemotivity.dev/">nemotivity.dev</a></em></strong>.</p>
]]></content:encoded></item><item><title><![CDATA[Build a Password Generator with JavaScript]]></title><description><![CDATA[Building a JavaScript project always gives an excellent overview of the internals of the language. And also, it helps to make the portfolio better. In today’s article, we will be building a fantastic mini JavaScript project. We aim to develop a Passw...]]></description><link>https://blog.nemotivity.dev/build-a-password-generator-with-javascript</link><guid isPermaLink="true">https://blog.nemotivity.dev/build-a-password-generator-with-javascript</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[HTML5]]></category><category><![CDATA[CSS]]></category><dc:creator><![CDATA[Subha Chanda]]></dc:creator><pubDate>Sat, 03 Jul 2021 12:29:59 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1625315239401/B5oybJ8KY.gif" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Building a JavaScript project always gives an excellent overview of the internals of the language. And also, it helps to make the portfolio better. In today’s article, we will be building a fantastic mini JavaScript project. We aim to develop a Password Generator with pure HTML, CSS, and JavaScript. Even if you are thinking of moving to a certain framework like Angular, Vue, or React, learning core JavaScript concepts will significantly strengthen your base.</p>
<p>🖼 <strong>What Will We Learn?</strong></p>
<ul>
<li>What is an ASCII Character table</li>
<li>The <code>createElement</code>method</li>
<li>Flooring a decimal value</li>
<li>The <code>execCommand</code> method</li>
</ul>
<h1 id="writing-the-markup">🥼 Writing the Markup</h1>
<p><img src="https://lh3.googleusercontent.com/QBYO73MsSdKMZX0xupMK_tYW9CYFtNGqkmpWcqlnPC11Qut87LB9YJ97o5gAZGMiEhtQCfOUT3EbQx1W5QKHAgsL-7jXNICWE6f33JODlcCY8tH_lhQ-hgu-pY26hfbQU9iRrtdq" alt="complexe Password generator using Javascript" /></p>
<p>Before beginning to write any code, let’s first check the application itself. As you can see from the above GIF, the application has an area where the generated password is shown. It also contains a copy button that can be used to copy the password to the clipboard. Below that, we have a few options. The first one is a length property, which can be used to specify the password’s length. The next few options are to add or remove uppercase characters, numbers, or symbols. And finally, a button to generate the password. It seems easy, right? Now that we have a basic understanding of how we want to style our page we can start writing the page’s markup.</p>
<pre><code class="lang-html"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span> <span class="hljs-meta-keyword">lang</span>=<span class="hljs-meta-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">link</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">"stylesheet"</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"./styles.css"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">link</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">"preconnect"</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"https://fonts.gstatic.com"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">link</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"https://fonts.googleapis.com/css2?family=Oswald&amp;display=swap"</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">"stylesheet"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"./generator.js"</span> <span class="hljs-attr">defer</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">title</span>&gt;</span>Password Generator with JavaScript<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">form</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"passwordGeneratorForm"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"container"</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Password Generator<span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"result__container"</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"result"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"copy"</span>&gt;</span>Copy<span class="hljs-tag">&lt;/<span class="hljs-name">button</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">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"options"</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"option"</span>&gt;</span>
                    <span class="hljs-tag">&lt;<span class="hljs-name">label</span>&gt;</span>Length<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
                    <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"number"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"length"</span> <span class="hljs-attr">min</span>=<span class="hljs-string">"4"</span> <span class="hljs-attr">max</span>=<span class="hljs-string">"20"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"10"</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">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"option"</span>&gt;</span>
                    <span class="hljs-tag">&lt;<span class="hljs-name">label</span>&gt;</span>Include Uppercase<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
                    <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"checkbox"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"uppercase"</span> <span class="hljs-attr">checked</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">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"option"</span>&gt;</span>
                    <span class="hljs-tag">&lt;<span class="hljs-name">label</span>&gt;</span>Include Numbers<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
                    <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"checkbox"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"numbers"</span> <span class="hljs-attr">checked</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">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"option"</span>&gt;</span>
                    <span class="hljs-tag">&lt;<span class="hljs-name">label</span>&gt;</span>Include Symbols<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
                    <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"checkbox"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"symbols"</span> <span class="hljs-attr">checked</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">div</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"btn"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"generate"</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span>&gt;</span>Generate Password<span class="hljs-tag">&lt;/<span class="hljs-name">button</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">form</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>
</code></pre>
<p>As we can see, the markup is very straightforward. We are adding a google font to beautify the page. We are using the <strong>Oswald Google font</strong>. Other than that, we are linking our <code>styles.css</code> file and the JavaScript file that is named <code>generator.js</code>. The <code>defer</code> keyword in the script source makes sure that the JavaScript script is executed after the browser parses it.</p>
<p>Inside the <code>body</code>tag, we are wrapping the complete password generator inside a form. We can also achieve the same functionalities using a <code>div</code>. But, we would use a form here. We are also giving a <code>passwordGeneratorForm</code> ID to the form. Inside the form, we are wrapping the whole block inside a <code>div</code>called <code>container</code>. A heading is also added. We are using <code>H2</code>here for the title. Now, for the place where we want to show the password, a <code>result__container</code> class is added. This <code>result__container</code> has two items. The first one is a<code>span</code> with an ID of <code>result</code>, and the second one is a button with a text Copy in it. This button will be used as a copy to the clipboard button.</p>
<p>After closing the <code>result__container</code> <code>div</code>, we use a parent div of <code>options</code>to show the options. Each option inside the <code>options</code>class is wrapped under a div of <code>option</code>.</p>
<p>The first option in our form is the password length. The <code>input</code>tag in HTML is used for it. It’ll have a label of Length and an input type of <code>number</code>. An ID of <code>length</code>is also given to it for accessing it through JavaScript. The<code>min=”4” max=”20” value=”10”</code> represents that the input will be of a minimum value of 4 and a maximum value of 20. The default value of the input will be 10.</p>
<p>The second option that we have in our app is to check if our password contains uppercase letters. Checking it will generate a password with uppercase characters. It has a label of Include Uppercase. The checkbox is an HTML input tag with a type of <code>checkbox</code>and an ID of <code>uppercase</code>. The <code>checked</code>at the end of the input type means that by default, the box is checked. The include numbers and include symbols are the same as the include uppercase. All of these have different IDs according to their functionality.</p>
<p>Finally, after closing the options div, we add a button with a class <code>btn</code>and an ID of <code>generate</code>. The button will also have a type of <code>submit</code>. The button has a label of Generate Password. By clicking this button, the password will be generated. And we are done with the HTML.</p>
<p>Now we can move on to the CSS part. As you can see, the whole form is horizontally and vertically centered. This is achieved by using the CSS flexbox. If you are unfamiliar with CSS Flexbox, check the two-part CSS flexbox series.</p>
<ul>
<li><a target="_blank" href="https://nemotivity.dev/a-guide-to-css-flexbox-part-i-ckpw5u9az0d8uzls1c35j3f4q">CSS Flexbox Part I</a></li>
<li><a target="_blank" href="https://nemotivity.dev/a-guide-to-css-flexbox-part-ii-ckq7qa3pr09ouh4s15i937xak">CSS Flexbox Part II</a></li>
</ul>
<h1 id="styling-the-document">✨ Styling the Document</h1>
<p>The first thing that we do in every project is to clear the default formatting of the document. We will do the same here.</p>
<pre><code class="lang-css">* {
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">0</span>;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">0</span>;
  <span class="hljs-attribute">box-sizing</span>: border-box;
}
</code></pre>
<p>The next thing is to specify the height and width of the body element. We will set the height and width to <code>100vh</code> and <code>100vw</code>. The <code>vh</code> and <code>vw</code> are the viewport height and width. The viewport height and viewport width resolve a percentage of the viewport. For example, <code>10vw</code>will set 10% of the current viewport width. So, the <code>100vh</code> and <code>100vw</code> will take 100% of the current viewport height and width. These units were introduced to CSS between 2011 and 2015. Because all the elements have to be centered vertically and horizontally, we will be using flexbox here. Also, we will add the<code>font-family</code> property in the body. A background-colour is also specified here. The <code>*</code> is a global selector in CSS. The above styles will clear the default page style.</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">body</span> {
  <span class="hljs-attribute">height</span>: <span class="hljs-number">100vh</span>;
  <span class="hljs-attribute">width</span>: <span class="hljs-number">100vw</span>;
  <span class="hljs-attribute">display</span>: flex;
  <span class="hljs-attribute">align-items</span>: center;
  <span class="hljs-attribute">justify-content</span>: center;
  <span class="hljs-attribute">flex-direction</span>: column;
  <span class="hljs-attribute">font-family</span>: <span class="hljs-string">'Oswald'</span>, sans-serif;
  <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#9dc5bb</span>;
}
</code></pre>
<p>Now comes the <code>container</code> div section. This section has no complicated styling. It only has a <code>padding</code> property, a <code>border</code> property, a <code>width</code> property, and a <code>background-color</code> property. The <code>1rem</code> represents 16 pixels by default.</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.container</span> {
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">1rem</span> <span class="hljs-number">1.5rem</span>;
  <span class="hljs-attribute">border</span>: <span class="hljs-number">1px</span> solid black;
  <span class="hljs-attribute">width</span>: <span class="hljs-number">350px</span>;
  <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#bcf4f5</span>;
}
</code></pre>
<p>The Password Generator heading is the next element to style. It should be centered, so we go for the <code>text-align: center</code> property. The padding of the top and bottom is also added to make some room for the heading.</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">h2</span> {
  <span class="hljs-attribute">text-align</span>: center;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">15px</span> <span class="hljs-number">0</span>;
}
</code></pre>
<p>We have the <code>option</code>class in our document that wraps up the various options. We're going to be styling it next. Here the flexbox will also be used to space the checkbox and the label. There are also some paddings added here.</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.option</span> {
  <span class="hljs-attribute">display</span>: flex;
  <span class="hljs-attribute">justify-content</span>: space-between;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">4px</span>;
}
</code></pre>
<p>Now, we will style the password box. The password box has a <code>result__container</code> div. A height and width will be given first to this box. Then we will use flexbox here to space the password area and the copy button.</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.result__container</span> {
  <span class="hljs-attribute">height</span>: <span class="hljs-number">50px</span>;
  <span class="hljs-attribute">width</span>: <span class="hljs-number">100%</span>;
  <span class="hljs-attribute">display</span>: flex;
  <span class="hljs-attribute">justify-content</span>: space-between;
  <span class="hljs-attribute">align-items</span>: center;
  <span class="hljs-attribute">border</span>: <span class="hljs-number">1px</span> solid black;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">0</span> <span class="hljs-number">5px</span>;
}
</code></pre>
<p>The <code>justify-content:space-between</code> will push the elements to both ends. The <code>align-items:center</code> will center the elements on the cross-axis. A border and padding are also added to make proper spacing. The span where the password will be added will have only two properties. The first one is the word-wrap property. The <code>word-wrap: reak-word</code> will wrap the words inside the <code>span</code>. And a <code>max-width</code> property with the <code>calc</code> function is also added to adjust the maximum width. It is also fine if you don’t want to specify the <code>max-width</code>.</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.result-container</span> <span class="hljs-selector-id">#result</span> {
  <span class="hljs-attribute">word-wrap</span>: break-word;
  <span class="hljs-attribute">max-width</span>: <span class="hljs-built_in">calc</span>(<span class="hljs-number">100%</span> - <span class="hljs-number">40px</span>);
}
</code></pre>
<p>Now, we will be styling the copy button. The styling is very easy. I’ll just paste the styles below and you will get an understanding.</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.result__container</span> <span class="hljs-selector-id">#copy</span> {
  <span class="hljs-attribute">height</span>: <span class="hljs-number">40px</span>;
  <span class="hljs-attribute">width</span>: <span class="hljs-number">40px</span>;
  <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#5bc0be</span>;
  <span class="hljs-attribute">color</span>: <span class="hljs-number">#ffffff</span>;
  <span class="hljs-attribute">border</span>: none;
  <span class="hljs-attribute">cursor</span>: pointer;
  <span class="hljs-attribute">outline</span>: none;
}

<span class="hljs-selector-class">.result__container</span> <span class="hljs-selector-id">#copy</span><span class="hljs-selector-pseudo">:hover</span> {
  <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#1c2541</span>;
  <span class="hljs-attribute">color</span>: <span class="hljs-number">#ffffff</span>;
}
</code></pre>
<p>We are specifying a height and width for the button. The cursor is changed to a <code>pointer</code> because we want to point that the button is clickable. The <code>outline:none</code> property will remove the border that is shown when the button is clicked. We are also setting the border to <code>none</code>. And, for the hover effect, we are changing the background color.</p>
<p>The only thing that is left now is the generate button. This is also similar to the above styles. We are just adding a <code>border-radius</code> extra here.</p>
<pre><code class="lang-css"><span class="hljs-selector-id">#generate</span> {
  <span class="hljs-attribute">height</span>: <span class="hljs-number">40px</span>;
  <span class="hljs-attribute">width</span>: <span class="hljs-number">100%</span>;
  <span class="hljs-attribute">border-radius</span>: <span class="hljs-number">10px</span>;
  <span class="hljs-attribute">border</span>: none;
  <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#0b132b</span>;
  <span class="hljs-attribute">color</span>: <span class="hljs-number">#ffffff</span>;
  <span class="hljs-attribute">font-size</span>: <span class="hljs-number">15px</span>;
  <span class="hljs-attribute">font-weight</span>: bold;
  <span class="hljs-attribute">cursor</span>: pointer;
  <span class="hljs-attribute">outline</span>: none;
}
<span class="hljs-selector-id">#generate</span><span class="hljs-selector-pseudo">:hover</span> {
  <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#5bc0be</span>;
  <span class="hljs-attribute">color</span>: <span class="hljs-number">#ffffff</span>;
}
</code></pre>
<p>Now comes the tricky part - the JavaScript section. The JavaScript part is the heart of this app. All the interactivity is achieved using JavaScript. Let’s move on to JavaScript.</p>
<h1 id="the-javascript-part">🎩 The JavaScript Part</h1>
<p>Before writing the codes straight, let’s get an understanding of the ASCII character table. All the characters that we have on our keyboard have different codes assigned to them.</p>
<p><img src="https://lh4.googleusercontent.com/1cPd0L10vghSgF_lJVGFabR01p85C5HFMp_urm3VxviDpXwWPtSwW0JJjX_gMSlLpLZS9dnDm88_dnuI5YUirtTljn2aWmbissShm_qGteEUrNHNeFaH5iV03wheyEuUce01IpWm" alt="Password generator Javascript" /></p>
<p><em>Image Source: https://bournetocode.com/projects/GCSE_Computing_Fundamentals/pages/3-3-5-ascii.html</em></p>
<p>The codes are in different number systems. If you see the ASCII column in the above image, the uppercase ASCII A has a value of 65. And if you increase the values with one, we’ll eventually get all the 26 uppercase characters. Similarly, the lowercase starts at decimal 97 and keeps going up to 122. The decimal numbers start at 48 and end at 57. The symbols are at various places. We will use these decimal values to generate different password combinations. This might seem confusing until now, but we’ll eventually understand what we are going to do with these codes.</p>
<p>Let’s complete the tedious task first. Linking the different HTML elements in the JavaScript seems the most tedious task to me. However, it is one of the most important things to do. All our different options, buttons, and the password box have different IDs assigned to them. Let’s grab them using their IDs.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Getting the DOM Eleements</span>
<span class="hljs-keyword">const</span> resultDOM = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'result'</span>);
<span class="hljs-keyword">const</span> copybtnDOM = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'copy'</span>);
<span class="hljs-keyword">const</span> lengthDOM = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'length'</span>);
<span class="hljs-keyword">const</span> uppercaseDOM = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'uppercase'</span>);
<span class="hljs-keyword">const</span> numbersDOM = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'numbers'</span>);
<span class="hljs-keyword">const</span> symbolsDOM = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'symbols'</span>);
<span class="hljs-keyword">const</span> generatebtn = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'generate'</span>);
<span class="hljs-keyword">const</span> form = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'passwordGeneratorForm'</span>);
</code></pre>
<p>There is nothing much to explain here. So, we will jump to the next part.</p>
<p>As you have seen, all characters have a unique decimal value assigned to them. JavaScript has a particular method called <code>fromCharCode</code>. This method returns a string corresponding to the decimal value that we pass.</p>
<p><img src="https://lh3.googleusercontent.com/5lvPiOQelR2rVUYBe3azVknpaR8tV1PYpmpZiOvR0PU19tmjfCXJpobyQtJxoKqIBpbaP6lAqOh5RdPWo4Z0ahMeDC5Ji2-9QdPTU8T_tBSKDzYue9fpjiEJHI-pjeKDubeQmFXY" alt="Password generator Javascript" /></p>
<p>It is a static method of the <code>String</code> object, and for this, we always have to use the <code>String.fromCharCode(value)</code> syntax. So, now we have understood that we can generate the characters from codes. Now, we need such a function that will create all the characters. To achieve this, we’ll create a function that generates the decimal values of the characters. And in the end, we will convert all these values to characters using this method.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Character Code Generating Function</span>
<span class="hljs-keyword">let</span> arrayFromLowToHigh = <span class="hljs-function">(<span class="hljs-params">low, high</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> array = [];
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = low; i &lt;= high; i++) {
    array.push(i);
  }
  <span class="hljs-keyword">return</span> array;
};
</code></pre>
<p>This function will take two inputs, one for the smallest value and one for the highest value. It is an effortless function. It just increments until the highest value is achieved. All the incremented values are pushed to an array, and finally, the function returns the array.</p>
<p>This function can be used to generate decimal values of the characters.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Generating Character Codes</span>
<span class="hljs-keyword">const</span> UPPERCASE_CODES = arrayFromLowToHigh(<span class="hljs-number">65</span>, <span class="hljs-number">90</span>);
<span class="hljs-keyword">const</span> LOWERCASE_CODES = arrayFromLowToHigh(<span class="hljs-number">97</span>, <span class="hljs-number">122</span>);
<span class="hljs-keyword">const</span> NUMBER_CODES = arrayFromLowToHigh(<span class="hljs-number">48</span>, <span class="hljs-number">57</span>);
<span class="hljs-keyword">const</span> SYMBOL_CODES = arrayFromLowToHigh(<span class="hljs-number">33</span>, <span class="hljs-number">47</span>)
  .concat(arrayFromLowToHigh(<span class="hljs-number">58</span>, <span class="hljs-number">64</span>))
  .concat(arrayFromLowToHigh(<span class="hljs-number">91</span>, <span class="hljs-number">96</span>))
  .concat(arrayFromLowToHigh(<span class="hljs-number">123</span>, <span class="hljs-number">126</span>));
</code></pre>
<p>As you can see, for the uppercase codes, we are passing the low of 65 i.e, the value of uppercase A, and the high value of 90 i.e., the uppercase Z. Similarly, we are doing this for the lowecase characters and the numbers. Generating the character codes of the symbols are little different. Because they are distributed in the various corners of the table, we need to use the concat function to combine them into a single array. The symbols starts at 33 and increments up to 47 and then again continues at 58 and so on.</p>
<p>The <code>concat</code>method in JavaScript allows the concatenation of strings and arrays. Calling <code>concat</code>on a string or array and passing another string or array inside the <code>concat</code>function will concatenate the strings or arrays.</p>
<p><strong>Syntax**</strong>:</p>
<pre><code class="lang-javascript">str.concat(string2, string3, string4,......, stringN)
</code></pre>
<p>Where <code>str</code> is the base string, and the parameters are the strings that we want to concatenate. Here’s an example to help you understand the method better.</p>
<p><img src="https://lh5.googleusercontent.com/mCN8c_gP5HyhkOaEXyAF5OzEHfvlWb31Kx6Yoom5MrGgBQpo43KxOxKR5V99JbNjjzKm35Vr18xXD1TlUGJp1K3CBBibnYNkjpoMy8p8cBXW5q2uHaVcZAw-rjC0oyaPRUvUhmX_" alt="img" /></p>
<p>So, calling the <code>arrayFromLowToHigh</code> function with different ranges inside the <code>concat</code> method will create a complete array consisting of all the standard symbols’ decimal values.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Generating Character Codes</span>
<span class="hljs-keyword">const</span> UPPERCASE_CODES = arrayFromLowToHigh(<span class="hljs-number">65</span>, <span class="hljs-number">90</span>);
<span class="hljs-keyword">const</span> LOWERCASE_CODES = arrayFromLowToHigh(<span class="hljs-number">97</span>, <span class="hljs-number">122</span>);
<span class="hljs-keyword">const</span> NUMBER_CODES = arrayFromLowToHigh(<span class="hljs-number">48</span>, <span class="hljs-number">57</span>);
<span class="hljs-keyword">const</span> SYMBOL_CODES = arrayFromLowToHigh(<span class="hljs-number">33</span>, <span class="hljs-number">47</span>)
  .concat(arrayFromLowToHigh(<span class="hljs-number">58</span>, <span class="hljs-number">64</span>))
  .concat(arrayFromLowToHigh(<span class="hljs-number">91</span>, <span class="hljs-number">96</span>))
  .concat(arrayFromLowToHigh(<span class="hljs-number">123</span>, <span class="hljs-number">126</span>));
</code></pre>
<p>By console logging all the arrays, you’ll be able to see that we have the arrays with decimal codes of the different characters.</p>
<p><img src="https://lh3.googleusercontent.com/PDzIfx_4k4B1ng99WpoieL8ifdTxdU1E3f0oK_ptVVnJVDtD2BjlzNSRM4rksy8sP2xF6wFOZjlmLnevACv6GLB3kCqnUXCp_BTi4SlSkwNagtb2HtsgvhjSaAqeTYFWRkcVmOa0" alt="img" /></p>
<p>We’ll be now moving on to making the Generate Password button working. We’ll target the button using the submit event listener. Until this point, if you click the button, you’ll find that the page is reloading. The first thing that we need to do is to disable this reloading behavior. JavaScript has a web API called <code>preventDefault</code>. The <code>preventDefault</code> method will make sure that the default behavior is not taken as it usually would be. To understand more about this method, I’d suggest you check this <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault">article</a>.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Checking the options that are selected and setting the password</span>
form.addEventListener(<span class="hljs-string">'submit'</span>, <span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> {
  e.preventDefault();
  <span class="hljs-keyword">const</span> characterAmount = lengthDOM.value;
  <span class="hljs-keyword">const</span> includeUppercase = uppercaseDOM.checked;
  <span class="hljs-keyword">const</span> includeNumbers = numbersDOM.checked;
  <span class="hljs-keyword">const</span> includeSymbols = symbolsDOM.checked;
  <span class="hljs-keyword">const</span> password = generatePassword(
    characterAmount,
    includeUppercase,
    includeNumbers,
    includeSymbols
  );
  resultDOM.innerText = password;
});
</code></pre>
<p>In the above code, you can see that we are listening to the submit event. Getting the event, we are passing it to a function. We are using arrow functions here. The <code>e</code> is representing the event. The<code>e.preventDefault()</code> is restricting the default behavior. Then, we are checking the multiple options. We can access the value inside the password length field by using the <code>.value</code> getter method that returns the input value. The <code>.checked</code>getter will return true if the checkboxes are selected. Otherwise, it’ll return false. The values that we are getting from the options are stored inside separate variables. We are also creating a variable called <code>password</code>. This variable will store the value returned by the <code>generatePassword</code> function that we’ll create soon. The <code>generatePassword</code> function takes four arguments because we have four options to select from. The arguments are the values stored by the variables that we declared above. Finally, with the <code>innerText</code> method’s help, we target the text inside <code>resultDOM</code> and change with the generated password.</p>
<p>The <code>generatePassword</code> function is the most crucial function here. Because the password that we are getting is generated using this function. We’ll be building this function now.</p>
<p>In the above code, we have seen that the <code>generatePassword</code> function takes four arguments. So, we also have to pass in the four parameters when creating the function. We will be using arrow functions again here.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> generatePassword = <span class="hljs-function">(<span class="hljs-params">
characterAmount,
includeUppercase,
includeNumbers,
includeSymbols
</span>) =&gt;</span> {
}
</code></pre>
<p>We want the password to be lowercase if no option is checked. Inside our function, we will create a variable that will store an array of the character codes. We’ll initially assign the lowercase character codes inside it.</p>
<pre><code class="lang-javascript">  <span class="hljs-keyword">let</span> charCodes = LOWERCASE_CODES;
</code></pre>
<p>After that, we will check the options if they are true or not. We’ll use conditional statements for this.</p>
<pre><code class="lang-javascript">  <span class="hljs-keyword">if</span> (includeUppercase) charCodes = charCodes.concat(UPPERCASE_CODES);
  <span class="hljs-keyword">if</span> (includeSymbols) charCodes = charCodes.concat(SYMBOL_CODES);
  <span class="hljs-keyword">if</span> (includeNumbers) charCodes = charCodes.concat(NUMBER_CODES);
</code></pre>
<p>Depending on the options that are selected, we will concatenate the values to the <code>charCodes</code> variable. Now, for the password that will be generated, we create an empty array first. For this example, we will call it <code>passwordCharacters</code>. Then, we will create a loop that will loop until it reaches the number of characters we want. Inside the loop, we generate random character codes from the values that are available in the <code>charCodes</code>array. And finally, we convert the characters from the character codes and push it into the <code>passwordCharacters</code> array. Let’s see the complete <code>generatePassword</code> function now.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Password Generating Function</span>
<span class="hljs-keyword">let</span> generatePassword = <span class="hljs-function">(<span class="hljs-params">
  characterAmount,
  includeUppercase,
  includeNumbers,
  includeSymbols
</span>) =&gt;</span> {
  <span class="hljs-keyword">let</span> charCodes = LOWERCASE_CODES;
  <span class="hljs-keyword">if</span> (includeUppercase) charCodes = charCodes.concat(UPPERCASE_CODES);
  <span class="hljs-keyword">if</span> (includeSymbols) charCodes = charCodes.concat(SYMBOL_CODES);
  <span class="hljs-keyword">if</span> (includeNumbers) charCodes = charCodes.concat(NUMBER_CODES);
  <span class="hljs-keyword">const</span> passwordCharacters = [];
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; characterAmount; i++) {
    <span class="hljs-keyword">const</span> characterCode =
      charCodes[<span class="hljs-built_in">Math</span>.floor(<span class="hljs-built_in">Math</span>.random() * charCodes.length)];
    passwordCharacters.push(<span class="hljs-built_in">String</span>.fromCharCode(characterCode));
  }
  <span class="hljs-keyword">return</span> passwordCharacters.join(<span class="hljs-string">''</span>);
};
</code></pre>
<p>So, we loop till the characterAmount that we are getting from the input field in our app. The <code>charCodes</code> variable has all the character codes depending on the options selected. We will then generate a random index position of the array using the <code>Math.random()</code> method. We are multiplying it with <code>charCodes.length</code> to restrict it to generate numbers up to the highest index position only. The <code>Math.floor</code> will round-off the number that is generated.</p>
<p>The <code>String.fromCharCode(characterCode)</code> will generate the string from the character code, and the<code>passwordCharacters.push()</code> will finally push the character to the array. The <code>return passwordCharacters.join(‘’)</code> will convert the array to a string and return it.</p>
<p>And we are almost done. The only thing that is left is the copy to clipboard functionality. It may seem complicated, but actually, it is not. The copy to clipboard functionality can be achieved with just a few lines of JavaScript code. The simplest way to achieve it is by following the below steps.</p>
<ol>
<li>Create a <code>textarea</code> element</li>
<li>Set it’s <code>value</code> to the value we want to copy</li>
<li>Append the <code>textarea</code> to the HTML document</li>
<li>Select the value using the <code>select()</code> method</li>
<li>Execute the <code>execCommand(‘copy’)</code> method</li>
<li>Remove the <code>textarea</code></li>
</ol>
<p>And we are done. Let’s see how we can integrate it within our code. We have a <code>copybtnDOM</code>button. We will listen to the click event on this element. When the event is triggered, we’ll execute a function. Inside the function, the first thing we will do is to create a <code>textarea</code> element. We can create HTML elements from JavaScript using the <code>createElement</code> method by passing the element we want to create.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> textarea = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">'textarea'</span>);
</code></pre>
<p>We will create a variable now that will store the value that is to be copied. We can get the value using the<code>resultDOM.innerText</code> because the text inside the <code>resultDOM</code> holds our generated password.</p>
<pre><code class="lang-javascript">  <span class="hljs-keyword">const</span> passwordToCopy = resultDOM.innerText;
</code></pre>
<p>If the <code>passwordToCopy</code> variable is empty, we will just return the function.</p>
<pre><code class="lang-javascript">  <span class="hljs-comment">// Edge Case when Password is Empty</span>
  <span class="hljs-keyword">if</span> (!passwordToCopy) <span class="hljs-keyword">return</span>;
</code></pre>
<p>The next step is to set the <code>textarea</code> value with the value that we want to copy.</p>
<pre><code class="lang-javascript">  textarea.value = passwordToCopy;
</code></pre>
<p>Now, we will append it to the body of our document using the <code>appendChild</code> method. The <code>appendChild</code> method adds a node to the end of the list of children of a specified parent node.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">document</span>.body.appendChild(textarea);
</code></pre>
<p>So, the above code will create a children node of <code>textarea</code> inside the body parent.</p>
<p>To select the elements that we want to copy, we execute <code>textarea.select();</code> method.</p>
<p>To copy the elements, we execute <code>document.execCommand('copy');</code> method. The <code>execCommand()</code> method executes the specified command for the selected part of an editable section; for this app, the editable section is the <code>textarea</code>. The <code>copy</code>command inside it will copy the values of the editable section.</p>
<p>After copying is done, we have to remove the <code>textarea</code>. It can be removed using <code>textarea.remove();</code>. And finally, to give the user a notification that the password is successfully copied, we will use a simple <code>alert</code>.</p>
<pre><code class="lang-javascript">alert(<span class="hljs-string">'Password Copied to Clipboard'</span>);
</code></pre>
<p>So, the final copy to clipboard functionality will look like this,</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Copy Password</span>
copybtnDOM.addEventListener(<span class="hljs-string">'click'</span>, <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">const</span> textarea = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">'textarea'</span>);
  <span class="hljs-keyword">const</span> passwordToCopy = resultDOM.innerText;

  <span class="hljs-comment">// Edge Case when Password is Empty</span>
  <span class="hljs-keyword">if</span> (!passwordToCopy) <span class="hljs-keyword">return</span>;

  <span class="hljs-comment">// Copy Functionality</span>
  textarea.value = passwordToCopy;
  <span class="hljs-built_in">document</span>.body.appendChild(textarea);
  textarea.select();
  <span class="hljs-built_in">document</span>.execCommand(<span class="hljs-string">'copy'</span>);
  textarea.remove();
  alert(<span class="hljs-string">'Password Copied to Clipboard'</span>);
});
</code></pre>
<p>And we are done. We have successfully made our working password generator app. Finally, the complete JavaScript code looks like this,</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Getting the DOM Eleements</span>
<span class="hljs-keyword">const</span> resultDOM = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'result'</span>);
<span class="hljs-keyword">const</span> copybtnDOM = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'copy'</span>);
<span class="hljs-keyword">const</span> lengthDOM = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'length'</span>);
<span class="hljs-keyword">const</span> uppercaseDOM = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'uppercase'</span>);
<span class="hljs-keyword">const</span> numbersDOM = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'numbers'</span>);
<span class="hljs-keyword">const</span> symbolsDOM = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'symbols'</span>);
<span class="hljs-keyword">const</span> generatebtn = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'generate'</span>);
<span class="hljs-keyword">const</span> form = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'passwordGeneratorForm'</span>);

<span class="hljs-comment">// Generating Character Codes</span>
<span class="hljs-keyword">const</span> UPPERCASE_CODES = arrayFromLowToHigh(<span class="hljs-number">65</span>, <span class="hljs-number">90</span>);
<span class="hljs-keyword">const</span> LOWERCASE_CODES = arrayFromLowToHigh(<span class="hljs-number">97</span>, <span class="hljs-number">122</span>);
<span class="hljs-keyword">const</span> NUMBER_CODES = arrayFromLowToHigh(<span class="hljs-number">48</span>, <span class="hljs-number">57</span>);
<span class="hljs-keyword">const</span> SYMBOL_CODES = arrayFromLowToHigh(<span class="hljs-number">33</span>, <span class="hljs-number">47</span>)
  .concat(arrayFromLowToHigh(<span class="hljs-number">58</span>, <span class="hljs-number">64</span>))
  .concat(arrayFromLowToHigh(<span class="hljs-number">91</span>, <span class="hljs-number">96</span>))
  .concat(arrayFromLowToHigh(<span class="hljs-number">123</span>, <span class="hljs-number">126</span>));

<span class="hljs-comment">// Copy Password</span>
copybtnDOM.addEventListener(<span class="hljs-string">'click'</span>, <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">const</span> textarea = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">'textarea'</span>);
  <span class="hljs-keyword">const</span> passwordToCopy = resultDOM.innerText;

  <span class="hljs-comment">// Edge Case when Password is Empty</span>
  <span class="hljs-keyword">if</span> (!passwordToCopy) <span class="hljs-keyword">return</span>;

  <span class="hljs-comment">// Copy Functionality</span>
  textarea.value = passwordToCopy;
  <span class="hljs-built_in">document</span>.body.appendChild(textarea);
  textarea.select();
  <span class="hljs-built_in">document</span>.execCommand(<span class="hljs-string">'copy'</span>);
  textarea.remove();
  alert(<span class="hljs-string">'Password Copied to Clipboard'</span>);
});

<span class="hljs-comment">// Checking the options that are selected and setting the password</span>
form.addEventListener(<span class="hljs-string">'submit'</span>, <span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> {
  e.preventDefault();
  <span class="hljs-keyword">const</span> characterAmount = lengthDOM.value;
  <span class="hljs-keyword">const</span> includeUppercase = uppercaseDOM.checked;
  <span class="hljs-keyword">const</span> includeNumbers = numbersDOM.checked;
  <span class="hljs-keyword">const</span> includeSymbols = symbolsDOM.checked;
  <span class="hljs-keyword">const</span> password = generatePassword(
    characterAmount,
    includeUppercase,
    includeNumbers,
    includeSymbols
  );
  resultDOM.innerText = password;
});

<span class="hljs-comment">// Password Generating Function</span>
<span class="hljs-keyword">let</span> generatePassword = <span class="hljs-function">(<span class="hljs-params">
  characterAmount,
  includeUppercase,
  includeNumbers,
  includeSymbols
</span>) =&gt;</span> {
  <span class="hljs-keyword">let</span> charCodes = LOWERCASE_CODES;
  <span class="hljs-keyword">if</span> (includeUppercase) charCodes = charCodes.concat(UPPERCASE_CODES);
  <span class="hljs-keyword">if</span> (includeSymbols) charCodes = charCodes.concat(SYMBOL_CODES);
  <span class="hljs-keyword">if</span> (includeNumbers) charCodes = charCodes.concat(NUMBER_CODES);
  <span class="hljs-keyword">const</span> passwordCharacters = [];
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; characterAmount; i++) {
    <span class="hljs-keyword">const</span> characterCode =
      charCodes[<span class="hljs-built_in">Math</span>.floor(<span class="hljs-built_in">Math</span>.random() * charCodes.length)];
    passwordCharacters.push(<span class="hljs-built_in">String</span>.fromCharCode(characterCode));
  }
  <span class="hljs-keyword">return</span> passwordCharacters.join(<span class="hljs-string">''</span>);
};

<span class="hljs-comment">// Character Code Generating Function</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">arrayFromLowToHigh</span>(<span class="hljs-params">low, high</span>) </span>{
  <span class="hljs-keyword">const</span> array = [];
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = low; i &lt;= high; i++) {
    array.push(i);
  }
  <span class="hljs-keyword">return</span> array;
}
</code></pre>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://codepen.io/nemo011/pen/JjNYEEV">https://codepen.io/nemo011/pen/JjNYEEV</a></div>
<h1 id="conclusion">🧶 Conclusion</h1>
<p>This app is just one way to generate passwords. Many other ways can be explored to achieve the same functionality. I hope you liked building our cool little password generator. If you have any doubt or suggestions, please comment below.</p>
<p>The complete code can also be found at this <a target="_blank" href="https://github.com/nemo0/password-generator">GitHub repo</a>.</p>
]]></content:encoded></item><item><title><![CDATA[Build a Weather App with JavaScript]]></title><description><![CDATA[Building a Weather app with JavaScript is an excellent project for beginners. It helps to understand the core basics of the DOM and teaches how to use fetch API, to call and get data from a third-party service.
In this tutorial, we'll be building a g...]]></description><link>https://blog.nemotivity.dev/build-a-weather-app-with-javascript</link><guid isPermaLink="true">https://blog.nemotivity.dev/build-a-weather-app-with-javascript</guid><category><![CDATA[HTML5]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[CSS]]></category><category><![CDATA[projects]]></category><dc:creator><![CDATA[Subha Chanda]]></dc:creator><pubDate>Fri, 25 Jun 2021 12:55:18 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1624625641422/C2cMxENG6n.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Building a <strong>Weather app with JavaScript</strong> is an excellent project for beginners. It helps to understand the core basics of the DOM and teaches how to use fetch API, to call and get data from a third-party service.</p>
<p>In this tutorial, we'll be building a geolocation-based weather app that will show us the current weather data depending on the user's location.</p>
<p>Prerequisites for this tutorial:</p>
<ul>
<li>Basic HTML</li>
<li>Basic CSS (including <a target="_blank" href="https://nemotivity.dev/a-guide-to-css-flexbox-part-i-ckpw5u9az0d8uzls1c35j3f4q?guid=15bb5758-cc31-443d-9440-3535920da194&amp;deviceId=7c3759fc-1bfb-4e2d-8d33-e3c3b2923931">CSS Flexbox</a>)</li>
<li>Basic JavaScript (knowing <a target="_blank" href="https://www.studytonight.com/post/understanding-promises-in-javascript-for-beginners">Javascript promise</a> is a plus)</li>
</ul>
<p>What will we learn? By building this app, we'll learn some stuff like,</p>
<ul>
<li>Interacting with the DOM</li>
<li>The use of Fetch API</li>
<li>The navigator object of JavaScript</li>
<li>How to use a third-party API service and more</li>
</ul>
<p>Now that we have understood the prerequisites and other vital information let's jump into coding our app.</p>
<h2 id="markup-of-the-app">Markup of the App</h2>
<p>The markup or HTML of the app is straightforward. You can see the image below of the final output to get an idea about our markup style.</p>
<p><img src="https://s3.ap-south-1.amazonaws.com/s3.studytonight.com/curious/uploads/pictures/1605692551-1.png" alt="Weather app Javascript" /></p>
<p>We have an image that will change according to the weather. The location will be based on the user's geolocation. Below it is the summary of the weather, the temperature is in both <strong>Celcius</strong> and <strong>Fahrenheit</strong>. And in the end, we are showing the sunrise and sunset time. We are also using the <strong>Lora google font</strong>.</p>
<pre><code class="lang-html"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<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">meta</span> <span class="hljs-attr">http-equiv</span>=<span class="hljs-string">"X-UA-Compatible"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"ie=edge"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>Weather app<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">link</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">"stylesheet"</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"styles.css"</span> /&gt;</span>
    <span class="hljs-comment">&lt;!-- Google Fonts --&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">link</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">"preconnect"</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"https://fonts.gstatic.com"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">link</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"https://fonts.googleapis.com/css2?family=Lora:ital,wght@0,700;1,600&amp;display=swap"</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">"stylesheet"</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">class</span>=<span class="hljs-string">"container"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">img</span> <span class="hljs-attr">src</span>=<span class="hljs-string">""</span> <span class="hljs-attr">alt</span>=<span class="hljs-string">""</span> <span class="hljs-attr">srcset</span>=<span class="hljs-string">""</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"weather-icon"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"location"</span>&gt;</span>Unable to Fetch Weather<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"desc"</span>&gt;</span>No Information Available.<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"weather"</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"c"</span>&gt;</span>Error<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"circle"</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">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"f"</span>&gt;</span>Error<span class="hljs-tag">&lt;/<span class="hljs-name">div</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">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"info"</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">h4</span>&gt;</span>Sunrise: <span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"sunrise"</span>&gt;</span>No Information Available<span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">h4</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">h4</span>&gt;</span>Sunset: <span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"sunset"</span>&gt;</span>No Information Available<span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">h4</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">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">"scripts.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>
</code></pre>
<p>In the above code, you can see we are using multiple <code>div</code>s with classes and IDs. The classes and IDs are important because we will be using those to interact with the DOM. In the HTML file, we link the CSS file called <strong>styles.css</strong> and the JavaScript file called <strong>scripts.js</strong>. The whole information section is wrapped under a <code>div</code> named <code>container</code>. The <code>container</code> contains an image tag with a blank <code>src</code> attribute, another <code>div</code> with an <strong>ID</strong> of location. The <code>div</code> has a text saying "Unable to fetch weather". A <code>desc</code> class is added under the location that will show the summary of the weather. And then, we are wrapping the temperatures inside a <code>div</code> called <code>weather</code>. The weather class consists of three classes to show Celcius's temperature, Fahrenheit, and a <code>div</code> to separate them. Finally, two <code>divs</code> are used to indicate sunrise and sunset timing.</p>
<p>All the div's text will be shown when the browser cannot get the users' geolocation.</p>
<p>Up to this point, our markup will look like this, if you open the above HTML file in browser,</p>
<p><img src="https://lh5.googleusercontent.com/zLhH2FLQuMDXJ8qTjjL_-favBfcG7-ic9dD7M1I5ZZ9_4nHGE_4H-aspwzYN48ggswfrq-JuLSOKZ2PhDT0FVVdTaZIRQutSq8RVk76R2jgsl1eiSAOrGTfKdh3R2F5Rf02vQ34j" alt="Javascript Weather App for beginners" /></p>
<h2 id="styling-the-markup">Styling the Markup</h2>
<p>Now it's time to style our app. The styling is also effortless. But before we start styling our app, please make sure you know about CSS flexbox. If you are not familiar with flexbox, check our two-part flexbox series.</p>
<ul>
<li><a target="_blank" href="https://nemotivity.dev/a-guide-to-css-flexbox-part-i-ckpw5u9az0d8uzls1c35j3f4q">CSS Flexbox Part 1</a></li>
<li><a target="_blank" href="https://nemotivity.dev/a-guide-to-css-flexbox-part-ii-ckq7qa3pr09ouh4s15i937xak">CSS Flexbox Part 2</a></li>
</ul>
<p>Before starting to style our project, we will reset the default margins and paddings of the page.</p>
<pre><code class="lang-css">* {
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">0</span>;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">0</span>;
  <span class="hljs-attribute">box-sizing</span>: border-box;
}
</code></pre>
<p>We will use the Lora font for the whole document. We will add the <code>font-family</code> into the body section. The asterisk(*) is a global selector that selects all the elements, and after selecting all the elements, we are setting the margin and padding to 0. The <code>box-sizing:border-box</code> makes working with flexbox easier.</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">body</span> {
  <span class="hljs-attribute">font-family</span>: <span class="hljs-string">'Lora'</span>, serif;
}
</code></pre>
<p>The <strong>serif font is a fallback to the Lora google font</strong>. Now let's start designing the container. First of all, we need to set up a height and a width. We'll be using <strong>100 viewport height</strong> and <strong>100 viewport width</strong> for the container. Then, to center the elements in our app, we'll take the help of CSS flexbox. To invoke flexbox, we need to specify <code>display:flex</code> in the container first. To center the elements along the main-axis, we use <code>justify-content:center</code>, and to center along the cross-axis, we use <code>align-items:center</code>. We also use the <code>flex-direction: column</code> here to align the items along the vertical axis. For the background, I am using a <strong>radial gradient background</strong>. To speed up the process, I am using an online gradient generator tool. The final container styling is pasted below.</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.container</span> {
  <span class="hljs-attribute">height</span>: <span class="hljs-number">100vh</span>;
  <span class="hljs-attribute">width</span>: <span class="hljs-number">100vw</span>;
  <span class="hljs-attribute">display</span>: flex;
  <span class="hljs-attribute">align-items</span>: center;
  <span class="hljs-attribute">justify-content</span>: center;
  <span class="hljs-attribute">flex-direction</span>: column;
  <span class="hljs-attribute">background</span>: <span class="hljs-built_in">rgb</span>(<span class="hljs-number">251</span>, <span class="hljs-number">242</span>, <span class="hljs-number">133</span>);
  <span class="hljs-attribute">background</span>: <span class="hljs-built_in">radial-gradient</span>(
    circle,
    rgba(<span class="hljs-number">251</span>, <span class="hljs-number">242</span>, <span class="hljs-number">133</span>, <span class="hljs-number">0.6334908963585435</span>) <span class="hljs-number">0%</span>,
    <span class="hljs-built_in">rgba</span>(<span class="hljs-number">224</span>, <span class="hljs-number">196</span>, <span class="hljs-number">91</span>, <span class="hljs-number">0.8407738095238095</span>) <span class="hljs-number">35%</span>,
    <span class="hljs-built_in">rgba</span>(<span class="hljs-number">230</span>, <span class="hljs-number">224</span>, <span class="hljs-number">113</span>, <span class="hljs-number">1</span>) <span class="hljs-number">100%</span>
  );
}
</code></pre>
<p>We will design the temperature section now. It is inside a <code>weather</code> class div. We are using a flexbox here also.</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.weather</span> {
  <span class="hljs-attribute">display</span>: flex; 
  <span class="hljs-attribute">align-items</span>: center;
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">15px</span> <span class="hljs-number">0</span>;
  <span class="hljs-attribute">font-size</span>: <span class="hljs-number">1.5rem</span>;
}
</code></pre>
<p>To add some space below and top of the temperature <code>div</code>, we add some top and bottom margins. To style the location, we are using an ID of location. And for the description, a class <code>desc</code> is used.</p>
<pre><code class="lang-css"><span class="hljs-selector-id">#location</span> {
  <span class="hljs-attribute">font-size</span>: <span class="hljs-number">3rem</span>;
  <span class="hljs-attribute">font-weight</span>: <span class="hljs-number">800</span>;
  <span class="hljs-attribute">font-style</span>: italic;
}
<span class="hljs-selector-class">.desc</span> {
  <span class="hljs-attribute">font-size</span>: <span class="hljs-number">1.25rem</span>;
  <span class="hljs-attribute">text-transform</span>: capitalize;
}
</code></pre>
<p>I think the above lines doesn't require any explanation. It is pretty self-explanatory. The <code>text-transform: capitalize</code> property capitalizes the first letter of each word. And we are using <strong>rem units</strong> here for flexibility. Finally, to create the circle between the two temperatures, we are using a div called <code>circle</code>. We are giving it a <strong>height and width of 15px</strong> and then adding a <code>border-radius</code> of <strong>50px</strong>, making it a circle.</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.circle</span> {
  <span class="hljs-attribute">background-color</span>: black;
  <span class="hljs-attribute">border-radius</span>: <span class="hljs-number">50px</span>;
  <span class="hljs-attribute">height</span>: <span class="hljs-number">15px</span>;
  <span class="hljs-attribute">width</span>: <span class="hljs-number">15px</span>;
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">0</span> <span class="hljs-number">15px</span>;
}
</code></pre>
<p>Our styling for the app is done. Now it is time for the fun part. Before directly jumping to the JavaScript part, let’s first understand a few basic concepts.</p>
<h2 id="getting-data-from-api">Getting Data from API</h2>
<p>The first thing to understand is how do we get the weather data? To get the data, we are dependent on a third-party service. We will use a website called <a target="_blank" href="https://openweathermap.org/">OpenWeatherMap</a>. <strong>OpenWeatherMap</strong> is a service that provides various weather data through API. We can integrate the API into our app and can use the data on our website. An API is like a waiter, it works as a medium between the server and the client to serve the data to the client according to the client's request.</p>
<p>OpenWeatherMap is free up to a certain number of requests. After that, it charges money. To use the API, we need an <strong>API key</strong>. Let's see how we can get our API key:</p>
<p><strong>Step 1:</strong> Open <a target="_blank" href="https://openweathermap.org/">OpenWeatherMap</a> and click on Sign In:</p>
<p><img src="https://lh5.googleusercontent.com/P6WstRIrjadC3ApEUFEVIUfnImlSkaaW0fYgHxDZYn8ZvWCaeaSP3gNTb2LQTtmrLX9g-NueuxWzIKDmGosfUdi45XDq56L3IdvRnCI4fE2x7626TQDed_Bu2Olqexjg29w2ImGF" alt="use weather API for data" /></p>
<p><strong>Step 2:</strong> Click on "<strong>Not Registered? Create an account</strong>", if you don't have an account,</p>
<p><img src="https://lh3.googleusercontent.com/LfP9G2Pk7I_0sWTZ1HD7ptL1203GcNLENvbcTB8Eax4H5Rz29cz812GNboplw5wtKcz0sQzErUAUuDSAbrfmS7--p4grxUsvKYgrrvSovoT-ieMyVgXPIvCVtmvF5yFp347_5_0g" alt="use weather API for data" /></p>
<p><strong>Step 3:</strong> Fill out the form and click on sign up to create your account.</p>
<p><img src="https://lh4.googleusercontent.com/La4OafMItcrq6KsuCEhgzJaKJYrdnqosfkGbG6d-didqGmqtYHN6vfHoKtMj7vRS_AZJywZNNAk4pxG3xw28vJjBMo4nN2BaBxxFEp29zzH1b60cNrW0sDaTfGhJXEImndDzmGoQ" alt="use weather API for data" /></p>
<p><strong>Step 4:</strong> Click on <strong>API</strong> on the menu</p>
<p><strong>Step 5:</strong> Because we need the current weather data, we will need to subscribe to the <strong>Current Weather Data API</strong> subscription. It is the first option you will see in the menu. Click on <strong>Subscribe</strong>.</p>
<p><img src="https://lh6.googleusercontent.com/LHyxOsXlvLCIv6fYgsMilU40soqkO7HXY_jqIFSxbhfguiTUtWLGlL_1913wgauMD8Gg_mujZNYlBB40-kP28LBZp7AUTI9--4SGDlXyCvA1TlKUyQH3-neugNg1954XL4CifMbk" alt="use weather API for data" /></p>
<p><strong>Step 6:</strong> Now, the pricings window will open. We don't need any paid plan for this hobby project. So, select the free option here, and we are almost done.</p>
<p><img src="https://lh6.googleusercontent.com/YYmLCz5z6mP2B9kEvpehV3U5X_9rEJP7BHIMAWsTsohPhJerb5V9RY_pWGH8dyrpnCNgizAmarSxHkf6sqywR71RittdJWn4CndAbzIRyf5yMwBIfJ_-k0SZmN8b2LLh8tfmMlKY" alt="use weather API for data" /></p>
<p><strong>Step 7:</strong> After subscribing to it, in the top right corner, where your profile name appears, click on it, and select <strong>My API Keys</strong></p>
<p><img src="https://lh5.googleusercontent.com/NJ3vYrz2ftBFCUp9NIGDd8QWaXS_Ub2uexj0_TA9Nm5Ovqik9IbwEOkLDWVAhCGPuUULJS7mfUXG0r4WKDjky_lDP6Y8q565HZtZDYc58hZmZQaokSykCmuRYZ-gigeM8YD-6FuE" alt="use weather API for data" /></p>
<p><strong>Step 8:</strong> You will find your API key here. Keep it safe, and do not share it publicly with anyone.</p>
<p><img src="https://lh3.googleusercontent.com/TFaZLJLTQHy8hY-w6pWMwR8k29zUpEyqObMgs2DvYvYAK56AX7bHibxILFdS3vDP3TKmnkBAEsDR-w8IMB9yTeB2R3Iw19YqkUGUz8NAKxtLfqvBD_yqeHcobCSQumIxCkWEapgU" alt="use weather API for data" /></p>
<p>Now that we have our API key, we can move forward to building our app again.</p>
<p>In this app, we get the <strong>user's geolocation</strong> to show weather data according to the user's place. To get the geolocation data, we first have to know about the <strong>navigator object in JavaScript</strong>. The navigator object in JavaScript is used to fetch information related to the user agent or the browser. This object has a property called <code>geolocation</code>. By using this property, we can get the user's latitude and longitude. To know more about the <code>navigator</code> object, check out this awesome article <a target="_blank" href="https://www.studytonight.com/javascript/javascript-navigator-object">here</a>.</p>
<h4 id="also-read-build-a-piano-app-using-javascripthttpsnemotivitydevbuild-a-piano-app-using-javascript-ckpqfnqsg0ds5xis1eo5id8hd"><strong>Also Read: <a target="_blank" href="https://nemotivity.dev/build-a-piano-app-using-javascript-ckpqfnqsg0ds5xis1eo5id8hd">Build a Piano App using JavaScript</a></strong></h4>
<h2 id="the-javascript-part">The JavaScript Part</h2>
<p>The first thing that we need to do in our <code>scripts.js</code> file is to create a variable to store the API key.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// OpenWeatherMap API. Do not share it publicly.</span>
<span class="hljs-keyword">const</span> api = <span class="hljs-string">'66869939e0b182ac2d6***********'</span>; <span class="hljs-comment">//Replace with your API</span>
</code></pre>
<p>I am creating a variable called <code>api</code> and storing my API key there. The next step is to create an event listener that will fire up when the page loads. So, the event we are looking for is <code>load</code> here. And when the page loads, it will execute some function that we define.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">window</span>.addEventListener(<span class="hljs-string">'load'</span>, <span class="hljs-function">() =&gt;</span> {});
</code></pre>
<p>As you can see, we are using an <strong>arrow function</strong> here. Inside the function, we will create two variables called <code>lat</code> and <code>long</code> to store the user's latitude and longitude. And then, we will use the <code>navigator</code> object to get the latitude and longitude of the user. We will use an if statement here because many browsers do not allow access to the location. If you want, you can also add an else statement for cases when the location is not available. But for the sake of simplicity, I’ll only use the if statement in this tutorial.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">window</span>.addEventListener(<span class="hljs-string">'load'</span>, <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">let</span> long;
  <span class="hljs-keyword">let</span> lat;
  <span class="hljs-comment">// Accessing Geolocation of User</span>
  <span class="hljs-keyword">if</span> (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(<span class="hljs-function">(<span class="hljs-params">position</span>) =&gt;</span> {

    });
  }
});
</code></pre>
<p>The <code>if(navigator.geolocation)</code> method will check if the object is available in the browser. If it is available, then we will call a method called <code>getCurrentPosition</code> which is available on <code>geolocation</code> property. We pass in an argument of <code>position</code> inside the <code>getCurrentPosition</code> method. We can name anything for the argument that we are passing. Now, if we console log the position, we will be able to see that we are getting the latitude and longitude. But before showing the values, the browser will ask for our permission to allow the location access.</p>
<p><img src="https://lh6.googleusercontent.com/3070vxEXONioss1A73udKQfXhLbRbrQjiu0Uni4uz2eLM7Nn4zg5qsM4H55WznEtxAb12EQaMjSz4MPxGd_CS3jQJhjep34j3LEZu66j0Nwoq9lqSRD0qc0m4SN57-Wrxc2vwf_8" alt="Weather app Javascript" /></p>
<p>If you allow your browser to access the location, the console will show your location.</p>
<p><img src="https://lh4.googleusercontent.com/SDNoCoVti0WE3fd_MfmmB_6qsclFFh65Dl7HHM_2W-tqP2yUavNPF7bcCl44Lkpeaihk3LtyWYqyRDqeeXEE1PoI4oPSjRqyLxRrX_T0RguPpPmXH-o5HKniKKZ-to14aSEGICH7" alt="Weather app Javascript" /></p>
<p>It throws multiple values. But we only need the latitude and longitude values for our app. So, we'll store these two values inside the variables that we declared before.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">window</span>.addEventListener(<span class="hljs-string">'load'</span>, <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">let</span> long;
  <span class="hljs-keyword">let</span> lat;
  <span class="hljs-comment">// Accesing Geolocation of User</span>
  <span class="hljs-keyword">if</span> (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(<span class="hljs-function">(<span class="hljs-params">position</span>) =&gt;</span> {
      <span class="hljs-comment">// Storing Longitude and Latitude in variables</span>
      long = position.coords.longitude;
      lat = position.coords.latitude;
    });
  }
});
</code></pre>
<p>Every API has a base URL. By giving some arguments to that URL returns the information that we need. For OpenWeatherMap, this URL is <code>https://api.openweathermap.org/data/2.5/weather?</code>, after the question mark(?), we provide some information to the URL, and it returns the values in JSON format. All the API calls are well described in the official documentation of OpenWeatherMap. You can visit their page <a target="_blank" href="https://openweathermap.org/current">here</a>. To get the data for a particular latitude and longitude, the below format is used.</p>
<pre><code class="lang-sh">https://api.openweathermap.org/data/2.5/weather?lat=<span class="hljs-variable">${lat}</span>&amp;lon=<span class="hljs-variable">${long}</span>&amp;appid=<span class="hljs-variable">${api}</span>&amp;units=metric`
</code></pre>
<p>Where <code>${lat}</code> is the latitude of the user, <code>${long}</code> is the longitude of the user, <code>${api}</code> is the API key provided by OWM, and at the end, <code>units=metric</code> is to get the weather data in celsius. We need to store the complete URL inside some variable. For this tutorial, we are storing it inside a variable called <code>base</code>. After storing it into a variable, if you console log it, you will get a proper URL in return. Now, if you open the URL, you can see all the different information available to you.</p>
<p><img src="https://lh4.googleusercontent.com/e5SseWGcVkLajQ3VaupodwdaXy9SgNESbHd6GCFnOgboLNnZG_AIgSjgxaHZVnsVges-oolvUZGqMonqY1XatjjAzt0X41iA0S9tAidOk930DK8eS2_-p2_OojtclmGTGUzz5M3Q" alt="Weather app Javascript" /></p>
<p>Now somehow, we need to extract all these data and show it into our app. Here comes the use of promises and object destructuring. Javascript Promise in itself a vast topic.</p>
<p>Now it is time to use the JavaScript Fetch API. The fetch API enables us to call and get data from API services. We will pass in the base variable inside it. The value that is returned after passing the base URL needs to be converted into JSON format so that we can use it in our app. So, after the first call, we return the response by transforming it to JSON.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">if</span> (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(<span class="hljs-function">(<span class="hljs-params">position</span>) =&gt;</span> {
      <span class="hljs-comment">// Storing Longitude and Latitude in variables</span>
      long = position.coords.longitude;
      lat = position.coords.latitude;
      <span class="hljs-keyword">const</span> base = <span class="hljs-string">`https://api.openweathermap.org/data/2.5/weatherlat=<span class="hljs-subst">${lat}</span>&amp;lon=<span class="hljs-subst">${long}</span>&amp;appid=<span class="hljs-subst">${api}</span>&amp;units=metric`</span>;
      <span class="hljs-built_in">console</span>.log(base);
      fetch(base).then(<span class="hljs-function">(<span class="hljs-params">response</span>) =&gt;</span> {
        <span class="hljs-keyword">return</span> response.json();
      });
    });
  }
</code></pre>
<p>The return <code>response.json();</code> converts the response to a JSON object. After we get the JSON object, we will extract the values we need for our app. This is done by using JavaScript object destructuring. A brief article about object destructuring can be found <a target="_blank" href="https://nemotivity.dev/object-destructuring-in-javascript-for-beginners-ckd901fae00n5qus1ebko8j2r">here</a>.</p>
<pre><code class="lang-javascript">  <span class="hljs-keyword">if</span> (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(<span class="hljs-function">(<span class="hljs-params">position</span>) =&gt;</span> {
      <span class="hljs-comment">// Storing Longitude and Latitude in variables</span>
      long = position.coords.longitude;
      lat = position.coords.latitude;
      <span class="hljs-keyword">const</span> base = <span class="hljs-string">`https://api.openweathermap.org/data/2.5/weather?lat=<span class="hljs-subst">${lat}</span>&amp;lon=<span class="hljs-subst">${long}</span>&amp;appid=<span class="hljs-subst">${api}</span>&amp;units=metric`</span>;

      <span class="hljs-comment">// Using fetch to get data</span>
      fetch(base)
        .then(<span class="hljs-function">(<span class="hljs-params">response</span>) =&gt;</span> {
          <span class="hljs-keyword">return</span> response.json();
        })
        .then(<span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> {
          <span class="hljs-keyword">const</span> { temp } = data.main;
          <span class="hljs-keyword">const</span> place = data.name;
          <span class="hljs-keyword">const</span> { description, icon } = data.weather[<span class="hljs-number">0</span>];
          <span class="hljs-keyword">const</span> { sunrise, sunset } = data.sys;
        });
    });
  }
</code></pre>
<p>So, after getting the data in JSON format, we extract the values that we are going to use. If you console log the data now, you'll be able to see we are getting all the data that was previously shown through the base URL. We are extracting the <code>temp</code> from the <code>main</code> object and storing it into a variable of the same name <code>temp</code>. We are getting the name of the place from the <code>name</code> key of the object. The description and icon code is available in the <code>weather</code> array inside the object. We only have one array. So, we are accessing that array to get the two values. And finally, the <code>sys</code> object stores the sunrise and sunset time. We are also storing them into variables of the same name. If you console log the different values now, you’ll be able to see it. But you might get confused about two things, the first one is the sunrise and sunset time and the second one is the icon. Let's first talk about the icon code. OpenWeatherMap provides icons depending on various weather conditions. And, to show the icons, it gives some icon code. Providing the icon code in a particular URL will return the image. You can see all the icons <a target="_blank" href="https://openweathermap.org/weather-conditions">here</a>. The icon URL is http://openweathermap.org/img/wn/${icon}@2x.png; if we replace the <code>${icon}</code> with the icon code, we'll get the icon according to the weather condition. Now, let's talk about time. The time that is returned by the API is in epoch format. So, to make it human-readable, we need to convert it to GMT time first. The formula to convert epoch time to GMT using JavaScript is,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> timeInGMT = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>(epochTime * <span class="hljs-number">1000</span>);
</code></pre>
<p>So, we are getting two different times that are to be converted into GMT. Let’s create two variables, one for the sunrise and the other one for the sunset time. And, let’s also create an icon URL that we will put inside the blank <code>img</code>tag that we created before. And one more thing that we have to do is, convert the Celcius to Fahrenheit because we want to show the temperature in both the degrees. To convert the celsius to Fahrenheit, we use the formula,</p>
<p><strong>fahrenheit = (celcius * 9) / 5 + 32</strong></p>
<p>Now our code will look something like this,</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">window</span>.addEventListener(<span class="hljs-string">'load'</span>, <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">let</span> long;
  <span class="hljs-keyword">let</span> lat;
  <span class="hljs-comment">// Accesing Geolocation of User</span>
  <span class="hljs-keyword">if</span> (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(<span class="hljs-function">(<span class="hljs-params">position</span>) =&gt;</span> {
      <span class="hljs-comment">// Storing Longitude and Latitude in variables</span>
      long = position.coords.longitude;
      lat = position.coords.latitude;
      <span class="hljs-keyword">const</span> base = <span class="hljs-string">`https://api.openweathermap.org/data/2.5/weather?lat=<span class="hljs-subst">${lat}</span>&amp;lon=<span class="hljs-subst">${long}</span>&amp;appid=<span class="hljs-subst">${api}</span>&amp;units=metric`</span>;

      <span class="hljs-comment">// Using fetch to get data</span>
      fetch(base)
        .then(<span class="hljs-function">(<span class="hljs-params">response</span>) =&gt;</span> {
          <span class="hljs-keyword">return</span> response.json();
        })
        .then(<span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> {
          <span class="hljs-built_in">console</span>.log(data);
          <span class="hljs-keyword">const</span> { temp } = data.main;
          <span class="hljs-keyword">const</span> place = data.name;
          <span class="hljs-keyword">const</span> { description, icon } = data.weather[<span class="hljs-number">0</span>];
          <span class="hljs-keyword">const</span> { sunrise, sunset } = data.sys;

          <span class="hljs-keyword">const</span> iconUrl = <span class="hljs-string">`http://openweathermap.org/img/wn/<span class="hljs-subst">${icon}</span>@2x.png`</span>;
          <span class="hljs-keyword">const</span> fahrenheit = (temp * <span class="hljs-number">9</span>) / <span class="hljs-number">5</span> + <span class="hljs-number">32</span>;

          <span class="hljs-comment">// Converting Epoch(Unix) time to GMT</span>
          <span class="hljs-keyword">const</span> sunriseGMT = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>(sunrise * <span class="hljs-number">1000</span>);
          <span class="hljs-keyword">const</span> sunsetGMT = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>(sunset * <span class="hljs-number">1000</span>);
        });
    });
  }
});
</code></pre>
<p>And we are almost done. We have all the data that we need to show. The only thing that is left, is to access the DOM elements using JavaScript and changing the values. I am pasting the code for selecting the elements below. I think the code do not need any explanation.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> iconImg = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'weather-icon'</span>);
<span class="hljs-keyword">const</span> loc = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'#location'</span>);
<span class="hljs-keyword">const</span> tempC = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'.c'</span>);
<span class="hljs-keyword">const</span> tempF = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'.f'</span>);
<span class="hljs-keyword">const</span> desc = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'.desc'</span>);
<span class="hljs-keyword">const</span> sunriseDOM = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'.sunrise'</span>);
<span class="hljs-keyword">const</span> sunsetDOM = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'.sunset'</span>);
</code></pre>
<p>We are just accessing the DOM elements and storing them into separate variables. We are doing this outside the <code>eventListener</code> function.</p>
<p>Now, to change the src tag of an image, we access the image element using a selector, here we are selecting using the ID of <code>weather-icon</code>, now if we use the <code>.src</code> property over it, we can easily change the image source.</p>
<pre><code class="lang-javascript">iconImg.src = iconUrl;
</code></pre>
<p>We are changing the image URL with the icon URL that we stored before. Rest of the code is very simple.</p>
<pre><code class="lang-javascript">loc.textContent = <span class="hljs-string">`<span class="hljs-subst">${place}</span>`</span>;
desc.textContent = <span class="hljs-string">`<span class="hljs-subst">${description}</span>`</span>;
tempC.textContent = <span class="hljs-string">`<span class="hljs-subst">${temp.toFixed(<span class="hljs-number">2</span>)}</span> °C`</span>;
tempF.textContent = <span class="hljs-string">`<span class="hljs-subst">${fahrenheit.toFixed(<span class="hljs-number">2</span>)}</span> °F`</span>;
sunriseDOM.textContent = <span class="hljs-string">`<span class="hljs-subst">${sunriseGMT.toLocaleDateString()}</span>, <span class="hljs-subst">${sunriseGMT.toLocaleTimeString()}</span>`</span>;
sunsetDOM.textContent = <span class="hljs-string">`<span class="hljs-subst">${sunsetGMT.toLocaleDateString()}</span>, <span class="hljs-subst">${sunsetGMT.toLocaleTimeString()}</span>`</span>;
</code></pre>
<p>We are using template literals. The <code>toFixed(2)</code> method is used so that the degree shows up to two decimal places only. The <code>toLocaleDateString()</code> and <code>toLocaleTimeString()</code> methods are used to convert the GMT time and date to local time and date. The .<code>textContent</code> property sets the inside text with the values passed on the right side. And we are done. The complete JavaScript code will look like this,</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Openweathermap API. Do not share it publicly.</span>
<span class="hljs-keyword">const</span> api = <span class="hljs-string">'66869939e0b182ac2d6************'</span>; <span class="hljs-comment">//Replace with your API</span>

<span class="hljs-keyword">const</span> iconImg = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'weather-icon'</span>);
<span class="hljs-keyword">const</span> loc = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'#location'</span>);
<span class="hljs-keyword">const</span> tempC = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'.c'</span>);
<span class="hljs-keyword">const</span> tempF = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'.f'</span>);
<span class="hljs-keyword">const</span> desc = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'.desc'</span>);
<span class="hljs-keyword">const</span> sunriseDOM = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'.sunrise'</span>);
<span class="hljs-keyword">const</span> sunsetDOM = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'.sunset'</span>);

<span class="hljs-built_in">window</span>.addEventListener(<span class="hljs-string">'load'</span>, <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">let</span> long;
  <span class="hljs-keyword">let</span> lat;
  <span class="hljs-comment">// Accesing Geolocation of User</span>
  <span class="hljs-keyword">if</span> (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(<span class="hljs-function">(<span class="hljs-params">position</span>) =&gt;</span> {
      <span class="hljs-comment">// Storing Longitude and Latitude in variables</span>
      long = position.coords.longitude;
      lat = position.coords.latitude;
      <span class="hljs-keyword">const</span> base = <span class="hljs-string">`https://api.openweathermap.org/data/2.5/weather?lat=<span class="hljs-subst">${lat}</span>&amp;lon=<span class="hljs-subst">${long}</span>&amp;appid=<span class="hljs-subst">${api}</span>&amp;units=metric`</span>;

      <span class="hljs-comment">// Using fetch to get data</span>
      fetch(base)
        .then(<span class="hljs-function">(<span class="hljs-params">response</span>) =&gt;</span> {
          <span class="hljs-keyword">return</span> response.json();
        })
        .then(<span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> {
          <span class="hljs-keyword">const</span> { temp } = data.main;
          <span class="hljs-keyword">const</span> place = data.name;
          <span class="hljs-keyword">const</span> { description, icon } = data.weather[<span class="hljs-number">0</span>];
          <span class="hljs-keyword">const</span> { sunrise, sunset } = data.sys;

          <span class="hljs-keyword">const</span> iconUrl = <span class="hljs-string">`http://openweathermap.org/img/wn/<span class="hljs-subst">${icon}</span>@2x.png`</span>;
          <span class="hljs-keyword">const</span> fahrenheit = (temp * <span class="hljs-number">9</span>) / <span class="hljs-number">5</span> + <span class="hljs-number">32</span>;

          <span class="hljs-comment">// Converting Epoch(Unix) time to GMT</span>
          <span class="hljs-keyword">const</span> sunriseGMT = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>(sunrise * <span class="hljs-number">1000</span>);
          <span class="hljs-keyword">const</span> sunsetGMT = <span class="hljs-keyword">new</span> <span class="hljs-built_in">Date</span>(sunset * <span class="hljs-number">1000</span>);

          <span class="hljs-comment">// Interacting with DOM to show data</span>
          iconImg.src = iconUrl;
          loc.textContent = <span class="hljs-string">`<span class="hljs-subst">${place}</span>`</span>;
          desc.textContent = <span class="hljs-string">`<span class="hljs-subst">${description}</span>`</span>;
          tempC.textContent = <span class="hljs-string">`<span class="hljs-subst">${temp.toFixed(<span class="hljs-number">2</span>)}</span> °C`</span>;
          tempF.textContent = <span class="hljs-string">`<span class="hljs-subst">${fahrenheit.toFixed(<span class="hljs-number">2</span>)}</span> °F`</span>;
          sunriseDOM.textContent = <span class="hljs-string">`<span class="hljs-subst">${sunriseGMT.toLocaleDateString()}</span>, <span class="hljs-subst">${sunriseGMT.toLocaleTimeString()}</span>`</span>;
          sunsetDOM.textContent = <span class="hljs-string">`<span class="hljs-subst">${sunsetGMT.toLocaleDateString()}</span>, <span class="hljs-subst">${sunsetGMT.toLocaleTimeString()}</span>`</span>;
        });
    });
  }
});
</code></pre>
<p>The complete source code can be found in this Github <a target="_blank" href="https://github.com/nemo0/js-weather-app">repo</a>.</p>
<h1 id="conclusion">Conclusion</h1>
<p>This was our complete weather app from scratch. You can modify it with your styles and preference. This was an attempt to break all the pieces and explain them accordingly. I hope you find it helpful. If you want to build something more using APIs, we have another article about creating a Covid tracker using JavaScript - <a target="_blank" href="https://nemotivity.dev/create-a-javascript-covid-19-tracker-ckpm90f3d0qpyz0s177p25aft">Create a Javascript Covid 19 Tracker</a></p>
]]></content:encoded></item><item><title><![CDATA[A Guide to CSS Flexbox: Part II]]></title><description><![CDATA[The previous article covers the basics of CSS Flexbox, we’ve learned how to use the flexbox properties available in a flexbox parent. If you haven't read the article yet, I would highly encourage you to check that before moving to this one.
Our aim i...]]></description><link>https://blog.nemotivity.dev/a-guide-to-css-flexbox-part-ii</link><guid isPermaLink="true">https://blog.nemotivity.dev/a-guide-to-css-flexbox-part-ii</guid><category><![CDATA[CSS]]></category><category><![CDATA[CSS3]]></category><category><![CDATA[Frontend Development]]></category><category><![CDATA[flexbox]]></category><category><![CDATA[HTML5]]></category><dc:creator><![CDATA[Subha Chanda]]></dc:creator><pubDate>Tue, 22 Jun 2021 07:30:27 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1624346887472/D243YhkjR.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>The previous article covers the <a target="_blank" href="https://nemotivity.dev/a-guide-to-css-flexbox-part-i-ckpw5u9az0d8uzls1c35j3f4q">basics of CSS Flexbox</a>, we’ve learned how to use the <strong>flexbox properties</strong> available in a flexbox parent. If you haven't read the article yet, I would highly encourage you to check that before moving to this one.</p>
<p>Our aim in this article is to learn and apply the available properties to the flexbox items.</p>
<p>So, we've already discussed these properties before (In part 1 of this series - <a target="_blank" href="https://nemotivity.dev/a-guide-to-css-flexbox-part-i-ckpw5u9az0d8uzls1c35j3f4q">Basics of CSS Flexbox</a>):</p>
<ol>
<li>Flex container and flex item</li>
<li>Main axis and Cross axis</li>
<li>The <code>display:flex</code> property</li>
<li>Flex-wrap</li>
<li>Flex-direction</li>
<li>Flex-flow</li>
<li>Justify-content</li>
<li>Align-items</li>
<li>Align-content</li>
</ol>
<p>Let's start discussing the topics that are left.</p>
<h3 id="1-flex-order-property">1. <code>flex-order</code> Property:</h3>
<p>The flex-order property is used to define the order of the flex-items.</p>
<p>Here is the <strong>syntax</strong>:</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.flex-item</span> {
    <span class="hljs-attribute">order</span>: <span class="hljs-number">0</span> | -<span class="hljs-number">1</span> | <span class="hljs-number">4</span>;
}
</code></pre>
<p>The default value for all the items is <strong>zero</strong>. If we apply any value greater than zero to a <strong>flex-item</strong>, the flex-item will be <strong>pushed to the end of all the items</strong>. For example, if you look at the embed below, you'll find that the <strong>item-1</strong> class has an order of 4, pushing it to the end. And as you might have guessed, any value which is less than 0 will push the element to the first. The <strong>item-4</strong> class has a flex-order value of <strong>-1</strong>, which is pushing it to the first.</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://codepen.io/nemo011/pen/eYvaear">https://codepen.io/nemo011/pen/eYvaear</a></div>
<h3 id="2-flex-grow-property">2. <code>flex-grow</code> Property:</h3>
<p>The <code>flex-grow</code> property is used to make a flex-item grow if sufficient space is available in the parent container. The <code>flex-grow</code> takes a unitless value and uses it as a proportion.</p>
<p>Here is the <strong>syntax</strong>:</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.flex-item</span> {
    <span class="hljs-attribute">flex-grow</span>: <span class="hljs-number">2</span> | inherit | initial;
}
</code></pre>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://codepen.io/nemo011/pen/RwpmjzN">https://codepen.io/nemo011/pen/RwpmjzN</a></div>
<p>This property will specify how much available free space should be assigned to a flex item. There are few things to note when using the flex-grow.</p>
<p>It assigns the space open in the <strong>flex-container</strong> to the <strong>flex-items</strong>. And the proportion is determined by the number of <code>flex-grow</code> values we have in the flex-items.</p>
<p>For example, if we have a <code>flex-grow: 2;</code> value in the first item and a <code>flex-grow: 1;</code> value in the second item, flexbox will divide the total <strong>available space by 3</strong> and will <strong>add 2/3</strong> of the available space to the first item and 1/3 to the second item. The initial value will set its value to the default and will inherit the value from its parent.</p>
<p><img src="https://lh4.googleusercontent.com/0dH0WXYfDyOYH4dokqwmo5NuKYtQd82kGo5opG0GINRtATp1WCbcPqibYBfyBaiBaNQsqayVCSQy2KzRFxH346xkTLXFHkSsJQwAslapYH6PLnXHRM4CWHrhB-MNszMYXMpgvOR7" alt="CSS flexbos flex-grow property" /></p>
<h3 id="3-flexshrink-property">3. <code>flex:shrink</code> Property:</h3>
<p>This property is the opposite of the flex-grow property. It determines how much one element will shrink if necessary.</p>
<p>Here is the <strong>syntax</strong>:</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.flex-item</span> {
    <span class="hljs-attribute">flex-shrink</span>: <span class="hljs-number">2</span> | initial | inherit;
}
</code></pre>
<p>The <code>flex-shrink</code> property is not much used, and also, the calculation of flex-shrink is more complicated than flex-grow. We’ll not be discussing it in-depth in this article. For now, keep that in mind that the higher the shrink value, the more the item shrinks. To get an idea about it, open the below embed in fullscreen and resize it. You'll notice that the flex-item having flex-shrink value 2, shrinks more than the other items.</p>
<p>It also takes the <strong>initial</strong> and <strong>inherit</strong> values. The initial will set the value to default, and inherit will inherit the parent container value.</p>
<p>The <strong>default</strong> value of <code>flex-shrink</code> is <strong>1</strong>.</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://codepen.io/nemo011/pen/LYWoOKo">https://codepen.io/nemo011/pen/LYWoOKo</a></div>
<h3 id="4-flexbasis-property">4. <code>flex:basis</code> Property:</h3>
<p>Setting the <code>flex-basis</code> property is like setting an initial width to the items. So why don’t we use the min-width property? Because the <code>min-width</code> property will make our code non-responsive if we reach a smaller size than the size specified in min-width. Also, the browser first checks for the <code>flex-basis</code> property. If it's not available, then it starts searching for the width and calculates the <code>flex-basis</code> value, which we don't want. So, it is always a good idea to use the <code>flex-basis</code> property.</p>
<p>Here is the <strong>syntax</strong>:</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.flex-item</span> {
    <span class="hljs-attribute">flex-basis</span>: <span class="hljs-number">250px</span> | <span class="hljs-number">50%</span> | auto;
}
</code></pre>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://codepen.io/nemo011/pen/ExWzbqO">https://codepen.io/nemo011/pen/ExWzbqO</a></div>
<h3 id="5-the-flex-property">5. The <code>flex</code> Property:</h3>
<p>The <code>flex</code> property is the shorthand for the <code>flex-grow</code>, <code>flex-shrink</code>, and <code>flex-basis</code> property.</p>
<p>Here is the syntax:</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.flex-item</span> {
    <span class="hljs-attribute">flex</span>: flex-grow flex-shrink flex-basis;
}
</code></pre>
<p>The <strong>second and third parameters are optional</strong>. The default value of <code>flex</code> is <strong>0 1 auto</strong>. Because we know the default <code>flex-grow</code> value is <strong>0</strong>, the <code>flex-shrink</code> value is <strong>1</strong> and <code>flex-basis</code> is <strong>auto</strong>. However, we can set values according to our needs.</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://codepen.io/nemo011/pen/poempzp">https://codepen.io/nemo011/pen/poempzp</a></div>
<p>For example, in the above code, we set the <code>flex</code> value <strong>2 2 auto</strong> to the first flex item.</p>
<p>If you resize the output, you'll find that the first element is growing and shrinking more than the other items. At the same time, the second item is not at all shrinking because its flex-shrink value is set to zero. Try resizing the output to view it in action.</p>
<h3 id="6-align-self-property">6. <code>align-self</code> Property:</h3>
<p>The <code>align-self</code> property overrides the <code>align-items</code> property assigned on the flex-container. We use this to set up the alignment on individual items. To understand the <code>align-self</code> property, you must know the <code>align-items</code> property available in the flex-container (check the first part of the article). The <code>align-self</code> takes the same values that are used in align-items, i.e.,</p>
<ul>
<li>Flex-start</li>
<li>Flex-end</li>
<li>Center</li>
<li>Stretch</li>
<li>Baseline</li>
</ul>
<p>Here's the image from our previous article to help you understand the values,</p>
<p><img src="https://lh5.googleusercontent.com/nDgGvbX4R-OhS9iZC8XIFbZo5rd5WTkFC2pmEJgAjfctXrVgdlI7hkiCT6aVWTaz8GxfivtJOGomBNZVP6Eg5Z-k0t8eEQs3UPngpUU5UDAtYL3pWkxOieKefUFPCwVR2J4T4v7j" alt="CSS flexbox align-self property" /></p>
<p>I don't think I’ve to explain the values again here. Check out the code snippet, and you'll get an idea.</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://codepen.io/nemo011/pen/jOBoYOG">https://codepen.io/nemo011/pen/jOBoYOG</a></div>
<p>So this was all about properties that can be applied to the flex-items.</p>
<p>I hope you liked this two-part guide to the flexbox. Leave a comment if you have any doubts or suggestions. 😊
And, here is another <a target="_blank" href="https://nemotivity.dev/lets-talk-about-mathceil-mathfloor-and-mathround-cke5vz93f013r9ds14gri50db">article suggestion</a> for you. 😄</p>
]]></content:encoded></item><item><title><![CDATA[I Built My Own Mini ReadWise.io with Node.js and HarperDB]]></title><description><![CDATA[Introduction
For the Hashnode HarperDB hackathon, I built a Twitter thread saver. What does my Twitter saver do though? I should explain it first. Let me show you a demo:
https://youtu.be/sU0moS6Pask
As you can see from the above video, when a specif...]]></description><link>https://blog.nemotivity.dev/i-built-my-own-mini-readwiseio-with-nodejs-and-harperdb</link><guid isPermaLink="true">https://blog.nemotivity.dev/i-built-my-own-mini-readwiseio-with-nodejs-and-harperdb</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Vue.js]]></category><category><![CDATA[Open Source]]></category><category><![CDATA[HarperDB Hackathon]]></category><category><![CDATA[Node.js]]></category><dc:creator><![CDATA[Subha Chanda]]></dc:creator><pubDate>Fri, 18 Jun 2021 07:03:58 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1623999224739/pxaAUCB7C.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="introduction">Introduction</h1>
<p>For the Hashnode HarperDB hackathon, I built a Twitter thread saver. What does my Twitter saver do though? I should explain it first. Let me show you a demo:</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://youtu.be/sU0moS6Pask">https://youtu.be/sU0moS6Pask</a></div>
<p>As you can see from the above video, when a specific command is used on a Twitter thread, it gets saved to the database, and then it is rendered to the frontend site. Seems simple? You can check the frontend version <a target="_blank" href="https://www.threadsaver.xyz/">here</a>. And here are the repo links,</p>
<ul>
<li><a target="_blank" href="https://github.com/nemo0/thread-saver-backend">Backend GitHub repo</a></li>
<li><a target="_blank" href="https://github.com/nemo0/thread-saver-frontend">Frontend GitHub repo</a></li>
</ul>
<h1 id="inspiration-and-real-world-usage">🕊 Inspiration and Real-world Usage</h1>
<p>The Twitter tech community is awesome. People like <a target="_blank" href="https://twitter.com/jesss_codes">Jessica Carter</a>, <a target="_blank" href="https://twitter.com/Prathkum">Pratham</a>, @DThompsonDev, and many other developers share their awesome content through Twitter threads. I always wanted to build something using which I can save and read the threads later. This is how I got the idea of building a thread saver. It was a long time plan to building such a thing but I couldn't get started. The Hashnode HarperDB hackathon pushed me to start building it. Till now, the app is in, I should say, the alpha version. I have a lot of plans with this app which I'll talk about in this article.</p>
<h1 id="challenges">❌ Challenges</h1>
<p><img src="https://i.ibb.co/Df2GTHt/threadsaver.gif" alt /></p>
<p>At first, when I started researching, I found that <a target="_blank" href="https://readwise.io/">readwise.io</a> works the same and in a much better way. Readwise worked as an inspiration to me.</p>
<h3 id="challenge-1-choosing-what-i-need">Challenge 1: Choosing what I need</h3>
<p>Now that I got an idea about what I want to build, I needed to explore the Twitter API and needed to know which API functionalities I exactly need. The Twitter stream API seemed perfect for me. Because I work more with JavaScript, JavaScript was my first choice. But I am thinking of building the whole backend with Golang in the future. I chose the <a target="_blank" href="https://www.npmjs.com/package/twitter">twitter</a> npm library to talk with the API.</p>
<h3 id="challenge-2-writing-functions-to-achieve-what-i-need">Challenge 2: Writing functions to achieve what I need</h3>
<p>My main target was to save a whole thread to the database, but the Twitter API doesn't send back the whole thread to which the tweets are replied to, rather it sends only the parent tweet's ID to which a tweet is replied. And also, I needed to know what is the first tweet of a thread and what a reply is. After finding the parent tweet and a child tweet, I needed to write a recursive function(if you don't know what a recursive function is, check <a target="_blank" href="https://nemotivity.dev/an-introduction-to-recursion-using-javascript-ckfgx2nrq001xols17h787f87">this link</a> 😉) that could go from a last replied thread to the top until it reaches the parent. This was the toughest part for me. I got confused a lot, but somehow I managed to write the functions that I needed.</p>
<h3 id="challenge-3-connecting-the-database">Challenge 3: Connecting the Database</h3>
<p>I shouldn't say connecting a database was a real challenge. HarperDB was my choice here. It is effortless to use a HarperDB database. For the server-side, I used the <a target="_blank" href="https://www.npmjs.com/package/harperive">Harperive</a> npm package. I could have used the API with Axios also, but I used the package here to explore a little more. You can check the backend repo <a target="_blank" href="https://github.com/nemo0/thread-saver-backend">here</a>.</p>
<h3 id="challenge-4-deploying">Challenge 4: Deploying</h3>
<p>I am still a student and I don't have any credit card. I love deploying to Heroku, but because I need an always on server so that I can listen to the streaming data, I needed to use a VPS. I used Vultr for it. Learned a little bit of docker, but finally deployed without Docker to a Vultr linux server. It was also challenging for me to deploy to a VPS.</p>
<h3 id="challenge-5-frontend">Challenge 5: Frontend</h3>
<p><img src="https://i.ibb.co/9t9hnRg/de49605b-7529-45d3-a7d1-5b15d73b9098.png" alt /></p>
<p>I prefer to work with pure JavaScript, but I choose Vue for the frontend for this project. I converted a complete HTML repo to a Vue repo. This was also not a challenge, to be honest. Though, few small places took a very long time. I used the HarperDB API with Axios here and used NoSQL queries. One problem with the HarperDB NoSQL query is, I cannot retrieve sorted data based on a specific field. Though it can be achieved in the front end, for now, it's on my to-do list. You can view the working frontend at <a target="_blank" href="http://threadsaver.xyz">threadsaver.xyz</a> and the repo are <a target="_blank" href="https://github.com/nemo0/thread-saver-frontend">here</a>.</p>
<h1 id="future-roadmap">🛣 Future Roadmap</h1>
<ul>
<li>The app currently lacks one of the most important features, when a thread is saved, the user should be notified either by DM or by a thread reply. Currently, I am working to solve this. This is on my top priority list now.</li>
<li>Getting data sorted by time is another important thing that I need to implement</li>
<li>The authentication is not yet implemented on the client-side for this Hackathon so that everyone can view the app. As the hackathon ends, I'll add the authentication service. And after adding authentication, I'll add the option to delete a specific tweet</li>
<li>The second thing I need to implement is to add OAuth so that the user doesn't have to do anything manually. They just give permission to the app and they are ready to go. In this version, I also want to implement a functionality to set up custom commands.</li>
<li>The UI needs more work.
<img src="https://i.ibb.co/jRVryPk/ad56a2c5-3767-43f5-a707-fb609350c146.png" alt /></li>
<li>Tag adding for threads is another important feature that I need to implement.</li>
</ul>
<h1 id="tech-stack">💻 Tech Stack</h1>
<ul>
<li><strong>Backend:</strong> Node.js, deployed to a linux VPS(<a target="_blank" href="https://github.com/nemo0/thread-saver-backend">repo</a>)</li>
<li><strong>Frontend:</strong> Vue.js, deployed to Vercel(<a target="_blank" href="https://github.com/nemo0/thread-saver-frontend">repo</a>)</li>
</ul>
<h1 id="conclusion">🎋 Conclusion</h1>
<p>During building this app, I learned a lot about how APIs work, more about asynchronous functions, working with Axios and VPS, and a lot more. I thank Hashnode and HarperDB for giving this push and opportunity to work on side projects.</p>
]]></content:encoded></item><item><title><![CDATA[A Guide to CSS Flexbox: Part I]]></title><description><![CDATA[CSS flexbox gives the ability to format HTML pages more efficiently. It provides complete control over the alignment, direction, order and box sizes. Before the CSS flexbox came into existence, we had floats. Floats allowed us to control only the hor...]]></description><link>https://blog.nemotivity.dev/a-guide-to-css-flexbox-part-i</link><guid isPermaLink="true">https://blog.nemotivity.dev/a-guide-to-css-flexbox-part-i</guid><category><![CDATA[HTML5]]></category><category><![CDATA[CSS]]></category><category><![CDATA[flexbox]]></category><category><![CDATA[Frontend Development]]></category><dc:creator><![CDATA[Subha Chanda]]></dc:creator><pubDate>Mon, 14 Jun 2021 05:12:47 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1623646356576/12npI0Phx.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>CSS flexbox gives the ability to format HTML pages more efficiently. It provides complete control over the alignment, direction, order and box sizes. Before the CSS flexbox came into existence, we had floats. Floats allowed us to control only the horizontal position of the items. As the browser support of flexbox has been increased, you are most likely to use them while working with CSS.</p>
<p><img src="https://lh5.googleusercontent.com/emyzlW3oKXkpF_ijzh2C5RQw4EU4IxsBRS-RWXuge--YIx0Fne8jwaYHiwfwq89cZwOgibURRNt4Dh0mi_LXnnk81UsPE-iTmIvJNwFMUSWu0CJOxQId68lYE9PJVc4IBRwLWOPd" alt="https://lh5.googleusercontent.com/emyzlW3oKXkpF_ijzh2C5RQw4EU4IxsBRS-RWXuge--YIx0Fne8jwaYHiwfwq89cZwOgibURRNt4Dh0mi_LXnnk81UsPE-iTmIvJNwFMUSWu0CJOxQId68lYE9PJVc4IBRwLWOPd" /></p>
<p>Floats were tough. Even a simple header menu would need a lot of work. At the same time, flexboxes are easy to learn and gives a lot more ability to format.</p>
<h2 id="flex-containers-and-flex-items">🎁 Flex Containers and Flex Items</h2>
<p>To start learning about flexboxes, we have to know about two things.</p>
<ol>
<li><strong>Flex Containers</strong></li>
<li><strong>Flex Items</strong></li>
</ol>
<p><img src="https://lh5.googleusercontent.com/b2fYFtzf6-u8tcWe7tysQHrUiCeG4yDi4xrl87SL0sLNqofDLr7LTRfyBukX9wCsW-r2UrZBDUZ1K_Df-lUtOpL6ZeFDOkv0jb30rzR5atR_Q4vNM3W__lvS9nam1RjSByW1vHXS" alt="https://lh5.googleusercontent.com/b2fYFtzf6-u8tcWe7tysQHrUiCeG4yDi4xrl87SL0sLNqofDLr7LTRfyBukX9wCsW-r2UrZBDUZ1K_Df-lUtOpL6ZeFDOkv0jb30rzR5atR_Q4vNM3W__lvS9nam1RjSByW1vHXS" /></p>
<p>You can get an idea about flex containers and flex items from the above image. The Flex container is used to <strong>group a bunch of flex items</strong>. And any HTML element that is a <strong>direct child of the flex container</strong> is a flex item. We use flex containers to determine the layout. However, the flex items can be manipulated individually also. Now, let's start to learn about the syntax of flexbox.</p>
<h1 id="flex-container-properties">👜 Flex Container Properties</h1>
<p>Following are some of the properties of the flex container.</p>
<h2 id="1-displayflex-property">⛳ <strong>1. <code>display:flex;</code> Property</strong></h2>
<p>The <code>display:flex;</code> is used to <strong>invoke the flexbox</strong>. This style goes inside the parent element or the flex container as we say here. When the browser sees this, it will render everything inside the container as a flexbox.</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.flex-container</span> {
    <span class="hljs-attribute">display</span>: flex;
}
</code></pre>
<p>Now, let's start experiencing the awesomeness of flexbox.</p>
<p>To start, we'll need an HTML file and a CSS file for styles. Let's say we have an HTML file called <strong>index.html</strong> and a CSS file called <strong>styles.css</strong>. We'll have a <code>div</code> called <strong>flex-container</strong>, and all the direct child elements of the flex-container will have a <code>div</code> of <strong>flex-item</strong>. So, our HTML file will look like this.</p>
<pre><code class="lang-html"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<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">link</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">"stylesheet"</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"./styles.css"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>CSS FLEXBOX<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">header</span>&gt;</span>
        <span class="hljs-comment">&lt;!-- Empty header tag --&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">header</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"flex-container"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"flex-item red"</span>&gt;</span>1<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"flex-item green"</span>&gt;</span>2<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"flex-item blue"</span>&gt;</span>3<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"flex-item yellow"</span>&gt;</span>4<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"flex-item pink"</span>&gt;</span>5<span class="hljs-tag">&lt;/<span class="hljs-name">div</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">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p>The classes <strong>red</strong>, <strong>green</strong>, <strong>blue</strong>, etc. are given to style the particular divs. Now, let's style the file.</p>
<pre><code class="lang-css">* {
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">0</span>;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">0</span>;
  <span class="hljs-attribute">box-sizing</span>: border-box;
}

<span class="hljs-selector-class">.flex-item</span> {
  <span class="hljs-attribute">height</span>: <span class="hljs-number">10vh</span>;
  <span class="hljs-attribute">width</span>: <span class="hljs-number">20%</span>;
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">5px</span>;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">5px</span>;
  <span class="hljs-attribute">font-size</span>: <span class="hljs-number">32px</span>;
}

<span class="hljs-selector-class">.red</span> {
  <span class="hljs-attribute">background-color</span>: red;
  <span class="hljs-attribute">color</span>: white;
}

<span class="hljs-selector-class">.green</span> {
  <span class="hljs-attribute">background-color</span>: green;
  <span class="hljs-attribute">color</span>: white;
}

<span class="hljs-selector-class">.blue</span> {
  <span class="hljs-attribute">background-color</span>: blue;
  <span class="hljs-attribute">color</span>: white;
}

<span class="hljs-selector-class">.yellow</span> {
  <span class="hljs-attribute">background-color</span>: yellow;
  <span class="hljs-attribute">color</span>: black;
}

<span class="hljs-selector-class">.pink</span> {
  <span class="hljs-attribute">background-color</span>: pink;
  <span class="hljs-attribute">color</span>: black;
}
</code></pre>
<p>Here's our <strong>styles.css</strong> file. We are giving each of the flex items a <strong>height of 10 viewports</strong> and width of <strong>20% of the parent</strong>. So, up until now, the output of our code will be like the below image,</p>
<p><img src="https://lh4.googleusercontent.com/2t_ohqdiXnp3-6psk8CXKS8ajFUT7MvAxR8-XlWGFspOWHyBsoYsefUsvZNQHQ2yoC6u4_ZdDKTNk7ZIVI3Vm3X_c_p2bF7besgm3Rrwzr_ukJyY4oNY8ATzNNk3lLXCqJJZPS7Z" alt="https://lh4.googleusercontent.com/2t_ohqdiXnp3-6psk8CXKS8ajFUT7MvAxR8-XlWGFspOWHyBsoYsefUsvZNQHQ2yoC6u4_ZdDKTNk7ZIVI3Vm3X_c_p2bF7besgm3Rrwzr_ukJyY4oNY8ATzNNk3lLXCqJJZPS7Z" /></p>
<p>This output is what we were expecting.</p>
<p>Now if we want all this flex items to <strong>align horizontally</strong> using floats, we'll need a lot of work. But using flexbox, aligning the items horizontally is just a single line of code. Adding the <code>display:flex</code> property to the parent will do the magic.</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.flex-container</span> {
    <span class="hljs-attribute">display</span>: flex;
}
</code></pre>
<p>The above line will give us the output,</p>
<p><img src="https://lh6.googleusercontent.com/_xbqAHU5QEyB8iZRPGifeQo3wzXYaGPRdabkybqgZid53pL1KX2pSxJEajQEW1sU23A3L5KBOSDXoK_vEKxzr8qhRA5z703X2WVTMsSvkDhic6P-Z3h7H8fyg0cyHNE5SVVd5EcE" alt="https://lh6.googleusercontent.com/_xbqAHU5QEyB8iZRPGifeQo3wzXYaGPRdabkybqgZid53pL1KX2pSxJEajQEW1sU23A3L5KBOSDXoK_vEKxzr8qhRA5z703X2WVTMsSvkDhic6P-Z3h7H8fyg0cyHNE5SVVd5EcE" /></p>
<p>Isn't it awesome?</p>
<h2 id="2-flex-wrap-property">🥅 <strong>2. <code>flex-wrap</code> Property</strong></h2>
<p>The <code>flex-wrap</code> property has three options to choose from:</p>
<ul>
<li><code>nowrap</code></li>
<li><code>wrap</code></li>
<li><code>wrap-reverse</code></li>
</ul>
<p>The default property is <strong>nowrap</strong>. If you have ever used Microsoft Excel, then you must know what I am talking about.</p>
<p>The <strong>wrap</strong> option will add the elements to a new line if it crosses its total width available to it. For example, our flex items have a 20% width plus some margins. So technically, only four flex-items should align in a single line. But our output sets all the five items in a single line. Because by default it is set to nowrap.</p>
<p>The width we assigned here works like a <code>max-width</code>. Now, suppose we set the <code>flex-wrap</code> property to <strong>wrap</strong>. In that case, it'll take the width size given to the items and only align the maximum number of elements that can be added. And finally, the <strong>wrap-reverse</strong> property value will wrap all the items in reverse order.</p>
<p><strong>Here is the syntax:</strong></p>
<pre><code class="lang-css"><span class="hljs-comment">/* Assuming .flex-container is the Parent Container */</span>
<span class="hljs-selector-class">.flex-container</span> {
  <span class="hljs-attribute">display</span>: flex;
  <span class="hljs-attribute">flex-wrap</span>: nowrap | wrap | wrap-reverse;
}
</code></pre>
<p>You can see how the properties affect the style from the GIF below:</p>
<p><img src="https://lh3.googleusercontent.com/-BUG9TztXnhG44S3GR5pfBFj47vZlC_ry97c7FXTevU4RfmVHXZnf6i2Tj-seG3evOpa4JJSLrAV9EgbunfLv2KFyq4MYyOMDVdq3yqUiISl2sd3B2B43prMv2WxKOsPAVoqy_4A" alt="https://lh3.googleusercontent.com/-BUG9TztXnhG44S3GR5pfBFj47vZlC_ry97c7FXTevU4RfmVHXZnf6i2Tj-seG3evOpa4JJSLrAV9EgbunfLv2KFyq4MYyOMDVdq3yqUiISl2sd3B2B43prMv2WxKOsPAVoqy_4A" /></p>
<h2 id="3-flex-direction-property">🃏 <strong>3. <code>flex-direction</code> Property</strong></h2>
<p>As you can see, adding the <code>display:flex</code> property will align all our flex-items horizontally. But what if we don't want to align them in such a way? To control the alignment, we have the <code>flex-direction</code> property. This has four different options:</p>
<ol>
<li><strong>row</strong></li>
<li><strong>row-reverse</strong></li>
<li><strong>column</strong></li>
<li><strong>column-reverse</strong></li>
</ol>
<p>The default is the <strong>row</strong>. If we set it to <strong>column</strong>, our flex items will be aligned vertically. The <strong>row-reverse</strong> option will set the direction opposite to the text-direction.</p>
<p><strong>Here is the syntax:</strong></p>
<pre><code class="lang-css"><span class="hljs-comment">/* Assuming .flex-container is the Parent Container */</span>
<span class="hljs-selector-class">.flex-container</span> {
  <span class="hljs-attribute">display</span>: flex;
  <span class="hljs-attribute">flex-direction</span>: row | row-reverse | column | column-reverse;
}
</code></pre>
<p>Check the GIF to get some more idea about it.</p>
<p><img src="https://lh4.googleusercontent.com/kws5_jHc5ylKOaKeuVXmFytBxB4wcoroILH88NcFaag6_MLZXOj3kfhlYvet3uaJBokfPrcG88HW4MXc-2KDcM2K9BQSpRge7BaX2REX5KItQuucHDDU8oJLG76IebppwlTRjvnc" alt="https://lh4.googleusercontent.com/kws5_jHc5ylKOaKeuVXmFytBxB4wcoroILH88NcFaag6_MLZXOj3kfhlYvet3uaJBokfPrcG88HW4MXc-2KDcM2K9BQSpRge7BaX2REX5KItQuucHDDU8oJLG76IebppwlTRjvnc" /></p>
<p>Below we have a code example:</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://codepen.io/nemo011/pen/YzZRpVP">https://codepen.io/nemo011/pen/YzZRpVP</a></div>
<h2 id="4-flex-flow-property">🧩 <strong>4. <code>flex-flow</code> Property</strong></h2>
<p>This property is a shorthand for the <code>flex-wrap</code> and <code>flex-direction</code> together. Now we have an idea about both the properties. In <code>flex-flow</code>, we describe the <strong>direction of the flex</strong> and the <strong>wrapping in a single line</strong>, like, <code>flex-flow: wrap column-reverse;</code> This will wrap our flexbox and will align the flex-items in the row-reverse order.</p>
<p><strong>Let's take an example:</strong></p>
<pre><code class="lang-css"><span class="hljs-comment">/* Assuming .flex-container is the Parent Container */</span>
<span class="hljs-selector-class">.flex-container</span> {
  <span class="hljs-attribute">display</span>: flex;
  <span class="hljs-attribute">flex-flow</span>: row wrap;
}
</code></pre>
<h2 id="5-justify-content-property">⚗ <strong>5. <code>justify-content</code> Property</strong></h2>
<p>To understand the <code>justify-content</code> property, first, we have to understand some terminologies that are connected to flexbox. Consider the image below:</p>
<p><img src="https://lh5.googleusercontent.com/vz6uey5WXlH3TOp46P4Q0jOE8ZPZphyJkn32br3b_JVRDvDObKNlAJXYeHoD8Gn1_V4D9_Kd5mSzLFPKEnkPb6a87Xsr9CvkLt-I6_qR6BL0QDp3RGrvWe0DFOIyKrNvZLaZmRoI" alt="https://lh5.googleusercontent.com/vz6uey5WXlH3TOp46P4Q0jOE8ZPZphyJkn32br3b_JVRDvDObKNlAJXYeHoD8Gn1_V4D9_Kd5mSzLFPKEnkPb6a87Xsr9CvkLt-I6_qR6BL0QDp3RGrvWe0DFOIyKrNvZLaZmRoI" /></p>
<ul>
<li><strong>Main Axis</strong>: It is the <strong>primary axis</strong> through which all the flex-items are laid off. It does not have to be horizontal always. It depends on the flex-direction property.</li>
<li><strong>Cross Axis:</strong> It is the <strong>axis perpendicular to the main axis</strong>. So, if the main axis is the X-axis(<code>flex-direction:row</code>) then it'll be the Y-axis and vice-versa.</li>
</ul>
<p>Now, let's come back to the <code>justify-content</code> property again. This property <strong>specifies the alignment along the main axis</strong>. We mostly use these properties with justify-content:</p>
<ol>
<li><strong>Flex-start:</strong> Items are packed to the start of the main axis.</li>
<li><strong>Center</strong>: Items are packed to the center of the main axis.</li>
<li><strong>Flex-end:</strong> Items are packed flush to the end of the main-axis</li>
<li><strong>Space-between:</strong> The first item is packed to the start of the main axis; the end item is packed to the end of the main axis. The spacing between the pairs of each adjacent elements is the same.</li>
<li><strong>Space-around:</strong> The flex-items are evenly distributed along the main-axis. The spacing between each adjacent elements is the same. But the space before the first item and after the last item is half of the spacing between each of the elements.</li>
<li><strong>Space-evenly:</strong> The spacing between all the adjacent elements and space before the first item and after the last item all are same. All the spacings are evenly distributed here.</li>
</ol>
<p>The images below show the alignment properties and how the elements align according to the values:</p>
<p><img src="https://lh3.googleusercontent.com/JLHEmc9WJGECMRBsjtnywIWBjMVhIxryQGWx5L2wn2U1pF0IvJ0yiQiUnFq67K16yJ0Iew_c2O4lmr8JfU4JvKgI6D6yoIwIYA3rRMmSRTB6oGuvZ0g9hKm0Gh2CH6Mh6dssbCKw" alt="https://lh3.googleusercontent.com/JLHEmc9WJGECMRBsjtnywIWBjMVhIxryQGWx5L2wn2U1pF0IvJ0yiQiUnFq67K16yJ0Iew_c2O4lmr8JfU4JvKgI6D6yoIwIYA3rRMmSRTB6oGuvZ0g9hKm0Gh2CH6Mh6dssbCKw" /></p>
<p>And the next three,</p>
<p><img src="https://lh5.googleusercontent.com/RhRT29d9l0OpWhttKrZ5lMhizxL_7zWh4J6EVuNusuxrKHXn5oj8vaN92AtQS4CYJ7dkFFvhXro-m1MIsn8N0MuCN9aglneNGYjohjYtMkd7CTznnh6Q2sVJxLnoXkdtWBJYs0_S" alt="https://lh5.googleusercontent.com/RhRT29d9l0OpWhttKrZ5lMhizxL_7zWh4J6EVuNusuxrKHXn5oj8vaN92AtQS4CYJ7dkFFvhXro-m1MIsn8N0MuCN9aglneNGYjohjYtMkd7CTznnh6Q2sVJxLnoXkdtWBJYs0_S" /></p>
<p><strong>Here is the syntax:</strong></p>
<pre><code class="lang-css"><span class="hljs-comment">/* Assuming .flex-container is the Parent Container */</span>
<span class="hljs-selector-class">.flex-container</span> {
  <span class="hljs-attribute">display</span>: flex;
  <span class="hljs-attribute">justify-content</span>: flex-start | flex-end | center | space-around | space-between | space-evenly;
}
</code></pre>
<p>Here, in this GIF, you can see how the flex-items change depending on the justify-content property.</p>
<p><img src="https://lh6.googleusercontent.com/lMFuSzGm_f7XGei1zp3HQSDPzjoyIbWslObvErbaJicDn1vdQOAml72pSks6zJpLZOKsAPaWk2_qIh7ro6VBJ_tzZ19-pM5Ra5tGEzxs_r21p_M2EUJxy7qc9VYU8SOmL1aurJ1W" alt="https://lh6.googleusercontent.com/lMFuSzGm_f7XGei1zp3HQSDPzjoyIbWslObvErbaJicDn1vdQOAml72pSks6zJpLZOKsAPaWk2_qIh7ro6VBJ_tzZ19-pM5Ra5tGEzxs_r21p_M2EUJxy7qc9VYU8SOmL1aurJ1W" /></p>
<p>You can also play with this CSS property in the below live HTML/CSS editor:</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://codepen.io/nemo011/pen/rNyQWwq">https://codepen.io/nemo011/pen/rNyQWwq</a></div>
<h2 id="6-align-items-property">📖 <strong>6. <code>align-items</code> Property</strong></h2>
<p>We have seen that the <code>justify-content</code> property helps us to <strong>align items in the main axis</strong>. To <strong>align items in the cross-axis</strong>, we have to use the <code>align-items</code> property. Usually, we use the below values with align-items:</p>
<ol>
<li><p><strong>Flex-start:</strong> Aligns the items to the start of the cross axis.</p>
</li>
<li><p><strong>Flex-end:</strong> Aligns the items to the end of the cross axis.</p>
</li>
<li><p><strong>Center:</strong> Aligns the items to the center of the cross axis.</p>
</li>
<li><p><strong>Stretch:</strong> Stretches the items to fill the container</p>
</li>
<li><p><strong>Baseline:</strong> The baseline will align the flex-items to the baseline of the content. If you are confused about what actually baseline is, <a target="_blank" href="https://en.wikipedia.org/wiki/Baseline_(typography">wikipedia</a>) describes it as, “<em>The line upon which most letters "sit" and below which descenders extend.</em>” The below image from Wikipedia will clear about it more.</p>
<p><img src="https://lh6.googleusercontent.com/QbKd30l2_fMhh6wtCpBcNQk4rmzkxfbsJSM8n4xvl4c7NWcCi9PMt1SAyCclU_fa2aIP3VXmWII0-S3fUcQGX4R25NDBv_IgnELi7l8whdP0jkccuzqw15lxvEeqjf1zX_DF27TQ" alt="https://lh6.googleusercontent.com/QbKd30l2_fMhh6wtCpBcNQk4rmzkxfbsJSM8n4xvl4c7NWcCi9PMt1SAyCclU_fa2aIP3VXmWII0-S3fUcQGX4R25NDBv_IgnELi7l8whdP0jkccuzqw15lxvEeqjf1zX_DF27TQ" /></p>
</li>
</ol>
<p>Here is an image that pictorially explains the different values:</p>
<p><img src="https://lh5.googleusercontent.com/WH5vS42Lunra6GZz-QFXXng5bPP4kmPrh1vSXXe81N_rCmKs5bm7JwrUGuqLu0ZOF7pbrnMj_iCpER9oYuqPvh1y9KjB84acc1pEwxtexgnVIFvkl_nGrTTw3_oyruAUhmvcU28T" alt="https://lh5.googleusercontent.com/WH5vS42Lunra6GZz-QFXXng5bPP4kmPrh1vSXXe81N_rCmKs5bm7JwrUGuqLu0ZOF7pbrnMj_iCpER9oYuqPvh1y9KjB84acc1pEwxtexgnVIFvkl_nGrTTw3_oyruAUhmvcU28T" /></p>
<p><strong>Here is the syntax:</strong></p>
<pre><code class="lang-css"><span class="hljs-comment">/* Assuming .flex-container is the Parent Container */</span>
<span class="hljs-selector-class">.flex-container</span> {
  <span class="hljs-attribute">display</span>: flex;
  <span class="hljs-attribute">align-items</span>: flex-start | flex-end | baseline | stretch;
}
</code></pre>
<p>You can play with it here,</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://codepen.io/nemo011/pen/QWpJGMO">https://codepen.io/nemo011/pen/QWpJGMO</a></div>
<h2 id="7-align-content-property">🥏 <strong>7. <code>align-content</code> Property:</strong></h2>
<p>The <code>align-content</code> property <strong>sets and distributes the space between and around the flex-items</strong> along the cross axis of the flexbox. It works like the <code>justify-content</code> for the cross-axis. It'll only work if your container is set to <code>flex-wrap: wrap</code>.</p>
<p>The values that align-content property takes are:</p>
<ol>
<li><strong>Flex-start:</strong> Aligns items to the start of the cross-axis of the container.</li>
<li><strong>Flex-end:</strong> Align items to the end of the cross-axis.</li>
<li><strong>Center:</strong> Align items to the center of the cross-axis.</li>
<li><strong>Stretch:</strong> Stretches or takes the full space for the flex items.</li>
<li><strong>Space-between:</strong> Spaces are evenly distributed.</li>
<li><strong>Space-around:</strong> Items are evenly distributed between all the lines.</li>
</ol>
<p><img src="https://lh4.googleusercontent.com/wKzBsWMEcaiekbYeIteUFV21RHEY9i8FQN4NnICX6e8zUcVIxGHIa7G6S437rvkHospbvT-GeY2ORdYxgEdQwHBUPMtDonj78GiSuWs9Zglp6K8rOaegmvhRKaaTFLO2Gr1BbM6N" alt="https://lh4.googleusercontent.com/wKzBsWMEcaiekbYeIteUFV21RHEY9i8FQN4NnICX6e8zUcVIxGHIa7G6S437rvkHospbvT-GeY2ORdYxgEdQwHBUPMtDonj78GiSuWs9Zglp6K8rOaegmvhRKaaTFLO2Gr1BbM6N" /></p>
<p><strong>Here is the syntax:</strong></p>
<pre><code class="lang-css"><span class="hljs-comment">/* Assuming .flex-container is the Parent Container */</span>
<span class="hljs-selector-class">.flex-container</span> {
  <span class="hljs-attribute">display</span>: flex;
  <span class="hljs-attribute">align-content</span>: flex-start | flex-end | center | stretch | space-between |
    space-around;
}
</code></pre>
<p>In this article, we primarily discussed the flexbox properties that can be applied to a flexbox container. In the next article, we’ll discuss the properties that apply to the flexbox items. Until then, try practicing these properties and share your awesome codes with us.</p>
]]></content:encoded></item><item><title><![CDATA[Build a Piano App using JavaScript]]></title><description><![CDATA[In this tutorial, we will be building a piano using HTML, CSS, and JavaScript. This will be a great article to learn about some new stuff, like the HTML audio attribute and how we can use it in JavaScript. But, to start building this project, we’ve t...]]></description><link>https://blog.nemotivity.dev/build-a-piano-app-using-javascript</link><guid isPermaLink="true">https://blog.nemotivity.dev/build-a-piano-app-using-javascript</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[HTML5]]></category><category><![CDATA[HTML]]></category><category><![CDATA[CSS]]></category><category><![CDATA[side project]]></category><dc:creator><![CDATA[Subha Chanda]]></dc:creator><pubDate>Thu, 10 Jun 2021 05:01:02 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1623301094410/XURi_cvOQ.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In this tutorial, we will be building a piano using HTML, CSS, and JavaScript. This will be a great article to learn about some new stuff, like the HTML audio attribute and how we can use it in JavaScript. But, to start building this project, we’ve to know some basics like,</p>
<ul>
<li>Basic HTML</li>
<li>Basic CSS including CSS Flexbox</li>
<li>Basic JavaScript</li>
</ul>
<p>What will we learn in this tutorial?</p>
<ul>
<li>The HTML audio tag</li>
<li>The Data attribute</li>
<li>The <code>keydown</code> Event Listener</li>
<li>Adding Classes using JavaScript</li>
</ul>
<h1 id="the-html-part">👲 The HTML Part</h1>
<p>First, let's see the output of the piano.</p>
<p><img src="https://lh6.googleusercontent.com/hWpbwMSKdhOIIGhP7BNN8KBAKf3IsfasIvBLfoE2AVnX5I_AATfIMrVTqk6_K7cQ3ScrbUjHm7O7rddRfw86eRDsAzIa_VyPhCx5j2TuhT1TXLy9j4MZf86RJOF0iLwWFT02v3rm" alt="Javascript Piano App" /></p>
<p><a target="_blank" href="https://nemo0.github.io/js-piano/">Here</a> is the live version of it. Try it before jumping into the article.</p>
<p>As you can see, the piano will have different black and white keys. The white keys represent the seven notes of a piano(<strong>A-B-C-D-E-F-G</strong>), and the black keys will represent the sharp or flat notes. Also, for the background, we'll be using linear gradients. Our HTML is very simple. We'll have an individual <code>divs</code> for every piano key. Our piano consists of 12 keys. So, we will add twelve <code>div</code> wrapped into a parent <code>div</code>. Each <code>div</code> will have a unique <code>data</code> attribute. The <code>data</code> attributes will be used to map the <code>div</code> with their audio. Also, our piano keys will have styles according to the key type. The black keys will have an extra <strong>class</strong> <code>black</code>, and the white keys will have an extra <strong>class</strong> <code>white</code>. Other than that, all the <code>div</code> for the keys will have a class called <code>key</code>. And, all the keys will be finally wrapped into a <code>div</code> called <code>piano</code>.</p>
<p>Here's our HTML</p>
<pre><code class="lang-html"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<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>Piano<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">class</span>=<span class="hljs-string">"piano"</span>&gt;</span> 
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"key white"</span> <span class="hljs-attr">data-note</span>=<span class="hljs-string">"C"</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">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"key black"</span> <span class="hljs-attr">data-note</span>=<span class="hljs-string">"Cs"</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">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"key white"</span> <span class="hljs-attr">data-note</span>=<span class="hljs-string">"D"</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">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"key black"</span> <span class="hljs-attr">data-note</span>=<span class="hljs-string">"Ds"</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">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"key white"</span> <span class="hljs-attr">data-note</span>=<span class="hljs-string">"E"</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">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"key white"</span> <span class="hljs-attr">data-note</span>=<span class="hljs-string">"F"</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">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"key black"</span> <span class="hljs-attr">data-note</span>=<span class="hljs-string">"Fs"</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">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"key white"</span> <span class="hljs-attr">data-note</span>=<span class="hljs-string">"G"</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">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"key black"</span> <span class="hljs-attr">data-note</span>=<span class="hljs-string">"Gs"</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">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"key white"</span> <span class="hljs-attr">data-note</span>=<span class="hljs-string">"A"</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">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"key black"</span> <span class="hljs-attr">data-note</span>=<span class="hljs-string">"As"</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">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"key white"</span> <span class="hljs-attr">data-note</span>=<span class="hljs-string">"B"</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">div</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>
</code></pre>
<h1 id="the-data-attribute-in-javascript">🎩 The data Attribute in JavaScript</h1>
<p>The <code>data</code> attribute in HTML5 helps us to store some extra information without any extra work. Any attribute, whose attribute name starts with <code>data-</code> is a <code>data attribute</code>. So, for our piano, we are storing some extra data called <code>note</code> with the help of the <code>data</code> attribute in each of the <code>div</code>. For example, in the first div the <code>data-note="C"</code> stores a piece of information that this key will represent the <strong>C</strong> note in our piano. The data attributes can be easily targeted in JavaScript using the <code>dataset</code> keyword. We will discuss it more later in this article. To know more about the data attribute, visit the link <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes">here</a>.</p>
<h1 id="styling-the-piano">🎄 Styling the Piano</h1>
<p>The first step of styling an HTML page is to reset the default styles. Here also, we are resetting the <strong>margin</strong> and <strong>padding</strong> by targeting the global selector. We are also adding <code>box-sizing: border-box</code> because it'll help us to work with flexbox easily.</p>
<pre><code class="lang-css">* {
    <span class="hljs-attribute">margin</span>: <span class="hljs-number">0</span>;
    <span class="hljs-attribute">padding</span>: <span class="hljs-number">0</span>;
    <span class="hljs-attribute">box-sizing</span>: border-box;
}
</code></pre>
<p>For the background, we'll add a linear gradient. To speed up the process, I've used an online gradient generator called <a target="_blank" href="https://cssgradient.io/">CSS Gradient</a>. Here's our body.</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">body</span> {
    <span class="hljs-attribute">background</span>: <span class="hljs-number">#0f2027</span>;
    <span class="hljs-comment">/* fallback for old browsers */</span>
    <span class="hljs-attribute">background</span>: <span class="hljs-built_in">-webkit-linear-gradient</span>(to bottom, #<span class="hljs-number">2</span>c5364, #<span class="hljs-number">203</span>a43, #<span class="hljs-number">0</span>f2027);
    <span class="hljs-comment">/* Chrome 10-25, Safari 5.1-6 */</span>
    <span class="hljs-attribute">background</span>: <span class="hljs-built_in">linear-gradient</span>(to bottom, #<span class="hljs-number">2</span>c5364, #<span class="hljs-number">203</span>a43, #<span class="hljs-number">0</span>f2027);
    <span class="hljs-comment">/* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */</span>
}
</code></pre>
<p>Now, comes the tough part, styling the keys of the piano. First of all, let's add a <strong>height</strong> and a <strong>width</strong> for the piano. Because we'll be using flexbox, our flexbox will also be invoked here.</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.piano</span> {
    <span class="hljs-attribute">height</span>: <span class="hljs-number">100vh</span>;
    <span class="hljs-attribute">width</span>: <span class="hljs-number">100%</span>;
    <span class="hljs-attribute">display</span>: flex;
    <span class="hljs-attribute">justify-content</span>: center;
}
</code></pre>
<h2 id="styling-the-white-keys">🎹 Styling the White Keys</h2>
<p>The first thing to style the keys is to give them a height and a width. Otherwise, our keys will not be visible at all. We'll also need a border for each element to separate one from the other.</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.white</span> {
    <span class="hljs-attribute">width</span>: <span class="hljs-number">9%</span>;
    <span class="hljs-attribute">min-width</span>: <span class="hljs-number">60px</span>;
    <span class="hljs-attribute">height</span>: <span class="hljs-number">70%</span>;
    <span class="hljs-attribute">background-color</span>: white;
    <span class="hljs-attribute">border</span>: <span class="hljs-number">1px</span> solid <span class="hljs-number">#ccc</span>;
}
</code></pre>
<p>We are giving the white keys a width of <strong>9% of the parent</strong> and a height of <strong>70% of the parent</strong>. We are also adding a <code>min-height</code> property so that our keys don't become too small. Our white keys will have a <strong>background color of white</strong> and a <strong>solid border of 1px</strong>. The border color will be <code>#CCCCCC</code>, which is a darker shade of white. Here's the output of our piano until now,</p>
<p><img src="https://lh5.googleusercontent.com/rYEUL_VO_Fg_qkWI8sOQle41WI6d2O1wXGV75VTKSUk08LTCBjxtuKryP3heiPKTWvU98cxJ0PRRm1NGScvIbd_G0dTa4xfSMK5O8ZUcORNgXn2ZvyVIi4Qt4nGndJVr57AtTTBV" alt="create a piano app with javascript" /></p>
<h2 id="styling-the-black-keys">🎹 Styling the Black Keys</h2>
<p>The styling of the black keys is very similar to the white keys. The main difference is that the height of the black keys is smaller than the white keys.</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.black</span> {
    <span class="hljs-attribute">width</span>: <span class="hljs-number">8%</span>;
    <span class="hljs-attribute">height</span>: <span class="hljs-number">45%</span>;
    <span class="hljs-attribute">background-color</span>: black;
}
</code></pre>
<p>We are giving it a width of <strong>8% of the parent</strong>, a <strong>height of 45%</strong> of the parent and background color of <strong>black</strong>.</p>
<p>Here's the output after adding the black keys,</p>
<p><img src="https://lh4.googleusercontent.com/W9G3CjONJubfqp-lXhiVNj995LGBfZoVyQFn-jlWL4CBV-qO3TGOkHamgfcdWqP-la__XGpy3vxdwJU5a5A_2X92GHOS8nKhSfBzVZHje_9N_D8G4X68LTc2wbZLY9KWaWOGvfoH" alt="create piano app with javascript" /></p>
<p>This doesn't look like the one we want. How do we bring the black keys on top of the white ones? The easiest idea is to add some negative margins. Because our black keys have a width of 8%, we need to distribute it equally on two white keys. For that, we’ll add a -4% of left margin and a -4% of the right margin. We’ll also need to add a z-index to bring it forward. So, our complete style for the black keys will look like this,</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.black</span> {
    <span class="hljs-attribute">width</span>: <span class="hljs-number">8%</span>;
    <span class="hljs-attribute">height</span>: <span class="hljs-number">45%</span>;
    <span class="hljs-attribute">margin-left</span>: -<span class="hljs-number">4%</span>;
    <span class="hljs-attribute">margin-right</span>: -<span class="hljs-number">4%</span>;
    <span class="hljs-attribute">z-index</span>: <span class="hljs-number">2</span>;
    <span class="hljs-attribute">background-color</span>: black;
}
</code></pre>
<p>Now our piano will look similar to the one we wanted.</p>
<h1 id="the-audio-tag">🎵 The Audio Tag</h1>
<p>We have not added one important portion in our HTML document till now. We need to add <code>audio</code> tags for each key into the HTML element.</p>
<p>The HTML <code>audio</code> tag is used to embed sound into webpages. The <code>src</code> attribute into the <code>audio</code> tag will represent the source of the audio. In the Github <a target="_blank" href="https://github.com/nemo0/js-piano">repo</a> of this project, you will see that we have a folder called <strong>notes</strong>, inside the notes folder, we have all the <strong>mp3 sounds</strong> of the individual keys that we are going to use for this tutorial. Our audio <code>src</code> attribute will refer to the location of these sources. Each of the <code>audio</code> tag will also have a unique <code>ID</code> to determine the individual keys. Here's the remaining HTML part:</p>
<pre><code class="lang-markup">&lt;audio src="./notes/C4.mp3" id="C"&gt;&lt;/audio&gt;
&lt;audio src="./notes/Cs4.mp3" id="Cs"&gt;&lt;/audio&gt;
&lt;audio src="./notes/D4.mp3" id="D"&gt;&lt;/audio&gt;
&lt;audio src="./notes/Ds4.mp3" id="Ds"&gt;&lt;/audio&gt;
&lt;audio src="./notes/E4.mp3" id="E"&gt;&lt;/audio&gt;
&lt;audio src="./notes/F4.mp3" id="F"&gt;&lt;/audio&gt;
&lt;audio src="./notes/Fs4.mp3" id="Fs"&gt;&lt;/audio&gt;
&lt;audio src="./notes/G4.mp3" id="G"&gt;&lt;/audio&gt;
&lt;audio src="./notes/Gs4.mp3" id="Gs"&gt;&lt;/audio&gt;
&lt;audio src="./notes/A4.mp3" id="A"&gt;&lt;/audio&gt;
&lt;audio src="./notes/As4.mp3" id="As"&gt;&lt;/audio&gt;
&lt;audio src="./notes/B4.mp3" id="B"&gt;&lt;/audio&gt;
</code></pre>
<p>Our notes folder has more notes. But for this tutorial, we are only using standard piano keys(C4 to B4).</p>
<h1 id="putting-the-parts-together-with-javascript">🧵 Putting the Parts together with JavaScript</h1>
<p>Now comes the most important part - JavaScript. We'll start by selecting few elements of the DOM. These elements will be used to manipulate our piano. First of all, we'll need to select all the keys that are available to us. All the keys have a class of <code>key</code>, so targeting the key class will do the job.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> keys = <span class="hljs-built_in">document</span>.querySelectorAll(<span class="hljs-string">'.key'</span>);
</code></pre>
<p>We would also need to target the regulars and the sharp keys. As you know, our regulars have a <code>white</code> class and the sharps have a <code>black</code> class. Let's target them now.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> regulars = <span class="hljs-built_in">document</span>.querySelectorAll(<span class="hljs-string">'.key.white'</span>);
<span class="hljs-keyword">const</span> sharps = <span class="hljs-built_in">document</span>.querySelectorAll(<span class="hljs-string">'.key.black'</span>);
</code></pre>
<p>Now that we have selected the elements, the next thing we will do is to add a function to each of the keys.</p>
<pre><code class="lang-javascript">keys.forEach(<span class="hljs-function">(<span class="hljs-params">key</span>) =&gt;</span> {
  key.addEventListener(<span class="hljs-string">'click'</span>, <span class="hljs-function">() =&gt;</span> playNote(key));
});
</code></pre>
<p>Here, we are binding a function with the <code>click</code> event. For each click, the <code>playNote</code> function will be executed. The <code>playNote</code> function takes a single parameter ‘<code>key</code>’, which is the audio of that key. We are using <a target="_blank" href="https://www.studytonight.com/javascript/javascript-arrow-function">arrow functions</a> here.</p>
<p>Let's move to write the <code>playNote</code> function.</p>
<p>Our function takes a single parameter and that is the key that is pressed. The first thing when writing our function is to identify which key is pressed. How do we do so? Here comes the <code>data</code> attribute in use. At the <code>playNote</code> function call, we are passing the <code>key</code>parameter. The <code>key</code> parameter is nothing but the <code>div</code>which is clicked. So, to start with our function, let's first select the note that is pressed.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> playNote = <span class="hljs-function">(<span class="hljs-params">key</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> noteSound = <span class="hljs-built_in">document</span>.getElementById(key.dataset.note);
  <span class="hljs-built_in">console</span>.log(noteSound);
};
</code></pre>
<p>To access the <code>data</code> attribute, we use the <code>dataset</code> keyword in JavaScript. If we console log the <code>noteSound</code> constant, we will see that it is returning the <code>audio</code> attribute depending on the key that is pressed. Our piano maps the audio id with the <code>data-note</code> attribute of the key to play the correct audio. To play the audio now, we'll use the play method.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> playNote = <span class="hljs-function">(<span class="hljs-params">key</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> noteSound = <span class="hljs-built_in">document</span>.getElementById(key.dataset.note);
  noteSound.play();
};
</code></pre>
<p>Our piano is almost ready. But we can add a few modifications. If you press single key multiple times now, it’ll not play until the audio sound ends completely. We don't want it. We want to play the audio every time the key is clicked. To do so, we have to set the current time to zero each time the key is clicked. Another modification we can do here is to add a class to make it visible which key is pressed. For that, we have to add two classes to our CSS file. One is to show the active white key and another one is to show the active black key. We will just change the background color of the keys.</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.white</span><span class="hljs-selector-class">.active</span> {
    <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#ccc</span>;
}

<span class="hljs-selector-class">.black</span><span class="hljs-selector-class">.active</span> {
    <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#333</span>;
}
</code></pre>
<p>As you can see, the <code>.white.active</code> class has a darker white background and the <code>.black.active</code> class has lighter black color. To add the colors when keys are pressed, we'll use the <code>classList.add</code> method available in JavaScript.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> playNote = <span class="hljs-function">(<span class="hljs-params">key</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> noteSound = <span class="hljs-built_in">document</span>.getElementById(key.dataset.note);
  noteSound.currentTime = <span class="hljs-number">0</span>;
  noteSound.play();
  key.classList.add(<span class="hljs-string">'active'</span>);
  noteSound.addEventListener(<span class="hljs-string">'ended'</span>, <span class="hljs-function">() =&gt;</span> {
    key.classList.remove(<span class="hljs-string">'active'</span>);
  });
};
</code></pre>
<p>We are adding the class using the <code>key.classList.add('active')</code> method to a key whenever the key is pressed. And we are removing the class when the audio is completely played. For this, we are listening to an event called ‘<code>ended</code>’ and whenever this event is triggered, we are removing the class using <code>key.classList.remove(‘active’)</code> method.</p>
<p>And we are done building the piano.</p>
<h1 id="building-the-piano-computer-keyboard-friendly">🎈 Building the Piano Computer Keyboard Friendly</h1>
<p>But, we can stretch our piano further. How about playing our piano using the keyboard? Sounds awesome right? Let's just jump into building it our computer keyboard friendly!</p>
<p>First of all, we have to choose which keys to use. I think the middle layer of the keyboard, i.e., the line of keys with the Caps Lock button is perfect for it, because it has keys in the middle of it above it, just like an original piano. So, we can use the keys from <strong>A</strong> to <strong>J</strong> for the regular keys, and keys from <strong>W</strong> to <strong>Y</strong> for the sharps.</p>
<p>We will start by adding some CSS to help our users understand which key to press. Inside all the divs, we will add the corresponding keyboard key. So, now our HTML of divs will look like this now,</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"piano"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"key white"</span> <span class="hljs-attr">data-note</span>=<span class="hljs-string">"C"</span>&gt;</span>A<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"key black"</span> <span class="hljs-attr">data-note</span>=<span class="hljs-string">"Cs"</span>&gt;</span>W<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"key white"</span> <span class="hljs-attr">data-note</span>=<span class="hljs-string">"D"</span>&gt;</span>S<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"key black"</span> <span class="hljs-attr">data-note</span>=<span class="hljs-string">"Ds"</span>&gt;</span>E<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"key white"</span> <span class="hljs-attr">data-note</span>=<span class="hljs-string">"E"</span>&gt;</span>D<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"key white"</span> <span class="hljs-attr">data-note</span>=<span class="hljs-string">"F"</span>&gt;</span>F<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"key black"</span> <span class="hljs-attr">data-note</span>=<span class="hljs-string">"Fs"</span>&gt;</span>R<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"key white"</span> <span class="hljs-attr">data-note</span>=<span class="hljs-string">"G"</span>&gt;</span>G<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"key black"</span> <span class="hljs-attr">data-note</span>=<span class="hljs-string">"Gs"</span>&gt;</span>T<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"key white"</span> <span class="hljs-attr">data-note</span>=<span class="hljs-string">"A"</span>&gt;</span>H<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"key black"</span> <span class="hljs-attr">data-note</span>=<span class="hljs-string">"As"</span>&gt;</span>Y<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"key white"</span> <span class="hljs-attr">data-note</span>=<span class="hljs-string">"B"</span>&gt;</span>J<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<p>In the CSS part, we will style the ‘<code>key</code>’ class. The color of the text will be updated in the white and black classes because the colors will be different for the key types. We will use flexbox to position the text. Here’s our complete styling,</p>
<pre><code class="lang-css">* {
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">0</span>;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">0</span>;
  <span class="hljs-attribute">box-sizing</span>: border-box;
}

<span class="hljs-selector-tag">body</span> {
  <span class="hljs-attribute">background</span>: <span class="hljs-number">#0f2027</span>;
  <span class="hljs-comment">/* fallback for old browsers */</span>
  <span class="hljs-attribute">background</span>: <span class="hljs-built_in">-webkit-linear-gradient</span>(to bottom, #<span class="hljs-number">2</span>c5364, #<span class="hljs-number">203</span>a43, #<span class="hljs-number">0</span>f2027);
  <span class="hljs-comment">/* Chrome 10-25, Safari 5.1-6 */</span>
  <span class="hljs-attribute">background</span>: <span class="hljs-built_in">linear-gradient</span>(to bottom, #<span class="hljs-number">2</span>c5364, #<span class="hljs-number">203</span>a43, #<span class="hljs-number">0</span>f2027);
  <span class="hljs-comment">/* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */</span>
}

<span class="hljs-selector-class">.piano</span> {
  <span class="hljs-attribute">height</span>: <span class="hljs-number">100vh</span>;
  <span class="hljs-attribute">width</span>: <span class="hljs-number">100%</span>;
  <span class="hljs-attribute">display</span>: flex;
  <span class="hljs-attribute">justify-content</span>: center;
}

<span class="hljs-selector-class">.key</span> {
  <span class="hljs-attribute">display</span>: flex;
  <span class="hljs-attribute">justify-content</span>: center;
  <span class="hljs-attribute">align-items</span>: flex-end;
  <span class="hljs-attribute">font-size</span>: <span class="hljs-number">1.2rem</span>;
  <span class="hljs-attribute">font-weight</span>: bold;
  <span class="hljs-attribute">padding-bottom</span>: <span class="hljs-number">20px</span>;
}

<span class="hljs-selector-class">.white</span> {
  <span class="hljs-attribute">width</span>: <span class="hljs-number">9%</span>;
  <span class="hljs-attribute">min-width</span>: <span class="hljs-number">60px</span>;
  <span class="hljs-attribute">height</span>: <span class="hljs-number">70%</span>;
  <span class="hljs-attribute">background-color</span>: white;
  <span class="hljs-attribute">border</span>: <span class="hljs-number">1px</span> solid <span class="hljs-number">#ccc</span>;
  <span class="hljs-attribute">color</span>: <span class="hljs-number">#000</span>;
}

<span class="hljs-selector-class">.black</span> {
  <span class="hljs-attribute">width</span>: <span class="hljs-number">8%</span>;
  <span class="hljs-attribute">height</span>: <span class="hljs-number">45%</span>;
  <span class="hljs-attribute">margin-left</span>: -<span class="hljs-number">4%</span>;
  <span class="hljs-attribute">margin-right</span>: -<span class="hljs-number">4%</span>;
  <span class="hljs-attribute">z-index</span>: <span class="hljs-number">2</span>;
  <span class="hljs-attribute">background-color</span>: black;
  <span class="hljs-attribute">color</span>: <span class="hljs-number">#fff</span>;
}

<span class="hljs-selector-class">.white</span><span class="hljs-selector-class">.active</span> {
  <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#ccc</span>;
}

<span class="hljs-selector-class">.black</span><span class="hljs-selector-class">.active</span> {
  <span class="hljs-attribute">background-color</span>: <span class="hljs-number">#333</span>;
}
</code></pre>
<p>Now, let’s jump back to JavaScript again. We will create two arrays. These arrays will represent the keys. Check the arrays below, and you’ll get an idea.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> whites = [<span class="hljs-string">'a'</span>, <span class="hljs-string">'s'</span>, <span class="hljs-string">'d'</span>, <span class="hljs-string">'f'</span>, <span class="hljs-string">'g'</span>, <span class="hljs-string">'h'</span>, <span class="hljs-string">'j'</span>];
<span class="hljs-keyword">const</span> blacks = [<span class="hljs-string">'w'</span>, <span class="hljs-string">'e'</span>, <span class="hljs-string">'r'</span>, <span class="hljs-string">'t'</span>, <span class="hljs-string">'y'</span>];
</code></pre>
<p>The regular keys will be accessed through the keys <strong>a to j</strong>, and the sharps will be accessed through the keys <strong>w to y</strong>.</p>
<p>Now comes the most important section, the logic part. When a key is pressed, a <code>keydown</code> event is triggered. We will use this event to play audio.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">document</span>.addEventListener(<span class="hljs-string">'keydown'</span>, <span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> {
  <span class="hljs-keyword">if</span> (e.repeat) <span class="hljs-keyword">return</span>;
  <span class="hljs-keyword">const</span> key = e.key;
  <span class="hljs-keyword">const</span> whiteKeyIndex = whites.indexOf(key);
  <span class="hljs-keyword">const</span> blackKeyIndex = blacks.indexOf(key);

  <span class="hljs-keyword">if</span> (whiteKeyIndex &gt; <span class="hljs-number">-1</span>) playNote(regulars[whiteKeyIndex]);
  <span class="hljs-keyword">if</span> (blackKeyIndex &gt; <span class="hljs-number">-1</span>) playNote(sharps[blackKeyIndex]);
});
</code></pre>
<p>We are adding an event listener to listen to the <code>keydown</code> event. When the event is observed, we pass in a parameter inside the event listener function. To get the key that is pressed, we will use the <code>e.key</code> method. The <code>e.key</code> method will return the key that is pressed. Now, we’ll get the index of the key and will store it inside a variable. To store the white key index, we are using a variable called <code>whiteKeyIndex</code> and for the black key index, we’ll use a <code>blackKeyIndex</code> variable. To get the index, we’ll use the<code>indexOf</code>method. Inside the array of whites or blacks, we are checking the index of the key that is pressed using the <code>indexOf</code>method. Now that we know the index of the key that is pressed, we will write a condition. The condition is, if a white key is found(-1 means not found, any value larger than it means that the key is found), the <code>playNote</code>function will be invoked. And, inside the <code>playNote</code> function, we’ll pass in the key by locating it in the array with <code>regulars[whiteKeyIndex]</code>. We are doing the same step for the black keys also. Please keep in mind, because we are using the array to locate the key, our array should be in the exact order in which we want our piano keys to be set up.</p>
<p>The only thing that is left in our code is that, if you hold a key, the audio will sound ridiculous. Because, when a key is held, the <code>keydown</code>event gets triggered after every few seconds. To stop this behavior, we’ll check if the key is held down. If it is, then we’ll simply return the function. Returning the function will not execute any code. And this is done by <code>if (e.repeat) return</code> line. And we are done. Our piano is ready.</p>
<p>To check the complete source code, visit the GitHub repo <a target="_blank" href="https://github.com/nemo0/js-piano">here</a>. </p>
<h1 id="conclusion">🖼 Conclusion</h1>
<p>I hope you enjoyed building this piano. To get such more tutorials, keep visiting <a target="_blank" href="https://nemo.hashnode.dev">nemo.hashnode.dev</a>. Here is another simple JavaScript tutorial about building a <a target="_blank" href="https://nemo.hashnode.dev/create-a-javascript-covid-19-tracker-ckpm90f3d0qpyz0s177p25aft">covid 19 tracker</a>.</p>
]]></content:encoded></item><item><title><![CDATA[Create a Javascript Covid 19 Tracker]]></title><description><![CDATA[In this article, we will be building a web-based COVID 19 tracker using HTML, CSS, and Javascript, which tracks the coronavirus cases in the World for the last three months and shows it in a line graph. The project is pretty easy and straightforward....]]></description><link>https://blog.nemotivity.dev/create-a-javascript-covid-19-tracker</link><guid isPermaLink="true">https://blog.nemotivity.dev/create-a-javascript-covid-19-tracker</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[HTML5]]></category><category><![CDATA[CSS]]></category><category><![CDATA[APIs]]></category><category><![CDATA[Beginner Developers]]></category><dc:creator><![CDATA[Subha Chanda]]></dc:creator><pubDate>Mon, 07 Jun 2021 06:43:52 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1623048152884/QvVADVitp.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In this article, we will be building a web-based COVID 19 tracker using HTML, CSS, and Javascript, which tracks the coronavirus cases in the World for the last three months and shows it in a <strong>line graph</strong>. The project is pretty easy and straightforward. You can create a COVID tracker and show it off to your friends!</p>
<p>Things we'll implement in building this tracker are</p>
<ul>
<li>👨‍🍳 API</li>
<li>🤞 Promises</li>
<li>🅱 Bootstrap </li>
<li>📉 ChartJS </li>
<li>🧠 Brain! </li>
</ul>
<p><strong>File Structure for the App:</strong></p>
<p>COVID Tracker App</p>
<ul>
<li><code>index.html</code></li>
<li><code>styles.css</code></li>
<li><code>scripts.js</code></li>
</ul>
<p>So, let's start.</p>
<h2 id="creating-the-markup">🦴 Creating the Markup</h2>
<p>Our HTML file doesn't contain a lot of code. The only necessary thing we need in the HTML except the boilerplate is the Canvas. The canvas is used by the ChartJS library(which we'll see later) to create a chart.</p>
<p><strong>HTML Markup:</strong></p>
<pre><code class="lang-html"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<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">link</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">"stylesheet"</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"./styles.css"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">link</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">"stylesheet"</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>Track Covid Tonight<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">class</span>=<span class="hljs-string">"container"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">h1</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"text-center mt-4 heading"</span>&gt;</span>Track Covid Tonight<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">canvas</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"myChart"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">canvas</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">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"myList"</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">"./scripts.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://cdn.jsdelivr.net/npm/chart.js@2.9.3/dist/Chart.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">body</span>&gt;</span>

<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p>As you can see, our HTML file contains the bootstrap CSS file, a local <code>styles.css</code> file, and the most important <code>scripts.js</code> file. We also need the ChartJS library to display the chart. We have used CDNs(content delivery networks) for bootstrap and the Chart.</p>
<p>The markup has an <code>h1</code> element which shows the heading and a canvas that renders the chart. We've enclosed both the h1 and the canvas inside the bootstrap class called the container. Now let's see our <code>styles.css</code> file.</p>
<h2 id="adding-styles">🎨Adding Styles</h2>
<p><strong>styles.css</strong></p>
<pre><code class="lang-CSS">* {
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">0</span>;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">0</span>;
  <span class="hljs-attribute">box-sizing</span>: border-box;
}

<span class="hljs-selector-tag">body</span> {
  <span class="hljs-attribute">height</span>: <span class="hljs-number">100vh</span>;
}
</code></pre>
<p>If you want to style the app with your own styles, you can do so. I'd love to see your designs. However, I've kept the app minimal. Our <code>styles.css</code> file resets the default styles and adds height to the body element. We are using CSS <code>vh</code> unit which represents the viewport height. We are setting to <code>100vh</code>which means the body will cover the complete viewport.</p>
<h2 id="adding-javascript-functions">🤴 Adding JavaScript Functions</h2>
<p>Now, let's jump to the most important file. The <code>scripts.js</code> file. Our <code>scripts.js</code> file contains all the necessary codes to fetch and display the data.</p>
<p><strong>scripts.js</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> api = <span class="hljs-string">'https://disease.sh/v3/covid-19/historical/all?lastdays=90'</span>;

<span class="hljs-keyword">const</span> getData = <span class="hljs-keyword">async</span> () =&gt; {
  <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">`<span class="hljs-subst">${api}</span>`</span>);
  <span class="hljs-keyword">if</span> (response.ok) {
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">await</span> response.json();
  } <span class="hljs-keyword">else</span> {
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">Promise</span>.reject(response.status);
  }
};

<span class="hljs-keyword">const</span> result = getData();
result
  .then(<span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> {
    <span class="hljs-keyword">let</span> date = <span class="hljs-built_in">Object</span>.keys(data.cases);
    <span class="hljs-keyword">let</span> total = <span class="hljs-built_in">Object</span>.values(data.cases);
    <span class="hljs-keyword">let</span> deaths = <span class="hljs-built_in">Object</span>.values(data.deaths);
    <span class="hljs-keyword">let</span> recovered = <span class="hljs-built_in">Object</span>.values(data.recovered);

    <span class="hljs-keyword">var</span> ctx = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'myChart'</span>).getContext(<span class="hljs-string">'2d'</span>);
    <span class="hljs-keyword">let</span> myChart = <span class="hljs-keyword">new</span> Chart(ctx, {
      <span class="hljs-attr">type</span>: <span class="hljs-string">'line'</span>,
      <span class="hljs-attr">data</span>: {
        <span class="hljs-attr">labels</span>: date,
        <span class="hljs-attr">datasets</span>: [
          {
            <span class="hljs-attr">label</span>: <span class="hljs-string">'Total Cases'</span>,
            <span class="hljs-attr">data</span>: total,
            <span class="hljs-attr">borderColor</span>: <span class="hljs-string">'rgba(255, 99, 132)'</span>,
            <span class="hljs-attr">fill</span>: <span class="hljs-literal">false</span>,
          },
          {
            <span class="hljs-attr">label</span>: <span class="hljs-string">'Recovered Cases'</span>,
            <span class="hljs-attr">data</span>: recovered,
            <span class="hljs-attr">borderColor</span>: <span class="hljs-string">'rgba(153, 102, 255, 1)'</span>,
            <span class="hljs-attr">fill</span>: <span class="hljs-literal">false</span>,
          },
          {
            <span class="hljs-attr">label</span>: <span class="hljs-string">'Deaths'</span>,
            <span class="hljs-attr">data</span>: deaths,
            <span class="hljs-attr">borderColor</span>: <span class="hljs-string">'rgba(75, 192, 192, 1)'</span>,
            <span class="hljs-attr">fill</span>: <span class="hljs-literal">false</span>,
          },
        ],
      },
      <span class="hljs-attr">options</span>: {
        <span class="hljs-attr">scales</span>: {
          <span class="hljs-attr">yAxes</span>: [
            {
              <span class="hljs-attr">scaleLabel</span>: {
                <span class="hljs-attr">display</span>: <span class="hljs-literal">true</span>,
                <span class="hljs-attr">labelString</span>: <span class="hljs-string">'Numbers in Thousands'</span>,
              },
            },
          ],
          <span class="hljs-attr">xAxes</span>: [
            {
              <span class="hljs-attr">scaleLabel</span>: {
                <span class="hljs-attr">display</span>: <span class="hljs-literal">true</span>,
                <span class="hljs-attr">labelString</span>: <span class="hljs-string">'Date(DD/MM/YYYY)'</span>,
              },
            },
          ],
        },
        <span class="hljs-attr">title</span>: {
          <span class="hljs-attr">display</span>: <span class="hljs-literal">true</span>,
          <span class="hljs-attr">text</span>: <span class="hljs-string">`Coronovirus Cases in India for Last Three Months`</span>,
        },
      },
    });
  })
  .catch(<span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Error: '</span>, error);
  });
</code></pre>
<p>Don't get scared. The file looks scary, but it isn't. We'll understand the file by breaking in into parts.</p>
<p>Let's start at the top. We will use an API called <a target="_blank" href="https://disease.sh/">disease.sh</a> to fetch our data. I hope you know what an API is? API stands for <strong>Application Programming Interface</strong>. An API works as a waiter between the client and the server to put it in easy words. We ask for data from the server using the API, and the server returns our data through the API. It works as an intermediary.</p>
<p>We'll use the <strong>disease.sh</strong> to fetch coronavirus cases for the last 90 days. To fetch data from a date range, the API uses the below endpoint</p>
<pre><code><span class="hljs-attribute">https</span>://disease.sh/v<span class="hljs-number">3</span>/covid-<span class="hljs-number">19</span>/historical/<span class="hljs-literal">all</span>?lastdays=NO-OF-DAYS
</code></pre><p>We are setting the number of days to 90. Then we are fetching the data using an async function. First, let's see how the data looks like,</p>
<p><img src="https://i.ibb.co/vk7kc7D/1.png" alt="JSON Data from disease.sh for covid tracker" /></p>
<p>I've reduced the days to 10 to make it look cleaner here. This data might look cluttered in your browser. I've used a JSON formatter extension to look it cleaner. So, the API returns us three objects, i.e., cases, deaths and recovered. Each of the objects contains a key-value pair of date and numbers. The numbers represent the number of cases, deaths and recoveries. I think you get the idea. Now let's see how we fetch the data using the API.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> api = <span class="hljs-string">'https://disease.sh/v3/covid-19/historical/all?lastdays=90'</span>;

<span class="hljs-keyword">const</span> getData = <span class="hljs-keyword">async</span> () =&gt; {
  <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> fetch(<span class="hljs-string">`<span class="hljs-subst">${api}</span>`</span>);
  <span class="hljs-keyword">if</span> (response.ok) {
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">await</span> response.json();
  } <span class="hljs-keyword">else</span> {
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">Promise</span>.reject(response.status);
  }
};
</code></pre>
<p>We've added basic error handling to the function. If the <code>response.ok</code> is true, only then our promise will resolve. Otherwise, it'll reject and return an error. Also, we are using JavaScript <code>template literals</code> to fetch the API in our <code>getData</code> function. After creating the function we will be storing the data returned in a variable called <code>result</code>. Because the function will also return a promise, we have to handle it using a <code>then</code>statement. If you are not comfortable with JavaScript Promises, you can check the <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">MDN</a> docs.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> result = getData();
result
  .then(<span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> {
    <span class="hljs-keyword">let</span> date = <span class="hljs-built_in">Object</span>.keys(data.cases);
    <span class="hljs-keyword">let</span> total = <span class="hljs-built_in">Object</span>.values(data.cases);
    <span class="hljs-keyword">let</span> deaths = <span class="hljs-built_in">Object</span>.values(data.deaths);
    <span class="hljs-keyword">let</span> recovered = <span class="hljs-built_in">Object</span>.values(data.recovered);
};
</code></pre>
<p>This is the first part of our <code>then</code>statement. First, we are storing the dates in an array called <code>date</code>. We are sorting the data in arrays because ChartJS supports arrays. The <code>Object.keys</code> method returns an array containing the key properties from an object. We are targeting the keys because the API returns the values in a <code>key-value</code> pair of dates and cases. Then we are targeting the total cases, deaths and recoveries similarly and storing them to corresponding variables. You can <code>console.log</code> the values to see how the arrays look.</p>
<p><img src="https://i.ibb.co/Xjf6C9L/2.png" alt="Returned Arrays for covid tracker" /></p>
<p>We are almost done with the data. The only thing which is left now is visualizing the data. To visualize, we'll be using a popular data visualization library called Chart.js. It is a lightweight library which can make it easy to visualize data in popular formats like a bar chart, line chart, pie chart and more. We'll be using the line chart here.</p>
<p>Let's see the <code>myChart</code>function.</p>
<pre><code class="lang-javascript">    <span class="hljs-keyword">var</span> ctx = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'myChart'</span>).getContext(<span class="hljs-string">'2d'</span>);
    <span class="hljs-keyword">let</span> myChart = <span class="hljs-keyword">new</span> Chart(ctx, {
      <span class="hljs-attr">type</span>: <span class="hljs-string">'line'</span>,
      <span class="hljs-attr">data</span>: {
        <span class="hljs-attr">labels</span>: date,
        <span class="hljs-attr">datasets</span>: [
          {
            <span class="hljs-attr">label</span>: <span class="hljs-string">'Total Cases'</span>,
            <span class="hljs-attr">data</span>: total,
            <span class="hljs-attr">borderColor</span>: <span class="hljs-string">'rgba(255, 99, 132)'</span>,
            <span class="hljs-attr">fill</span>: <span class="hljs-literal">false</span>,
          },
          {
            <span class="hljs-attr">label</span>: <span class="hljs-string">'Recovered Cases'</span>,
            <span class="hljs-attr">data</span>: recovered,
            <span class="hljs-attr">borderColor</span>: <span class="hljs-string">'rgba(153, 102, 255, 1)'</span>,
            <span class="hljs-attr">fill</span>: <span class="hljs-literal">false</span>,
          },
          {
            <span class="hljs-attr">label</span>: <span class="hljs-string">'Deaths'</span>,
            <span class="hljs-attr">data</span>: deaths,
            <span class="hljs-attr">borderColor</span>: <span class="hljs-string">'rgba(75, 192, 192, 1)'</span>,
            <span class="hljs-attr">fill</span>: <span class="hljs-literal">false</span>,
          },
        ],
      },
      <span class="hljs-attr">options</span>: {
        <span class="hljs-attr">scales</span>: {
          <span class="hljs-attr">yAxes</span>: [
            {
              <span class="hljs-attr">scaleLabel</span>: {
                <span class="hljs-attr">display</span>: <span class="hljs-literal">true</span>,
                <span class="hljs-attr">labelString</span>: <span class="hljs-string">'Number of Cases'</span>,
              },
            },
          ],
          <span class="hljs-attr">xAxes</span>: [
            {
              <span class="hljs-attr">scaleLabel</span>: {
                <span class="hljs-attr">display</span>: <span class="hljs-literal">true</span>,
                <span class="hljs-attr">labelString</span>: <span class="hljs-string">'Date(DD/MM/YYYY)'</span>,
              },
            },
          ],
        },
        <span class="hljs-attr">title</span>: {
          <span class="hljs-attr">display</span>: <span class="hljs-literal">true</span>,
          <span class="hljs-attr">text</span>: <span class="hljs-string">`Coronavirus Cases in the World for 90 Days`</span>,
        },
      },
    });
</code></pre>
<p>The first thing we are doing here is, we are targeting our <code>canvas</code>which has an ID of <code>myChart</code>. The <code>getContext</code>gives access to the canvas tags 2D drawing functions. Then using the Chart constructor, we're creating a function that contains all the necessary configurations for the chart. The type:<code>'line'</code> specifies the type of chart. The <code>data</code>object holds all the <code>datasets</code>, <code>labels</code>and other data related configurations. We are passing our date variable as the label for our chart using <code>labels: date</code>. The <code>datasets</code>are an array of objects which hold the label, data, and colors for each line. There are a lot of other configurations available. But to keep this article simple we are using minimal options. You can check their documentation to get an idea about available options <a target="_blank" href="https://www.chartjs.org/docs/latest/">here</a>. After the <code>data</code>object, we are setting up a few options for the look. The labels for x and y axes are set using the <code>yAxes</code> and <code>xAxes</code>objects. And the title for the chart is setup using the <code>title</code>object. We have completed our code. The last thing left is to catch any error. The <code>catch</code>statement is used in promises to catch errors. For this app, we'll catch the error and <code>console.log</code> it into the console.</p>
<pre><code class="lang-javascript">.catch(<span class="hljs-function">(<span class="hljs-params">error</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Error: '</span>, error);
});
</code></pre>
<p>After following all the steps, our app will look like this,</p>
<p><img src="https://i.ibb.co/7JpDqmL/3.png" alt="create javascript Covid Tracker" /></p>
<p>You can check the live version of the app <a target="_blank" href="https://track-covid-tonight.vercel.app/">here</a>. And to see the source code, visit <a target="_blank" href="https://github.com/nemo0/track-covid-tonight"><code>here</code></a>.</p>
<p>I hope you enjoyed building this tracker. I've tried to keep it simple. Now try building your own COVID tracker and share it with us. </p>
]]></content:encoded></item><item><title><![CDATA[Build a Theme Switcher for Your Website with JavaScript]]></title><description><![CDATA[You might have noticed that nowadays, many websites have a theme switcher on top of their website. The theme switcher can also be used as a dark mode switcher. In this article, we’ll be building a theme switcher like that.
I am not going to focus a l...]]></description><link>https://blog.nemotivity.dev/build-a-theme-switcher-for-your-website-with-javascript</link><guid isPermaLink="true">https://blog.nemotivity.dev/build-a-theme-switcher-for-your-website-with-javascript</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[HTML5]]></category><category><![CDATA[CSS]]></category><category><![CDATA[Beginner Developers]]></category><dc:creator><![CDATA[Subha Chanda]]></dc:creator><pubDate>Thu, 03 Jun 2021 06:42:10 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1622701640872/ZBa0i3Z9K.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>You might have noticed that nowadays, many websites have a theme switcher on top of their website. The theme switcher can also be used as a dark mode switcher. In this article, we’ll be building a theme switcher like that.</p>
<p>I am not going to focus a lot on the styles; instead, we’ll try to understand the logic about creating it. Also, the theme switcher will be persistent. The selected theme will be stored in the browser and will apply the same theme even after reloading. We’ll implement this using the browser’s local storage. So, let’s start building.</p>
<h3 id="things-you-need-to-know">Things you need to know</h3>
<ul>
<li>Basic HTML - Learn HTML</li>
<li>Basic CSS - Learn CSS</li>
<li>Little JavaScript - Learn JavaScript
and you are good to go.</li>
</ul>
<h3 id="heres-our-complete-app">Here's our Complete App</h3>
<p><img src="https://i.ibb.co/KwjRQq8/ezgif-com-video-to-gif.gif" alt /><em>Complete Theme Switcher</em>
<em>One thing I must explain before we start building the Markup is custom data attributes in HTML.</em></p>
<h2 id="what-are-html-data-attributes">What are HTML Data Attributes?</h2>
<p>There may be situations when we have to store some information associated with DOM elements. Let's take an example, suppose we have a list of employees and we want to save their IDs, which we can use to manipulate them using the DOM. Before HTML5, we could have used class or IDs, but this is not an impressive solution. HTML5 introduced us to the concept of Custom Data Attributes. Any attribute that starts with <code>data-</code> is a custom data attribute. We also have special HTML <code>data</code> tags in HTML5.</p>
<p>For example, we can name <code>data-identity</code> to create a custom data attribute for employee ID. Two things to keep in mind while creating a data attribute is that the value that is stored inside data attributes can only be of <strong>string</strong> type. And the second point is that <strong>we cannot use any valid HTML attribute as a name for data attributes</strong>. Like, <code>data-id</code> is <strong>not</strong> appropriate.</p>
<p>We can access these attributes in JavaScript with <code>dataset</code> property.</p>
<p>Suppose we want to access the identity attribute from before. We can access this using the below codes,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> employee = <span class="hljs-built_in">document</span>.getElementByClassName(<span class="hljs-string">"employee-table"</span>);
<span class="hljs-keyword">let</span> empID = employee.dataset.identity;
<span class="hljs-comment">// Or</span>
<span class="hljs-keyword">let</span> empID = employee.dataset[<span class="hljs-string">'identity'</span>]
</code></pre>
<p>Now that you have a basic understanding of the data attributes, let's start building our Theme Switcher.</p>
<p><strong>File Structure:</strong></p>
<pre><code class="lang-sh">|--themes
|------dark.css
|------light.css
|------purple.css
|------sky.css
|--index.html
|--script.js
|--style.css
</code></pre>
<p>Now that we know the file structure, let's begin the coding.</p>
<h2 id="building-the-markup">Building the Markup</h2>
<p>As you can understand from the gif above, we are not using any high-level design. We have a simple header section with the name of our app and the buttons to change the themes. Our body contains an image and some random texts. We are also using the Roboto font to style the document.</p>
<pre><code class="lang-html"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">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">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>Theme Switcher<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">link</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">"stylesheet"</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"./style.css"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">link</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"https://fonts.googleapis.com/css2?family=Roboto:wght@400;500;700;900&amp;display=swap"</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">"stylesheet"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">link</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">"stylesheet"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"switcher-id"</span> <span class="hljs-attr">href</span>=<span class="hljs-string">""</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">header</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>???? THEME SWITCHER<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"theme-switches"</span>&gt;</span>

            <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">data-theme</span>=<span class="hljs-string">"light"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"switch"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"switch-1"</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">div</span> <span class="hljs-attr">data-theme</span>=<span class="hljs-string">"sky"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"switch"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"switch-2"</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">div</span> <span class="hljs-attr">data-theme</span>=<span class="hljs-string">"purple"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"switch"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"switch-3"</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">div</span> <span class="hljs-attr">data-theme</span>=<span class="hljs-string">"dark"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"switch"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"switch-4"</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">div</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">header</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"container"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"box"</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">img</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"https://images.unsplash.com/photo-1597926588114-2d9c1190b5c7?ixlib=rb-1.2.1&amp;ixid=eyJhcHBfaWQiOjEyMDd9&amp;auto=format&amp;fit=crop&amp;w=923&amp;q=80"</span>
                <span class="hljs-attr">alt</span>=<span class="hljs-string">"Placeholder"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"image"</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"text"</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">h3</span>&gt;</span>A Sweet Heading<span class="hljs-tag">&lt;/<span class="hljs-name">h3</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod 
                tempor incididunt ut labore et dolore magna aliqua. Ut enim 
                ad minim veniam, quis nostrud exercitation ullamco laboris 
                nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor 
                in reprehenderit in voluptate velit esse cillum dolore eu fugiat 
                nulla pariatur. Excepteur sint occaecat cupidatat non proident, 
                sunt in culpa qui officia deserunt mollit anim id est laborum.<span class="hljs-tag">&lt;/<span class="hljs-name">p</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">div</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">"./script.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>
</code></pre>
<p>That is just a few lines of Markup. We have added the fonts in the header, default styles stylesheets, and a stylesheet link with a blank <code>href</code>. This blank <code>href</code> will be used to attach our theme designs. You can also see we are using a <code>data-theme</code> custom data attribute to keep track of the theme selected. We will use the IDs of theme switches to design the switches. In our main body, we are using an image from Unsplash. And some random text. And finally, in the end, we are linking our <code>script</code> file.</p>
<h2 id="styling-our-default-css">Styling Our Default CSS</h2>
<p>As you might have observed, we have two stylesheets tag in our HTML document. The first stylesheet is responsible for all the default styles our website will have, like the font-sizes, viewport height-width, image sizes. And the second one will be responsible for the specific theme designs.</p>
<p>We’ll also use <strong>CSS variables</strong> in this example. The benefits of using variables are that we can declare a variable once and use it multiple times in a document. Declaring variables in CSS are pretty easy. We usually define them in the <code>:root</code> selector. Any name that starts with <code>--</code> is a CSS variable. Example,</p>
<pre><code class="lang-css"><span class="hljs-selector-tag">root</span> {
    <span class="hljs-attribute">--text-color</span>: <span class="hljs-number">#000</span>;
    <span class="hljs-attribute">--back-color</span>: <span class="hljs-number">#eee</span>;
}
</code></pre>
<p>In our default stylesheet, we will be declaring four variables that will be used for the theme switches. Then we'll reset our document.
We'll use <em>flex-box</em> to design the theme switches. The <code>display:flex</code> property set on the parent element will make the child elements horizontal. The <code>justify-content:center</code> will center the elements.
For the growing effect on the switches, we are using the CSS <code>scale</code> transform property. We are scaling the element 1.2 times the original. And for the smooth effect, we are using <code>transition: 0.3s all;</code>. Then, we are using our variables to design the switches. We are adding the variables as <code>background-color</code> on the switches to design them.
You can check the code, and you'll get a clear idea. We are also using some basic media-queries for responsiveness. I think I don't have to explain the whole code because it is pretty basic. And I've discussed the portions I thought needs some explanation. Here's the full CSS code.</p>
<pre><code class="lang-css"><span class="hljs-selector-pseudo">:root</span> {
  <span class="hljs-attribute">--light</span>: <span class="hljs-number">#ffffff</span>;
  <span class="hljs-attribute">--sky</span>: <span class="hljs-number">#7f9cf5</span>;
  <span class="hljs-attribute">--purple</span>: <span class="hljs-number">#97266d</span>;
  <span class="hljs-attribute">--dark</span>: <span class="hljs-number">#81899b</span>;
}

* {
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">0</span>;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">0</span>;
  <span class="hljs-attribute">box-sizing</span>: border-box;
}

<span class="hljs-selector-tag">body</span> {
  <span class="hljs-attribute">font-family</span>: <span class="hljs-string">'Roboto'</span>, sans-serif;
  <span class="hljs-attribute">height</span>: <span class="hljs-number">100vh</span>;
  <span class="hljs-attribute">overflow-x</span>: hidden;
}

<span class="hljs-selector-tag">header</span> {
  <span class="hljs-attribute">text-align</span>: center;
  <span class="hljs-attribute">font-size</span>: <span class="hljs-number">30px</span>;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">50px</span> <span class="hljs-number">0</span>;
}

<span class="hljs-selector-class">.theme-switches</span> {
  <span class="hljs-attribute">display</span>: flex;
  <span class="hljs-attribute">justify-content</span>: center;
}

<span class="hljs-selector-class">.switch</span> {
  <span class="hljs-attribute">border</span>: <span class="hljs-number">2px</span> solid black;
  <span class="hljs-attribute">border-radius</span>: <span class="hljs-number">50px</span>;
  <span class="hljs-attribute">height</span>: <span class="hljs-number">30px</span>;
  <span class="hljs-attribute">width</span>: <span class="hljs-number">30px</span>;
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">10px</span>;
  <span class="hljs-attribute">cursor</span>: pointer;
}

<span class="hljs-selector-class">.switch</span><span class="hljs-selector-pseudo">:hover</span> {
  <span class="hljs-attribute">transform</span>: <span class="hljs-built_in">scale</span>(<span class="hljs-number">1.2</span>);
  <span class="hljs-attribute">transition</span>: <span class="hljs-number">0.3s</span> ease-in-out;
}

<span class="hljs-selector-id">#switch-1</span> {
  <span class="hljs-attribute">background-color</span>: <span class="hljs-built_in">var</span>(--light);
}

<span class="hljs-selector-id">#switch-2</span> {
  <span class="hljs-attribute">background-color</span>: <span class="hljs-built_in">var</span>(--sky);
}

<span class="hljs-selector-id">#switch-3</span> {
  <span class="hljs-attribute">background-color</span>: <span class="hljs-built_in">var</span>(--purple);
}

<span class="hljs-selector-id">#switch-4</span> {
  <span class="hljs-attribute">background-color</span>: <span class="hljs-built_in">var</span>(--dark);
}

<span class="hljs-selector-class">.container</span> {
  <span class="hljs-attribute">max-width</span>: <span class="hljs-number">80%</span>;
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">0</span> auto;
}

<span class="hljs-selector-class">.box</span> {
  <span class="hljs-attribute">display</span>: flex;
  <span class="hljs-attribute">justify-content</span>: space-around;
  <span class="hljs-attribute">margin-top</span>: <span class="hljs-number">100px</span>;
}

<span class="hljs-selector-class">.box</span> <span class="hljs-selector-tag">img</span> {
  <span class="hljs-attribute">max-height</span>: <span class="hljs-number">300px</span>;
  <span class="hljs-attribute">width</span>: auto;
  <span class="hljs-attribute">border-radius</span>: <span class="hljs-number">20px</span>;
  <span class="hljs-attribute">margin</span>: <span class="hljs-number">20px</span>;
}

<span class="hljs-selector-class">.text</span> {
  <span class="hljs-attribute">width</span>: <span class="hljs-number">50%</span>;
}

<span class="hljs-selector-class">.text</span> <span class="hljs-selector-tag">h3</span> {
  <span class="hljs-attribute">font-size</span>: <span class="hljs-number">35px</span>;
  <span class="hljs-attribute">padding</span>: <span class="hljs-number">30px</span> <span class="hljs-number">0</span>;
  <span class="hljs-attribute">font-weight</span>: <span class="hljs-number">600</span>;
}

<span class="hljs-selector-class">.text</span> <span class="hljs-selector-tag">p</span> {
  <span class="hljs-attribute">font-size</span>: <span class="hljs-number">20px</span>;
  <span class="hljs-attribute">font-weight</span>: <span class="hljs-number">400</span>;
}

<span class="hljs-comment">/* Media Query */</span>
<span class="hljs-keyword">@media</span> (<span class="hljs-attribute">max-width:</span> <span class="hljs-number">768px</span>) {
  <span class="hljs-selector-tag">header</span> <span class="hljs-selector-tag">h1</span> {
    <span class="hljs-attribute">font-size</span>: <span class="hljs-number">25px</span>;
  }

  <span class="hljs-selector-class">.box</span> {
    <span class="hljs-attribute">display</span>: flex;
    <span class="hljs-attribute">flex-wrap</span>: wrap;
  }

  <span class="hljs-selector-class">.box</span> <span class="hljs-selector-tag">img</span> {
    <span class="hljs-attribute">max-width</span>: <span class="hljs-number">80vw</span>;
  }

  <span class="hljs-selector-class">.text</span> {
    <span class="hljs-attribute">width</span>: <span class="hljs-number">80%</span>;
  }
}
</code></pre>
<h2 id="styling-our-themes">Styling Our Themes</h2>
<p>Now, let's set our theme files.</p>
<p>First, let’s understand the properties that change when we change a theme. Let's make a list of them.</p>
<ol>
<li>Heading Background</li>
<li>Text Colors</li>
<li>Image Border</li>
<li>Body Background Color
Now that we've outlined the colors we’ll be changing, most of our work is done. First, create a file called <code>light.css</code> for the light styles.</li>
</ol>
<p><strong>light.css</strong></p>
<pre><code class="lang-css"><span class="hljs-selector-pseudo">:root</span> {
  <span class="hljs-attribute">--back-color</span>: <span class="hljs-number">#eee</span>;
  <span class="hljs-attribute">--primary-color</span>: <span class="hljs-number">#000000</span>;
  <span class="hljs-attribute">--header-back</span>: <span class="hljs-number">#5d5d5d</span>;
  <span class="hljs-attribute">--header-text</span>: <span class="hljs-number">#eee</span>;
}

<span class="hljs-selector-tag">body</span> {
  <span class="hljs-attribute">background-color</span>: <span class="hljs-built_in">var</span>(--back-color);
  <span class="hljs-attribute">color</span>: <span class="hljs-built_in">var</span>(--primary-color);
}

<span class="hljs-selector-tag">header</span> {
  <span class="hljs-attribute">background-color</span>: <span class="hljs-built_in">var</span>(--header-back);
  <span class="hljs-attribute">color</span>: <span class="hljs-built_in">var</span>(--header-text);
}

<span class="hljs-selector-class">.box</span> <span class="hljs-selector-tag">img</span> {
  <span class="hljs-attribute">border</span>: <span class="hljs-number">2px</span> solid <span class="hljs-built_in">var</span>(--primary-color);
}
</code></pre>
<p>As you can see, we've defined the colors we'll be using in the light theme as variables. Then we are just adding the colors to the properties we want to change. Pretty simple, right? I am attaching the other theme files below,</p>
<p><strong>sky.css</strong></p>
<pre><code class="lang-css"><span class="hljs-selector-pseudo">:root</span> {
  <span class="hljs-attribute">--back-color</span>: <span class="hljs-number">#c3dafe</span>;
  <span class="hljs-attribute">--primary-color</span>: <span class="hljs-number">#3c366b</span>;
  <span class="hljs-attribute">--header-back</span>: <span class="hljs-number">#5f718d</span>;
  <span class="hljs-attribute">--header-text</span>: <span class="hljs-number">#eee</span>;
}

<span class="hljs-selector-tag">body</span> {
  <span class="hljs-attribute">background-color</span>: <span class="hljs-built_in">var</span>(--back-color);
  <span class="hljs-attribute">color</span>: <span class="hljs-built_in">var</span>(--primary-color);
}

<span class="hljs-selector-tag">header</span> {
  <span class="hljs-attribute">background-color</span>: <span class="hljs-built_in">var</span>(--header-back);
  <span class="hljs-attribute">color</span>: <span class="hljs-built_in">var</span>(--header-text);
}

<span class="hljs-selector-class">.box</span> <span class="hljs-selector-tag">img</span> {
  <span class="hljs-attribute">border</span>: <span class="hljs-number">2px</span> solid <span class="hljs-built_in">var</span>(--primary-color);
}
</code></pre>
<p><strong>purple.css</strong></p>
<pre><code class="lang-css"><span class="hljs-selector-pseudo">:root</span> {
  <span class="hljs-attribute">--back-color</span>: <span class="hljs-number">#fed7e2</span>;
  <span class="hljs-attribute">--primary-color</span>: <span class="hljs-number">#702459</span>;
  <span class="hljs-attribute">--header-back</span>: <span class="hljs-number">#874f5e</span>;
  <span class="hljs-attribute">--header-text</span>: <span class="hljs-number">#eee</span>;
}

<span class="hljs-selector-tag">body</span> {
  <span class="hljs-attribute">background-color</span>: <span class="hljs-built_in">var</span>(--back-color);
  <span class="hljs-attribute">color</span>: <span class="hljs-built_in">var</span>(--primary-color);
}

<span class="hljs-selector-tag">header</span> {
  <span class="hljs-attribute">background-color</span>: <span class="hljs-built_in">var</span>(--header-back);
  <span class="hljs-attribute">color</span>: <span class="hljs-built_in">var</span>(--header-text);
}

<span class="hljs-selector-class">.box</span> <span class="hljs-selector-tag">img</span> {
  <span class="hljs-attribute">border</span>: <span class="hljs-number">2px</span> solid <span class="hljs-built_in">var</span>(--primary-color);
}
</code></pre>
<p><strong>dark.css</strong></p>
<pre><code class="lang-css"><span class="hljs-selector-pseudo">:root</span> {
  <span class="hljs-attribute">--back-color</span>: <span class="hljs-number">#81899b</span>;
  <span class="hljs-attribute">--primary-color</span>: <span class="hljs-number">#f9ffee</span>;
  <span class="hljs-attribute">--header-back</span>: <span class="hljs-number">#1a1d24</span>;
  <span class="hljs-attribute">--header-text</span>: <span class="hljs-number">#eee</span>;
}

<span class="hljs-selector-tag">body</span> {
  <span class="hljs-attribute">background-color</span>: <span class="hljs-built_in">var</span>(--back-color);
  <span class="hljs-attribute">color</span>: <span class="hljs-built_in">var</span>(--primary-color);
}

<span class="hljs-selector-tag">header</span> {
  <span class="hljs-attribute">background-color</span>: <span class="hljs-built_in">var</span>(--header-back);
  <span class="hljs-attribute">color</span>: <span class="hljs-built_in">var</span>(--header-text);
}

<span class="hljs-selector-class">.box</span> <span class="hljs-selector-tag">img</span> {
  <span class="hljs-attribute">border</span>: <span class="hljs-number">2px</span> solid <span class="hljs-built_in">var</span>(--primary-color);
}
</code></pre>
<p>As you can see, all our themes have the same styles, we’re just changing the color variables, and everything is ready.</p>
<h2 id="the-javascript-part">The JavaScript Part</h2>
<p>Here comes the most crucial part. Our JavaScript code is responsible for all the theme-changing things. Let’s first understand the logic behind our script file.</p>
<p>First, we’ll loop through all the switches and store the dataset value into a variable. Then, we’ll pass the value into a function that will set the theme accordingly.</p>
<p>We’ll get all the switches used in HTML using their class name and store those into a variable called <code>switches</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> switches = <span class="hljs-built_in">document</span>.getElementsByClassName(<span class="hljs-string">'switch'</span>);
</code></pre>
<p>Then we’ll loop over the switches and will listen for the click event on the switches. We’ll store the dataset value clicked inside a variable called <code>theme</code> in our case. I’ll be using a <code>for...in</code> loop here. If you are not familiar with <code>for...in</code> loop, check this <a target="_blank" href="https://www.studytonight.com/javascript/javascript-for-loop">article</a>.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i <span class="hljs-keyword">of</span> switches) {
  i.addEventListener(<span class="hljs-string">'click'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">let</span> theme = <span class="hljs-built_in">this</span>.dataset.theme;
    <span class="hljs-built_in">console</span>.log(theme);
  });
}
</code></pre>
<p>For your understanding, I’m first console logging the value that is clicked. Every time we click on a switch, it’ll <code>console.log</code> its custom data attribute value. You can see the gif to get an idea.</p>
<p><img src="https://i.ibb.co/M1HHCrQ/ezgif-com-crop.gif" alt /><em>Console Logging Values</em></p>
<p>Now we have to create a function called <code>setTheme</code>, which will set our theme. Let's see how it looks,</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">setTheme</span>(<span class="hljs-params">theme</span>) </span>{
  <span class="hljs-keyword">if</span> (theme == <span class="hljs-string">'light'</span>) {
    <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'switcher-id'</span>).href = <span class="hljs-string">'./themes/light.css'</span>;
  } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (theme == <span class="hljs-string">'sky'</span>) {
    <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'switcher-id'</span>).href = <span class="hljs-string">'./themes/sky.css'</span>;
  } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (theme == <span class="hljs-string">'purple'</span>) {
    <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'switcher-id'</span>).href = <span class="hljs-string">'./themes/purple.css'</span>;
  } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (theme == <span class="hljs-string">'dark'</span>) {
    <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'switcher-id'</span>).href = <span class="hljs-string">'./themes/dark.css'</span>;
  }
}
</code></pre>
<p>We are passing the parameter which we got from the <code>dataset</code> into this function. We can also achieve the same with a <code>switch case</code> statement. Our blank stylesheet in the HTML has the <code>switcher-id</code> id in it. We are targetting that element and adding an <code>href</code> to it. We are keeping all our theme styles in a separate folder called <code>themes</code>. And we have to call this function from the loop. So, our final code for the loops will be,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i <span class="hljs-keyword">of</span> switches) {
  i.addEventListener(<span class="hljs-string">'click'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">let</span> theme = <span class="hljs-built_in">this</span>.dataset.theme;
    <span class="hljs-built_in">console</span>.log(theme);
    setTheme(theme);
  });
}
</code></pre>
<p>I think it's making sense now. We are almost done. The final thing is to implement the local storage here. The stored data in local storage is saved across browser sessions, and it is pretty similar to session storage. Though, the significant difference between these is, local storage does not have any expiry. Local storage creates a <em>key-value</em> pair to store data.</p>
<p>The <code>localStorage.getItem</code>, with a name parameter, will create a key to save our values. In our example, we’ll be using a key called <code>theme</code>. So, our first step is to initiate it.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> style = <span class="hljs-built_in">localStorage</span>.getItem(<span class="hljs-string">'style'</span>);
</code></pre>
<p>The default property of a local storage element is <code>null</code>. So, our next step is to check if it’s <code>null</code> and if it is, we will set a theme value for it.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">if</span> (style == <span class="hljs-literal">null</span>) {
    setTheme(<span class="hljs-string">'light'</span>);
} <span class="hljs-keyword">else</span> {
    setTheme(style);
}
</code></pre>
<p>Here, if the value is <code>null</code>, we are setting the <em>light theme</em> as default. Otherwise, it'll set the value that is stored in the local storage.
And finally, We have to set the value as per the clicked switch. We’ll achieve this using the <code>setItem</code> property of local storage.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">localStorage</span>.setItem(<span class="hljs-string">'style'</span>, theme);
</code></pre>
<p>We’ll add this code before the end of the <code>setTheme</code> function. So, our complete <code>script.js</code> file will look like this,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> switches = <span class="hljs-built_in">document</span>.getElementsByClassName(<span class="hljs-string">'switch'</span>);

<span class="hljs-keyword">let</span> style = <span class="hljs-built_in">localStorage</span>.getItem(<span class="hljs-string">'style'</span>);

<span class="hljs-keyword">if</span> (style == <span class="hljs-literal">null</span>) {
  setTheme(<span class="hljs-string">'light'</span>);
} <span class="hljs-keyword">else</span> {
  setTheme(style);
}

<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i <span class="hljs-keyword">of</span> switches) {
  i.addEventListener(<span class="hljs-string">'click'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">let</span> theme = <span class="hljs-built_in">this</span>.dataset.theme;
    setTheme(theme);
  });
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">setTheme</span>(<span class="hljs-params">theme</span>) </span>{
  <span class="hljs-keyword">if</span> (theme == <span class="hljs-string">'light'</span>) {
    <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'switcher-id'</span>).href = <span class="hljs-string">'./themes/light.css'</span>;
  } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (theme == <span class="hljs-string">'sky'</span>) {
    <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'switcher-id'</span>).href = <span class="hljs-string">'./themes/sky.css'</span>;
  } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (theme == <span class="hljs-string">'purple'</span>) {
    <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'switcher-id'</span>).href = <span class="hljs-string">'./themes/purple.css'</span>;
  } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (theme == <span class="hljs-string">'dark'</span>) {
    <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'switcher-id'</span>).href = <span class="hljs-string">'./themes/dark.css'</span>;
  }
  <span class="hljs-built_in">localStorage</span>.setItem(<span class="hljs-string">'style'</span>, theme);
}
</code></pre>
<p>To learn more about the local storage web API, check this <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage">MDN</a> article. You can see the value of local storage from the <code>Inspect--&gt;Application--&gt;Local Storage</code>. We can check the gif below to see how it changes.
<img src="https://i.ibb.co/pfkwtKd/ezgif-com-crop-1.gif" alt /><em>Theme Changing</em></p>
<p>I hoped you learned something new in this article. Feel free to comment on your thoughts. And you can find the complete source code <a target="_blank" href="https://github.com/nemo0/JS-Theme-Switcher">here</a>.</p>
]]></content:encoded></item><item><title><![CDATA[The Three Dots of JavaScript: Rest and Spread Operator]]></title><description><![CDATA[The ES2018 introduced us with the concept of the rest and spread operators. Though the ES2015 already introduced us the spread operator, ES2018 further expanded the syntax by adding spread properties to object literals. Both of them become very usefu...]]></description><link>https://blog.nemotivity.dev/the-three-dots-of-javascript-rest-and-spread-operator</link><guid isPermaLink="true">https://blog.nemotivity.dev/the-three-dots-of-javascript-rest-and-spread-operator</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[100DaysOfCode]]></category><category><![CDATA[Programming Tips]]></category><dc:creator><![CDATA[Subha Chanda]]></dc:creator><pubDate>Sun, 11 Oct 2020 07:29:51 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1602401330443/BViwY4jnA.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>The ES2018 introduced us with the concept of the <code>rest</code> and <code>spread</code> operators. Though the ES2015 already introduced us the <code>spread</code> operator, ES2018 further expanded the syntax by adding spread properties to object literals. Both of them become very useful when we need to copy an array or object, or when we need to pass an indefinite amount of arguments into a function. Here, we'll discuss both the <code>rest</code> and <code>spread</code> operators.</p>
<h2 id="the-rest-operator">The Rest Operator 💆‍♂️</h2>
<p><img src="https://media.giphy.com/media/fdlcvptCs4qsM/giphy.gif" alt /><em>Gif from <a target="_blank" href="https://giphy.com">Giphy</a></em></p>
<p>ES2018 introduced us the concept of <code>rest</code> operator. The <code>rest</code> operator looks like any regular argument except that it has three dots(<code>...</code>) in front of it. The <code>rest</code> operator will gather all the elements passed in the function argument and will create an array with it. Let's see it in action. </p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">letsRest</span>(<span class="hljs-params">...args</span>) </span>{
    <span class="hljs-built_in">console</span>.log(args);
}

letsRest(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>); <span class="hljs-comment">// [1, 2, 3, 4]</span>
</code></pre>
<p>We are passing the arguments as rest parameters with the help of <code>...args</code> argument in the function definition. The parameters passed in the function will now create an array.</p>
<p>We can work with this array now. Any array methods can also be implemented in this array. And also, our function now can take an indefinite amount of arguments. Now, let's build a function with the help of rest parameters that will return the sum of all the arguments passed.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sumAll</span>(<span class="hljs-params">...args</span>) </span>{
    <span class="hljs-keyword">let</span> sum = <span class="hljs-number">0</span>;
    <span class="hljs-keyword">for</span>(<span class="hljs-keyword">let</span> arg <span class="hljs-keyword">of</span> args){
        sum = sum + arg;
    }
    <span class="hljs-keyword">return</span> sum;
}

sumAll(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>); <span class="hljs-comment">//6</span>
sumAll(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>); <span class="hljs-comment">//10</span>
</code></pre>
<p>We are using the <code>rest</code> operator to pass arguments and using a <code>for-of</code> loop to loop through all the elements and adding them into a variable sum. We can also pass regular parameters along with <code>rest</code> parameters in a function.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">iLove</span>(<span class="hljs-params">name, ...items</span>)</span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`I am <span class="hljs-subst">${name}</span>, and I love <span class="hljs-subst">${items}</span>`</span>)
}
iLove(<span class="hljs-string">"nemo"</span>, <span class="hljs-string">"apple"</span>, <span class="hljs-string">"banana"</span>, <span class="hljs-string">"lemon"</span>) 
<span class="hljs-comment">//I am nemo, and I love apple,banana,lemon</span>
</code></pre>
<p>Here, we are combining normal parameters along with <code>rest</code> parameters.
One thing to keep in mind when working with <code>rest</code> operators is that the argument with <code>rest</code> operator has to be the last argument passed. Because its job is to collect all the remaining arguments passed. So, the above example will work perfectly. 
But in the below code, we are passing a third argument after the <code>rest</code> parameter. This will return an error <code>Uncaught SyntaxError: Rest parameter must be the last formal parameter</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">iLove</span>(<span class="hljs-params">name, ...items, age</span>)</span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`I am <span class="hljs-subst">${name}</span>, I am <span class="hljs-subst">${age}</span> and I love <span class="hljs-subst">${items}</span>`</span>)
}
iLove(<span class="hljs-string">"nemo"</span>, <span class="hljs-string">"apple"</span>, <span class="hljs-string">"banana"</span>, <span class="hljs-string">"lemon"</span>, <span class="hljs-number">18</span>);
</code></pre>
<h2 id="the-spread-operator">The Spread Operator 🧈</h2>
<p><img src="https://media.giphy.com/media/ZAqPc6fdwwo97X8HNP/giphy.gif" alt /><em> Gif from <a target="_blank" href="https://giphy.com">Giphy</a></em></p>
<p>As the name suggests, the <code>spread</code> operator spreads the elements. It looks exactly like the <code>rest</code> operator. But, it works like a complement to the <code>rest</code> operator. The <code>rest</code> operator is defined in the function definition. </p>
<p>The <code>spread</code> operator will expand an array, string or object. Let's say, we want to clone all the values inside an array into a new one. Without the <code>spread</code> operator, we'll have to manually define all the values inside the new array like this,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> arr = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>];
<span class="hljs-keyword">let</span> arr2 = [arr[<span class="hljs-number">0</span>], arr[<span class="hljs-number">1</span>], arr[<span class="hljs-number">2</span>], <span class="hljs-number">4</span>, <span class="hljs-number">5</span>, <span class="hljs-number">6</span>]
</code></pre>
<p>Do you think this is an efficient solution? This needs a hell lot of writing. The <code>spread</code> operator makes it much easy to do such an operation.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> arr = [<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>];
<span class="hljs-keyword">let</span> arr2 = [...arr, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>, <span class="hljs-number">6</span>];

<span class="hljs-built_in">console</span>.log(arr2); <span class="hljs-comment">//[ 1, 2, 3, 4, 5, 6 ]</span>
</code></pre>
<p>We can also copy an array by simply using,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> arr3 = [...arr];
</code></pre>
<p>We can even clone an object with this syntax,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> obj = {
    <span class="hljs-number">1</span>: 👩,
    <span class="hljs-number">2</span>: 👨,
    <span class="hljs-number">3</span>: 🧑
}
<span class="hljs-keyword">const</span> obj2 = {...obj};

<span class="hljs-built_in">console</span>.log(obj2); <span class="hljs-comment">//{ 1: 👩, 2: 👨, 3: 🧑 }</span>
</code></pre>
<h2 id="conclusion">Conclusion 🙇‍♂️</h2>
<p>Both the <code>rest</code> and <code>spread</code> operator might seem confusing because both of them uses a ... syntax. So, how do we know where to use what? I remember it like this,</p>
<blockquote>
<p>Rest <strong>Packs</strong> the Elements, Spread <strong>Unpacks</strong> the Elements.</p>
</blockquote>
<p>Depending on your use case, you can choose which one you need.</p>
<hr />
<p>If you liked this article, leave a ❤ and a comment. You can also follow me on <a target="_blank" href="https://twitter.com/Ami_Subha">twitter</a>.</p>
]]></content:encoded></item><item><title><![CDATA[A Beginner-Friendly Intro to JavaScript Event Propagation]]></title><description><![CDATA[Introduction
Event propagation is an important concept when dealing with JavaScript events, and it is also crucial in terms of interviews. So, in this article, I'll try to help you understand the concept of Event Propagation. 
Event Propagation
To pu...]]></description><link>https://blog.nemotivity.dev/a-beginner-friendly-intro-to-javascript-event-propagation</link><guid isPermaLink="true">https://blog.nemotivity.dev/a-beginner-friendly-intro-to-javascript-event-propagation</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[programming languages]]></category><dc:creator><![CDATA[Subha Chanda]]></dc:creator><pubDate>Thu, 01 Oct 2020 06:24:35 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1601457026141/sE5jvNDzE.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="introduction">Introduction</h2>
<p>Event propagation is an important concept when dealing with JavaScript events, and it is also crucial in terms of interviews. So, in this article, I'll try to help you understand the concept of <strong>Event Propagation</strong>. </p>
<h2 id="event-propagation">Event Propagation</h2>
<p>To put it in easy words,</p>
<blockquote>
<p>The parent elements of a child will also receive events that happen to the children.</p>
</blockquote>
<p> The easy words seem tough? Don't worry. Let's understand it with example. </p>
<pre><code class="lang-javascript">&lt;div <span class="hljs-class"><span class="hljs-keyword">class</span></span>=<span class="hljs-string">"container"</span>&gt;
      <span class="xml"><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">button</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">id</span>=<span class="hljs-string">"item"</span>&gt;</span>Some Text<span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span>
            <span class="hljs-tag">&lt;/<span class="hljs-name">button</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>
&lt;/div&gt;
</code></pre>
<p>Look at the above snippet. We have a <code>a</code> tag nested inside a <code>button</code> which is inside a list item. Suppose we are clicking the link inside the button. The click will generate a <code>click</code> event for the <code>a</code> tag, and it will start to propagate through all the outer elements.  To get a better idea about propagation, let's understand the plain English meaning of the word "propagate". It basically means <em>"transmitting from one generation to another"</em> or <em>"moving from one element to others"</em>. So, when I say "it will start to propagate through all the outer elements", it means the event will move from one element to the other.</p>
<p><strong>Event Propagation</strong> is the order in which the propagation happens. JavaScript has two types of Event Propagation</p>
<ul>
<li>Bubbling</li>
<li>Capturing</li>
</ul>
<p>Bubbling means that the event propagation will start from the item that was clicked and will bubble up to the root node, starting from the closest one.</p>
<p>Capturing is the opposite of bubbling. It starts from the root element and then propagates by capturing all the child element until it reaches the target element that was clicked.    </p>
<h2 id="event-bubbling">Event Bubbling</h2>
<p>It is the default event propagation in JavaScript. As we understand earlier, bubbling starts from the element that was clicked and then it propagates all the way, up to the root. To see it in action, let's add some JavaScript to the HTML that we already have.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> item = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'item'</span>);
<span class="hljs-keyword">let</span> button = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'button'</span>);
<span class="hljs-keyword">let</span> list = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'li'</span>);

<span class="hljs-comment">// Event Bubbling</span>
item.addEventListener(<span class="hljs-string">'click'</span>, <span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Clicked on the Item'</span>);
});

button.addEventListener(<span class="hljs-string">'click'</span>, <span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Clicked on the Button'</span>);
});

list.addEventListener(<span class="hljs-string">'click'</span>, <span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Clicked on the li'</span>);
});
</code></pre>
<p>First of all, we are selecting the <code>item</code> id, <code>button</code> and the <code>li</code> Then, we are adding some event handlers to them. We are listening to the click event here. Callback functions are passed to each event handlers, which will console log the text that we are giving each time the event handler listens.</p>
<p>Now, if we click the <code>a</code> tag inside the button, we will see that our console logs out the output in the exact below order.</p>
<pre><code class="lang-bas">Clicked on the Item
Clicked on the Button
Clicked on the li
</code></pre>
<p>This is happening because the event starts propagating from the item that was clicked to the outer parents. This will bubble up to the root element. But because we do not have any event handlers associated with those, we can't see it.</p>
<h2 id="event-capturing">Event Capturing</h2>
<p>Now let's see an example of event capturing. The <code>addEventListener</code> can take a third parameter. It is a <code>Boolean</code> value which specifies whether the event capturing is true or false. The default value of the parameter is <code>false</code>. This is the reason why event bubbling happens by default. There can be situations where we want to fire the outer elements first before reaching the origin. So, to implement event capturing, we just have to put the third parameter. And our same above code will be like this - </p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> item = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'item'</span>);
<span class="hljs-keyword">let</span> button = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'button'</span>);
<span class="hljs-keyword">let</span> list = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'li'</span>);

<span class="hljs-comment">// Capturing</span>
item.addEventListener(
  <span class="hljs-string">'click'</span>,
  <span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Clicked on the Item'</span>);
  },
  <span class="hljs-literal">true</span>
);

button.addEventListener(
  <span class="hljs-string">'click'</span>,
  <span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Clicked on the Button'</span>);
  },
  <span class="hljs-literal">true</span>
);

list.addEventListener(
  <span class="hljs-string">'click'</span>,
  <span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Clicked on the li'</span>);
  },
  <span class="hljs-literal">true</span>
);
</code></pre>
<p>Now, clicking the <code>a</code> tag will console log the output in the exact below order,</p>
<pre><code class="lang-bash">Clicked on the li
Clicked on the Button
Clicked on the Item
</code></pre>
<p>The capturing starts from the root element and then comes to the origin. Because only the topmost <code>li</code> has an event handler, so it starts logging from the <code>li</code> and comes down to the origin which is the <code>item</code>.</p>
<h2 id="the-stoppropagation-method">The <code>stopPropagation</code> Method</h2>
<p>There may be cases where you don't want the propagation to occur. In such cases, we can use the <code>stopPropagation()</code> method into the callback function to stop it. For example, suppose in our first code, we don't want to propagate the event in the third handler. To prevent the propagation, we specify <code>event.stopPropagation()</code> into the callback of the second handler. Reaching the second handler, the propagation would stop. </p>
<h3 id="the-code">The Code</h3>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> item = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'item'</span>);
<span class="hljs-keyword">let</span> button = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'button'</span>);
<span class="hljs-keyword">let</span> list = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'li'</span>);

<span class="hljs-comment">// Event Bubbling</span>
item.addEventListener(<span class="hljs-string">'click'</span>, <span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Clicked on the Item'</span>);
});

button.addEventListener(<span class="hljs-string">'click'</span>, <span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Clicked on the Button'</span>);
  event.stopPropagation();
});

list.addEventListener(<span class="hljs-string">'click'</span>, <span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Clicked on the li'</span>);
});
</code></pre>
<p>If you click on the button now and check the console log, the output will be,</p>
<pre><code class="lang-bash">Clicked on the Item
Clicked on the Button
</code></pre>
<p>The event stops propagating after reaching the second handler. The same can also be applied for the capturing.</p>
<hr />
<p>I hope this article helped you to clarify the JavaScript propagation. If this helped you, click the ❤ and leave a comment. You can also follow me on <a target="_blank" href="https://twitter.com/Ami_Subha">twitter</a>.</p>
<p>Also, check this article about <a target="_blank" href="https://nemo.hashnode.dev/an-introduction-to-recursion-using-javascript-ckfgx2nrq001xols17h787f87">Recursion</a>.</p>
]]></content:encoded></item><item><title><![CDATA[An Introduction to Recursion using JavaScript]]></title><description><![CDATA[Recursion is an essential topic in the area of functional programming. Newbie programmers often find it challenging to understand what it is and how it works. So, I'll try to make recursion easy for you. At least, will try to clear your basic underst...]]></description><link>https://blog.nemotivity.dev/an-introduction-to-recursion-using-javascript</link><guid isPermaLink="true">https://blog.nemotivity.dev/an-introduction-to-recursion-using-javascript</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[programming]]></category><dc:creator><![CDATA[Subha Chanda]]></dc:creator><pubDate>Thu, 24 Sep 2020 14:33:46 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1600881752712/nY4UPmV6C.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Recursion is an essential topic in the area of functional programming. Newbie programmers often find it challenging to understand what it is and how it works. So, I'll try to make recursion easy for you. At least, will try to clear your basic understanding about the topic. So, let's get started 😁. 
<img src="https://media.giphy.com/media/XkDyB1jCZMxUs/giphy.gif" alt /> <em>Gif from <a target="_blank" href="https://giphy.com/">Giphy</a></em></p>
<h2 id="what-is-recursion">What is Recursion?</h2>
<p>If you search "recursion" in Google, every time you'll get a message "Did you mean: <strong><em>recursion</em></strong>". And every time you click on the <em>Did you mean</em> link, it'll again show you the same. And this is after all what recursion actually means, Calling something again and again.</p>
<p><img src="https://i.ibb.co/8BLS70r/recursion-1.png" alt /></p>
<p>In terms of computer programming, a recursive function is a function that calls itself until it satisfies some exit condition. Otherwise, we'll be stuck into an infinite loop or in case of JavaScript, the call stack will be overflowed. Let's see an example to understand it better. 
We all know what a factorial is. We get factorial of a number if we continue multiplying the number itself with a value smaller than it until we reach 1.
For example, the factorial for number 3 will be, 3 <em> 2 </em> 1 = 6.
Here's a function that returns the factorial of a number.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">factorial</span>(<span class="hljs-params">r</span>) </span>{
    <span class="hljs-keyword">if</span>(r &lt;= <span class="hljs-number">0</span>) <span class="hljs-keyword">return</span> <span class="hljs-number">1</span>;
    <span class="hljs-keyword">else</span> <span class="hljs-keyword">return</span> r*factorial(r<span class="hljs-number">-1</span>);
}
<span class="hljs-built_in">console</span>.log(factorial(<span class="hljs-number">3</span>)); <span class="hljs-comment">//6</span>
</code></pre>
<p>We are passing the number with the parameter r. How is this a recursive function? If you look at the else condition, you'll find that it is calling the function itself until it matches the exit condition which is r &lt;= 0. 
You can imagine that the same can be achieved using a loop. And you are right. Here is the same function using a loop.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">factorial</span>(<span class="hljs-params">r</span>) </span>{
    <span class="hljs-keyword">let</span> factor = <span class="hljs-number">1</span>;
    <span class="hljs-keyword">for</span>(<span class="hljs-keyword">let</span> i = r; i &gt; <span class="hljs-number">1</span>; i--) {
        factor *= i;
    }
    <span class="hljs-keyword">return</span> factor;
}
<span class="hljs-built_in">console</span>.log(factorial(<span class="hljs-number">3</span>)); <span class="hljs-comment">//6</span>
</code></pre>
<p>Rather, using a loop will be a better choice in case of such small functions. In JavaScript running a loop is generally cheaper than calling a function multiple times. The time complexity will be higher with a recursive function. But there are multiple instances where loops are not worth. They make the function more complex. And, any recursive function can be implemented using loops. 
Now that we know what a recursive function is let's move on to building a recursive function by ourselves. </p>
<h1 id="creating-a-recursive-function">Creating a Recursive Function</h1>
<p>One most important thing to keep in mind while working with recursive function is <strong>to Declare a termination condition</strong>. Otherwise, our function will overflow the call stack. </p>
<p>How do we declare a termination condition? Most simply, we can put it inside an if statement. </p>
<p>Here in this example, suppose we want to write a recursive function that returns the sum of a given range. So, if we pass 3, it will output the sum of the range from 1 to 3, i.e., 1 + 2 + 3 = 6.</p>
<p><strong>Step 1:</strong> Declare a function name. It'll take a single parameter which will specify the range. Feel free to use arrow functions if you want.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sumRange</span>(<span class="hljs-params">r</span>)</span>{

}
</code></pre>
<p><strong>Step 2:</strong> Declare a termination statement. When do we want this function to exit? When our range is 0, right? </p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sumRange</span>(<span class="hljs-params">r</span>) </span>{
    <span class="hljs-keyword">if</span>(r &lt;= <span class="hljs-number">0</span>) <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
}
</code></pre>
<p><strong>Step 3:</strong> Your logic where the magic happens. </p>
<p>What do we want to achieve here? We want to do (current range + (range-1)) in a loop until our range becomes 0. We are getting the current range from r. How do we get the (range-1)? We call the function again and again by passing the parameter as (r-1).</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sumRange</span>(<span class="hljs-params">r</span>) </span>{
    <span class="hljs-keyword">if</span>(r &lt;= <span class="hljs-number">0</span>) <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;
    <span class="hljs-keyword">return</span> r+sumRange(r<span class="hljs-number">-1</span>);
}
</code></pre>
<h2 id="the-function-flow">The function flow:</h2>
<ol>
<li><p>First, we call our function by passing the value 3.</p>
<pre><code class="lang-bash">sumRange(3);
</code></pre>
</li>
<li><p>The above call runs the function. First, it checks the if statement. Finding it false, it'll continue to work with the else. At else, we return <code>3</code> + the value of <code>sumRange(3-1)</code>.</p>
<pre><code class="lang-bash"><span class="hljs-built_in">return</span> 3 + sumRange(2);
</code></pre>
</li>
<li><p>The above logic also works here. Except that, this time, our range was <code>2</code>. So, it'll return <code>2 + sumRange(2-1)</code></p>
<pre><code class="lang-bash"><span class="hljs-built_in">return</span> 2 + sumRange(1);
</code></pre>
</li>
<li><p>Same happens again. Now the range is <code>1</code>. So the returning <code>sumRange</code> will be <code>(1-1)</code>. </p>
<pre><code class="lang-bash"><span class="hljs-built_in">return</span> 1 + sumRange(0);
</code></pre>
<p>When the range becomes 0, our if condition will run and it will return 0. </p>
</li>
</ol>
<p>Now that all our function calls has returned a value, everything will start to unwind. The innermost function will return first. </p>
<p>So, <code>sumRange(0)</code> will return 0.</p>
<p><code>sumRange(1)</code> will return <code>1 + sumRange(0)</code> or, <code>1 + 0 = 1</code></p>
<p><code>sumRange(2)</code> will return <code>2 + sumRange(1)</code> or, <code>2 + 1 + 0 = 3</code></p>
<p><code>sumRange(3)</code> will return <code>3 + sumRange(2)</code> or, <code>3 + 2 + 1 + 0 = 6</code> and we get the answer 6 and we are done. </p>
<hr />
<p>If you read the article to this point, a big thank you 😊. I hope you get some basic understanding of how recursion works and how to write a recursive function. </p>
]]></content:encoded></item><item><title><![CDATA[Why You Should Take the #2Articles1Week Challenge]]></title><description><![CDATA[Introduction
Recently I've completed the #2Articles1Week Challenge for four straight weeks here on Hashnode. And there are a few things I learned from the challenge which I want to share with you. However, I am not an expert blogger. But I felt that ...]]></description><link>https://blog.nemotivity.dev/why-you-should-take-the-2articles1week-challenge</link><guid isPermaLink="true">https://blog.nemotivity.dev/why-you-should-take-the-2articles1week-challenge</guid><category><![CDATA[2Articles1Week]]></category><category><![CDATA[Blogging]]></category><category><![CDATA[Programming Blogs]]></category><dc:creator><![CDATA[Subha Chanda]]></dc:creator><pubDate>Thu, 27 Aug 2020 13:17:04 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1598533822554/wsvzvgcWp.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="introduction">Introduction</h2>
<p>Recently I've completed the #2Articles1Week Challenge for four straight weeks here on Hashnode. And there are a few things I learned from the challenge which I want to share with you. However, I am not an expert blogger. But I felt that people like me, who overthink a lot before doing anything, might get inspiration from this post. </p>
<h2 id="my-first-encounter-with-hashnode">My First Encounter with Hashnode</h2>
<p>The first time I heard the name Hashnode was in the Lockdownconf organized by freecodecamp. So, I visited the Hashnode portal just out of curiosity. I created an account. Till then, I didn't think of posting a single article on my blog. The first thing that caught my eyes was the design of hashnode. The simple design of the blogs looks cool to me. Also, it's free! And, you can set up your blog with your domain! How awesome is that! Also, they have a discord server where you can get instant help if you face any problems. Even many paid services do not provide such a service to their users! 😉 </p>
<h2 id="the-challenge">The Challenge</h2>
<p>I started writing on my blog when I heard about the #2Articles1Week challenge. Before that, I was reading posts published by others. 
I thought, at least, let's try to write something. And I started writing for my blog.</p>
<p><img src="https://media.giphy.com/media/cOSp689PAhHUI/giphy.gif" alt /><em>GIF from <a target="_blank" href="https://giphy.com/">Giphy</a></em></p>
<h2 id="the-problems-the-opportunities">The Problems! The Opportunities!</h2>
<ul>
<li><p><strong>The Language:</strong> The first problem when I started writing was the language barrier. My native language is Bengali. I've studied all my life in Bengali until college. So my grip on English is not very good. The writing was an excellent opportunity for me to experiment with the language. After writing in English for more than a month now, I can confidently say that my English has significantly improved. </p>
</li>
<li><p><strong>Markdown! What the Heck!</strong> Before Hashnode, I never used a Markdown editor. The places where I wrote articles before usually use some WYSIWYG editor. But after exploring the power of Markdown, now I feel like why all the programming blogs don't use it! It is so easy and convenient, especially when writing code! I also prefer writing my articles offline first. So, I downloaded this fantastic markdown editor called <em><a target="_blank" href="https://typora.io/">Typora</a></em>.</p>
</li>
<li><p><strong>What should I Write?</strong> A big question for a beginner like me. Thinking and writing about two articles in a week for a month is a tough job, to be honest. Though, there are some incredible people like <a class="user-mention" href="https://hashnode.com/@dailydevtips">Daily Dev Tips</a>  who have decided to take this challenge to another level and have decided to go for a #7Articles1Week! 😎<br />This challenge opened a new angle to my thinking skills. It has become much easier for me to think about a topic to write. And also, hashnode has a request for article(<a target="_blank" href="https://hashnode.com/rfa">rfa</a>) section. We can always choose a topic from there as well.</p>
</li>
<li><p><strong>Researching the Topic:</strong> When you are writing something to explain things to someone else, you've to have a good understanding of the topic. I study the subjects I write from various sources to clear my concepts more. And try to make it easily understandable for the readers. And through this, I also got the opportunity to know about the topics in-depth! If you don't like researching, I'd suggest you to start writing about it. Make your <em>personal</em> notes. You'll find that researching something new you learned has become second nature for you.</p>
</li>
<li><p><strong>Who Will Read My Articles?</strong> It is something that I was never worried. My sole intention in writing is to improve myself. My thought about this is, </p>
<blockquote>
<p>Either We Win, Or We <em>Learn</em>.</p>
</blockquote>
<p>And learning is always my topmost priority. 😁 
But obviously, you need someone to see your work. After all, you are devoting a fair amount of time to this. Here comes the most beautiful part of the Hashnode community. It has its own userbase. So, you'll definitely get a fair amount of traffic from there. Also, It's like a family. Many helpful people are around here, who are willing to read and suggest about your article. Not everyone knows about everything. Maybe your explanation helped someone to understand something better. Even if a single person benefits from your writing, it's an outstanding achievement, I believe.</p>
</li>
<li><p><strong>Pushing the Limits.</strong> There were multiple times when I didn't felt like writing a single line at all. But the challenge and the dedication to this challenge made me push my limits. Even in such situations, I managed to write an article. Pushing myself helped me increase my willpower. Sometimes, it is vital to challenge your potentials. It teaches you more about yourself. </p>
</li>
<li><p><strong>THE BADGE!</strong> And finally, the biggest achievement of doing this challenge is the <strong>badge</strong> 😍! After completing this challenge, you'll be awarded the <strong><em>GOLD BADGE</em></strong>. And this honor will be showcased in your blog!
<img src="https://i.ibb.co/T4tYSNH/badges.png" alt /></p>
</li>
</ul>
<h2 id="final-words">Final Words</h2>
<p>In every way, this is a win-win for all. And if you are not motivated yet to start, <a target="_blank" href="https://www.freecodecamp.org/news/every-developer-should-have-a-blog-heres-why-and-how-to-stick-with-it-5fd55a247fbf/">here's</a> a great article on freecodecamp about why every programmer should have a blog.</p>
<p>I shared with you what I learned from the challenge. And I hope you'll also find it motivating to take the challenge. And, if you are the one who has successfully completed it, share your learnings from the challenge! 😀</p>
]]></content:encoded></item><item><title><![CDATA[Let's talk about Math.ceil, Math.floor, and Math.round 🌿]]></title><description><![CDATA[Introduction
We all have learned about rounding off numbers in our school. We usually increase the integer if its value is >=.5 and decrease it, if it is <= .4.

1.5 ≈ 2
1.4 ≈ 1

We all know JavaScript has a built-in object called Math, which has pro...]]></description><link>https://blog.nemotivity.dev/lets-talk-about-mathceil-mathfloor-and-mathround</link><guid isPermaLink="true">https://blog.nemotivity.dev/lets-talk-about-mathceil-mathfloor-and-mathround</guid><category><![CDATA[JavaScript]]></category><dc:creator><![CDATA[Subha Chanda]]></dc:creator><pubDate>Sat, 22 Aug 2020 16:37:58 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1598114170225/ZYW09ru63.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="introduction">Introduction</h2>
<p>We all have learned about rounding off numbers in our school. We usually increase the integer if its value is &gt;=.5 and decrease it, if it is &lt;= .4.</p>
<blockquote>
<p>1.5 ≈ 2</p>
<p>1.4 ≈ 1</p>
</blockquote>
<p>We all know JavaScript has a built-in object called Math, which has properties and methods for mathematical constants and functions. </p>
<p>We have three methods that are mostly used to round off a number in JS, i.e., <code>Math.ceil()</code>, <code>Math.floor()</code>, <code>Math.round()</code>. Let's explore them in this article.</p>
<p><img src="https://media.giphy.com/media/U5D3QY0QQWsR0nhwmg/giphy.gif" alt /></p>
<h2 id="mathceil">🎳 Math.ceil</h2>
<p><code>Math.ceil</code> function in JavaScript is used to round of a number that is passed into it to its nearest integer in upward direction of rounding. What to I mean by upward direction? Towards the greater value. <code>Math.ceil()</code> takes only one parameter that is the value to be rounded.  So, if we have a value of 1.4, <code>Math.ceil()</code> will round off it to 2.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">Math</span>.ceil(<span class="hljs-number">1.4</span>)); 
<span class="hljs-comment">//2</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">Math</span>.ceil(<span class="hljs-number">1.6</span>)); 
<span class="hljs-comment">// 2</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">Math</span>.round(<span class="hljs-number">-1.4</span>));
<span class="hljs-comment">// 1</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">Math</span>.round(<span class="hljs-number">-1.6</span>));
<span class="hljs-comment">// 1</span>
</code></pre>
<p><img src="https://upload.wikimedia.org/wikipedia/commons/thumb/f/fa/Ceiling_function.svg/800px-Ceiling_function.svg.png" alt /><em>Photo from <a target="_blank" href="https://en.wikipedia.org/wiki/Floor_and_ceiling_functions#/media/File:Ceiling_function.svg">Wikipedia</a></em></p>
<h2 id="mathfloor">🎳 Math.floor()</h2>
<p>Where the <code>Math.ceil</code> method returns the smallest integer greater than or equal to the value we pass, <code>Math.floor</code> returns the largest or equal integer less than the given value. It also takes a single parameter. </p>
<p><img src="https://upload.wikimedia.org/wikipedia/commons/thumb/e/e1/Floor_function.svg/800px-Floor_function.svg.png" alt /><em>Photo from <a target="_blank" href="https://en.wikipedia.org/wiki/Floor_and_ceiling_functions#/media/File:Floor_function.svg">Wikipedia</a></em></p>
<p>So, if we pass the same value 1.4 in <code>Math.floor</code>, we'll get 1 in return. Even if we pass 1.6, we'll also get 1.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">Math</span>.floor(<span class="hljs-number">1.4</span>));
<span class="hljs-comment">// 1</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">Math</span>.floor(<span class="hljs-number">1.6</span>));
<span class="hljs-comment">// 1</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">Math</span>.floor(<span class="hljs-number">-1.4</span>));
<span class="hljs-comment">// -2</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">Math</span>.floor(<span class="hljs-number">-1.6</span>));
<span class="hljs-comment">// -2</span>
</code></pre>
<h2 id="mathround">🎳 Math.round()</h2>
<p><code>Math.round()</code> rounds off the number depending on the fractional part of the number. So, if the fractional part is &gt;=.5, it'll return the smallest integer greater than the passed value and if the number is &lt;=.4 we'll get the largest integer smaller than the number we pass. </p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">Math</span>.round(<span class="hljs-number">1.4</span>));
<span class="hljs-comment">// 1</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">Math</span>.round(<span class="hljs-number">1.6</span>));
<span class="hljs-comment">// 2</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">Math</span>.round(<span class="hljs-number">1.5</span>)); 
<span class="hljs-comment">// 2</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">Math</span>.round(<span class="hljs-number">-1.4</span>));
<span class="hljs-comment">// -1</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">Math</span>.round(<span class="hljs-number">-1.6</span>));
<span class="hljs-comment">// -2</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">Math</span>.round(<span class="hljs-number">-1.5</span>));
<span class="hljs-comment">// 2</span>
</code></pre>
<p>So, Math.round() can go both upward and downward depending on the fractional Part.</p>
<p><img src="https://i.ibb.co/YcZbNhd/mathfloor.png" alt /></p>
<h2 id="mathtrunc">🎳 Math.trunc()</h2>
<p>There's another method available in JS Math object that is <code>Math.trunc()</code>. <code>Math.trunc()</code> returns the integer part of a number by removing any fractional part of the number.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">Math</span>.trunc(<span class="hljs-number">1.4</span>));
<span class="hljs-comment">// 1</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">Math</span>.trunc(<span class="hljs-number">1.6</span>));
<span class="hljs-comment">// 1</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">Math</span>.trunc(<span class="hljs-number">-1.4</span>));
<span class="hljs-comment">// 1</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">Math</span>.trunc(<span class="hljs-number">-1.6</span>));
<span class="hljs-comment">// 1</span>
</code></pre>
<h2 id="conclusion">Conclusion</h2>
<p>Rounding off numbers is an essential part of programming. I hope this article revisited your memories about different built-in rounding off methods we have in JavaScript. Leave an ❤ if you found this article helpful. 😊</p>
]]></content:encoded></item><item><title><![CDATA[Our Favourite VS Code Extensions! 🚀]]></title><description><![CDATA[Visual Studio Code has become one of the highly used IDE now. I believe most of the people reading this article use VS Code daily. Here are some useful VSCode extensions that we use daily. If your favourites aren't listed here, comment down below. Wo...]]></description><link>https://blog.nemotivity.dev/our-favourite-vs-code-extensions</link><guid isPermaLink="true">https://blog.nemotivity.dev/our-favourite-vs-code-extensions</guid><category><![CDATA[Visual Studio Code]]></category><category><![CDATA[2Articles1Week]]></category><dc:creator><![CDATA[Subha Chanda]]></dc:creator><pubDate>Sun, 09 Aug 2020 07:27:36 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1597069432388/a_0C4MvoQ.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Visual Studio Code has become one of the highly used IDE now. I believe most of the people reading this article use VS Code daily. Here are some useful VSCode extensions that we use daily. If your favourites aren&#39;t listed here, comment down below. Would love to add those to this list. 😎</p>
<p><img src="https://media.giphy.com/media/l0HlzApLBjaKNT25G/giphy.gif" alt="Gif from Giphy"> <em>Gif from <a target='_blank' rel='noopener'  href="https://giphy.com/">Giphy</a></em></p>
<h2 id="theme-and-icon-pack-">Theme and Icon Pack 🚚</h2>
<p>The visual appearance of the IDE is important to me. I use the <a target='_blank' rel='noopener'  href="https://marketplace.visualstudio.com/items?itemName=Equinusocio.vsc-material-theme">Material Theme</a> by Mattia Astorino and along with the theme, I use the <a target='_blank' rel='noopener'  href="https://marketplace.visualstudio.com/items?itemName=PKief.material-icon-theme">Material Icon Theme</a> by Philipp Kief. I use the Material Theme Ocean High Contrast Color theme for the editor.</p>
<p>Another extension I use to beautify my editor is the <a target='_blank' rel='noopener'  href="https://marketplace.visualstudio.com/items?itemName=naumovs.color-highlight">Color Highlight</a>. It just highlights the colors in my code.</p>
<p><img src="https://i.ibb.co/kx90Wwc/3.png" alt=""></p>
<h2 id="code-formatter-and-autocomplete-">Code Formatter and AutoComplete 🛺</h2>
<ul>
<li><a target='_blank' rel='noopener'  href="https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode">Prettier</a>, obviously! Who doesn&#39;t use this! Prettier is an awesome extension that format the code beautifully. The format on save feature is always on in my editor. I prefer to use 2 spaces and single quotes. I&#39;ve updated the prettier settings accordingly and now each time I save my document, it formats my code with 2 spaces and single quotes. It also adds the semicolons at the end which I forgot to put every time. 
<img src="https://scottsauber.files.wordpress.com/2017/06/prettier1.gif?w=809" alt=""> <em>Gif from <a target='_blank' rel='noopener'  href="https://scottsauber.com/2017/06/10/prettier-format-on-save-never-worry-about-formatting-javascript-again/">https://scottsauber.com</a></em></li>
<li><a target='_blank' rel='noopener'  href="https://marketplace.visualstudio.com/items?itemName=formulahendry.auto-rename-tag">Auto Rename Tag</a> by Jun Han! This does exactly what it says. It automatically renames the corresponding tag. It is useful to speed up the workflow. </li>
<li><a target='_blank' rel='noopener'  href="https://marketplace.visualstudio.com/items?itemName=ecmel.vscode-html-css">HTML CSS Support</a> by Ecmel is the next one in my list. It gives the ability to auto-complete the class and ID attributes in the HTML file. It&#39;ll show all the classes and ids to the HTML file which you have defined in your CSS file.</li>
<li><a target='_blank' rel='noopener'  href="https://marketplace.visualstudio.com/items?itemName=CoenraadS.bracket-pair-colorizer-2">Bracker Pair Colorizer 2</a> allows the matching brackets to be identified with colors. You can also specify which colors to use to colorize your bracket pairs.</li>
</ul>
<h2 id="miscellaneous-">Miscellaneous 🚡</h2>
<ul>
<li><a target='_blank' rel='noopener'  href="https://marketplace.visualstudio.com/items?itemName=ritwickdey.LiveServer">Live Server</a> by Ritwick Dey. I think most of you know what this extension does. It creates a local server which supports live reload. Kind of like Nodemon for static pages.</li>
<li><a target='_blank' rel='noopener'  href="https://marketplace.visualstudio.com/items?itemName=WallabyJs.quokka-vscode">Quokka</a>. I&#39;ve recently started using it and it already seems awesome to me. Quokka is used for testing JavaScript code in the Visual Studio code editor. With Quokka, you don&#39;t have to <code>console.log()</code> everything. It works like a live server for your JavaScript or TypeScript code. <img src="https://quokkajs.com/assets/img/main-video.gif" alt=""><em>Gif from <a target='_blank' rel='noopener'  href="https://quokkajs.com/docs/index.html">Quokkajs.com</a></em></li>
<li><a target='_blank' rel='noopener'  href="https://marketplace.visualstudio.com/items?itemName=ritwickdey.live-sass">Live Sass Compiler</a> is also an awesome extension if you are working with Sass. I used it before. It compiles your Sass file in the runtime. It is based on the Libsass library. But <code>libsass</code> doesn&#39;t support some latest Sass features like <code>@use</code>. So instead of using this, I&#39;ve started to use their official <code>npm</code> package with the command line.</li>
</ul>
<h2 id="some-more-useful-extensions-shared-by-the-awesome-tapas-adhikary-atapas-">Some More Useful Extensions Shared By the Awesome <a class="user-mention" href="https://hashnode.com/@atapas">Tapas Adhikary</a></h2>
<ul>
<li><a target='_blank' rel='noopener'  href="https://marketplace.visualstudio.com/items?itemName=doi.fileheadercomment">File Header Comment</a> allows you to add a timestamp, copyright or any other important information you want to add to the file as a comment.</li>
<li><a target='_blank' rel='noopener'  href="https://marketplace.visualstudio.com/items?itemName=wix.vscode-import-cost">Import Cost</a> This is quite a useful extension. It shows the size of the file we are importing inline. It uses webpack with the babili-webpack-plugin to calculate the size of the file.</li>
<li><a target='_blank' rel='noopener'  href="https://marketplace.visualstudio.com/items?itemName=WakaTime.vscode-wakatime">WakaTime</a> is the next plugin in our list. WakaTime gives you analytics about your programming activity. It automatically records your metrics, insights and tracks time of your activity in your favourite code editor. You just have to install the extension and give it the API key. You can get the API key by registering to their official <a target='_blank' rel='noopener'  href="https://wakatime.com/">site</a>. <img src="https://raw.githubusercontent.com/wakatime/vscode-wakatime/master/images/Screen-Shot-2016-03-21.png" alt=""><em>Image from <a target='_blank' rel='noopener'  href="https://wakatime.com/">WakaTime</a></em></li>
<li><a target='_blank' rel='noopener'  href="https://marketplace.visualstudio.com/items?itemName=WASTeamAccount.WebTemplateStudio-dev-nightly">Web Template Studio</a> Makes your workflow way faster by giving you boilerplate code for various front-end, backend, pages and cloud services. It gives a wizard-based experience to help you speed up your process. </li>
<li><a target='_blank' rel='noopener'  href="https://marketplace.visualstudio.com/items?itemName=sdras.night-owl">Night Owl</a> is <code>A Visual Studio Code theme for the night owls out there</code>. 😉 Check it out yourself and you&#39;ll fell in love with it.  </li>
</ul>
<hr>
<p>So, these are some of our favourite VS Code extensions we use daily. I&#39;d love to hear and try your favourite ones too. 😊</p>
<p>Once again a big shoutout to <a class="user-mention" href="https://hashnode.com/@atapas">Tapas Adhikary</a> for sharing his favourite ones. 😄</p>
]]></content:encoded></item><item><title><![CDATA[A Beginner's Guide to the JavaScript Fetch API 🦀]]></title><description><![CDATA[❓ What is the fetch API?
In easy words, fetch is nothing but a request to an API or Application Programming Interface. We use fetch to interact with an API. Or in more technical words,

Fetch is an interface through which JavaScript can make HTTP req...]]></description><link>https://blog.nemotivity.dev/a-beginners-guide-to-the-javascript-fetch-api</link><guid isPermaLink="true">https://blog.nemotivity.dev/a-beginners-guide-to-the-javascript-fetch-api</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[2Articles1Week]]></category><dc:creator><![CDATA[Subha Chanda]]></dc:creator><pubDate>Thu, 06 Aug 2020 18:09:19 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1596737327839/L-zgKAMV1.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="-what-is-the-fetch-api-">❓ What is the fetch API?</h2>
<p>In easy words, <code>fetch</code> is nothing but a request to an API or Application Programming Interface. We use <code>fetch</code> to interact with an API. Or in more technical words,</p>
<blockquote>
<p><strong>Fetch is an interface through which JavaScript can make HTTP requests.</strong></p>
</blockquote>
<p>Here in this article, we&#39;ll use <code>fetch</code> to interact with some free APIs. We&#39;ll also use the COVID API by <a target='_blank' rel='noopener'  href="https://github.com/javieraviles">javieraviles</a> to fetch total cases of Covid19. </p>
<h2 id="-why-use-fetch-">✨ Why use Fetch?</h2>
<p>The <code>XmlHttpRequest</code> or <code>XHR</code> can also be used to make asynchronous HTTP requests. But <code>XHR</code> is quite complicated to use. The <code>fetch API</code> is cleaner and flexible as it uses promises. Fetch is now supported by all modern browsers also. Though, one thing to keep in mind is that the promise returned by <code>fetch</code> will resolve even if the server responds with some error code. </p>
<h2 id="-how-to-use-fetch-">🏅How to use Fetch?</h2>
<p><img src="https://media.giphy.com/media/xlYKItjhiDsY/giphy.gif" alt="Gif Source: [Giphy](https://giphy.com/gifs/xlYKItjhiDsY)"></p>
<p>As I&#39;ve mentioned before, the <code>fetch</code> request will return a promise. A promise is resolved if the request is successful. If you are not familiar with <code>promises</code>, you can check some articles from this <a target='_blank' rel='noopener'  href="https://github.com/didicodes/javascript-dev-bookmarks#promise">link</a>.</p>
<h3 id="fetch-syntax">Fetch Syntax</h3>
<pre><code class="lang-javascript">fetch(<span class="hljs-string">'API Url'</span>)
    .then(response =&gt; {
    <span class="hljs-comment">//Do something with the response</span>
    }).catch(err =&gt; {
    <span class="hljs-comment">// Handle the Errors</span>
});
</code></pre>
<p>But in most of the cases, the first response from the server is pretty ugly. So, we parse it using the <code>json()</code> method which makes it easier to work with. But the <code>json()</code> method also returns a promise. So, we have to add another <code>then</code> to start working with the data. The <code>catch()</code> method is used to handle any error.</p>
<p>By default, the <code>fetch api</code> uses the <code>GET</code> method. Let&#39;s <code>GET</code> some data from the Covid API. </p>
<pre><code class="lang-javascript">fetch(<span class="hljs-string">`https://coronavirus-19-api.herokuapp.com/all`</span>)
  .then((res) =&gt; {
    <span class="hljs-keyword">return</span> res.json();
  })
  .then((data) =&gt; {
    <span class="hljs-built_in">console</span>.log(data);
  });
</code></pre>
<p><img src="https://i.ibb.co/Jxp4HpK/1.png" alt=""></p>
<p>The <code>const fetch = require(&quot;node-fetch&quot;);</code> is used to import a node.js package called <code>node-fetch</code> because fetch API is not implemented in NodeJS. But you don&#39;t need it to run your fetch API code into the browser.</p>
<p>This was pretty easy, right? Now, let&#39;s try to <code>POST</code> some data using <code>fetch API</code>. </p>
<h2 id="-post-data-using-fetch">🔔 Post Data Using Fetch</h2>
<p>We&#39;ll use the <a target='_blank' rel='noopener'  href="https://reqres.in/">reqres</a> API to post data using fetch API. We can use all the HTTP methods with the <a target='_blank' rel='noopener'  href="https://reqres.in/">reqres</a> website. </p>
<p>To post data, we add another parameter to the fetch method which will be an object. We pass the <code>method</code>, <code>body</code>  and <code>header</code> in the second parameter. Because by default fetch uses <code>GET</code> request, we have to explicitly declare the method which is something other than <code>GET</code>. The <code>body</code> will contain the data we are passing. The <code>header</code> will tell the application about the type of data we&#39;re sending and the type of data we&#39;ll accept in return. </p>
<p>We will send a post request to create a user in the reqres server. Let&#39;s see how we can do it.</p>
<p>First of all, we&#39;ll need a user object.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> user = {
    name: <span class="hljs-string">'Captain Nemo'</span>,
    occupation: <span class="hljs-string">'Pirate'</span>,
    email: <span class="hljs-string">'captain@nemo.com'</span>
}
</code></pre>
<p>Now we&#39;ll create another object to define the method, body  and the  type of headers.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> config = {
    method: <span class="hljs-string">'POST'</span>,
    body: json.stringify(user),
    headers: {
        <span class="hljs-string">"Content-Type"</span>: <span class="hljs-string">"application/json"</span>,
        <span class="hljs-string">"Accept"</span>: <span class="hljs-string">"application/json"</span> 
    }
}
</code></pre>
<p>We&#39;re almost done. The only thing left now is to use fetch to send the data. Our fetch method will look like this,</p>
<pre><code class="lang-javascript">fetch(<span class="hljs-string">'https://reqres.in/api/users'</span>, config).then(
  response =&gt; {
    <span class="hljs-keyword">return</span> response.json()
  }
).then(data =&gt; {
  <span class="hljs-built_in">console</span>.log(data);
})
</code></pre>
<p>Let&#39;s see what we get as an output.</p>
<p><img src="https://i.ibb.co/rkJDL1q/3.png" alt=""></p>
<p>First, we are sending our data to the server. Our <code>method</code>, <code>body</code> and <code>headers</code> are defined in the <code>config</code> object. Then the response is passed through the first <code>then</code> method which returns the data. And finally, we are using the data to <code>console.log</code> with the last <code>then</code> method. </p>
<p>The API sends us back the data with an ID and a timestamp.</p>
<h2 id="-error-handling">🚩 Error Handling</h2>
<p>There can be multiple reasons that a <code>fetch</code> request fails. Some can be,</p>
<ul>
<li>The website we are requesting is not found.</li>
<li>We are not authorized to fetch</li>
<li>Server error</li>
</ul>
<p>An unhandled error can be a nightmare. The <code>catch</code> method is the rescue officer in such cases. The <code>catch</code> method can catch any error during the execution of the request. </p>
<p>We can use the <code>ok</code> property of response to check whether the response was successful or not. </p>
<pre><code class="lang-javascript">fetch(<span class="hljs-string">`https://coronavirus-19-api.herokuapp.com/not-found`</span>)
  .then((res) =&gt; {
    <span class="hljs-keyword">if</span> (res.ok) {
      <span class="hljs-keyword">return</span> res.json();
    } <span class="hljs-keyword">else</span> {
      <span class="hljs-keyword">return</span> <span class="hljs-built_in">Promise</span>.reject(res.status);
    }
  })
  .then((data) =&gt; {
    <span class="hljs-built_in">console</span>.log(data);
  })
  .catch((error) =&gt; <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Error with message:'</span>, error));
</code></pre>
<p>So, we are trying to get data from a route which doesn&#39;t exist. We are implementing the <code>ok</code> method here to check if it resolves. Because the route is not available, the <code>catch</code> method catches the error and displays it using the <code>console.log</code>.</p>
<hr>
<p>So, this is it about the <code>JavaScript Fetch API</code> for now. If you liked the article, please leave  ❤ and write a comment. I&#39;d love to here from you. ☺</p>
]]></content:encoded></item><item><title><![CDATA[An Introduction to JavaScript Callbacks ⚔]]></title><description><![CDATA[What is a Callback function? 🤔
We know that in JavaScript, we can pass functions as an argument into another function. These functions which take other function as an argument are known as Higher-Order functions. And the functions which are passed a...]]></description><link>https://blog.nemotivity.dev/an-introduction-to-javascript-callbacks</link><guid isPermaLink="true">https://blog.nemotivity.dev/an-introduction-to-javascript-callbacks</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[ES6]]></category><category><![CDATA[2Articles1Week]]></category><dc:creator><![CDATA[Subha Chanda]]></dc:creator><pubDate>Sun, 02 Aug 2020 05:19:59 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1596345488378/QkrxAeMIp.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="what-is-a-callback-function-">What is a Callback function? 🤔</h1>
<p>We know that in JavaScript, we can pass functions as an argument into another function. These functions which take other function as an argument are known as <strong>Higher-Order functions</strong>. And the functions which are <strong>passed as an argument</strong> are known as a <strong>Callback function.</strong></p>
<p>I&#39;ve discussed three higher-order functions in this <a target='_blank' rel='noopener noreferrer'  href="https://nemo.hashnode.dev/a-brief-introduction-to-javascript-map-filter-and-reduce-methods-ckck648il00df57s122yn0eub">article</a>. 🚀</p>
<p>JavaScript uses a single-threaded non-blocking event loop to provide concurrency. Which means, rather than waiting for a function to complete its execution, it&#39;ll execute other function on the event loop first. </p>
<p>Let&#39;s check an example,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> first = () =&gt; {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"I'll Run First"</span>);
}

<span class="hljs-keyword">let</span> second = () =&gt; {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"I'll Run Second"</span>);
}

first();
second();
</code></pre>
<h3 id="output-">Output:</h3>
<pre><code class="lang-bash">I<span class="hljs-string">'ll Run First
I'</span>ll Run Second
</code></pre>
<p>This output was expected. What if the first function needs some time to execute? Suppose the first function is an API call, which takes more time than usual? Will our code work in the same top-down approach as before?</p>
<p>Let&#39;s create such an instance using the <code>setTimeout()</code> function. What <code>setTimeout</code> do is it evaluates an expression after a given time. </p>
<h3 id="example-">Example:</h3>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> first = () =&gt; {
 setTimeout(() =&gt; {
 <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"I'll Run First"</span>);
 }, <span class="hljs-number">500</span>);
}

<span class="hljs-keyword">let</span> second = () =&gt; {
 <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"I'll Run Second"</span>);
}
</code></pre>
<p>What we are doing here is, we are delaying the first function by 500 milliseconds by calling the <code>setTimeout()</code> function.</p>
<p>If we call the function first and second in the previous order now, we should get the same result as before.</p>
<pre><code class="lang-javascript">first();
second();
</code></pre>
<h3 id="output">Output</h3>
<p><img src="https://i.ibb.co/DpDf3xp/2.png" alt=""></p>
<p>But to our surprise, the second function will execute first this time. So, in this case, JavaScript didn&#39;t wait for the first function to complete, rather it executed the second function first. JavaScript doesn&#39;t always execute in the order they are called. This is because JavaScript is an event-driven language. We&#39;ll discuss the event loop in some future article. </p>
<p>But the key takeaway from here is we just can&#39;t hope that JavaScript will execute the functions in the order we called them. </p>
<p>Now, what if we want to complete a function execution and only then we want to jump to the next function? The callback comes to rescue here. ⛑</p>
<p>Callbacks make sure that another task doesn&#39;t run before a task is completed.</p>
<p><img src="https://media.giphy.com/media/xUA7aWmr0uddsafLEI/giphy.gif" alt=""></p>
<h1 id="creating-a-callback-">Creating a Callback 🎨</h1>
<p>To create a callback function, we usually name the argument <code>callback</code> or <code>cb</code> and pass it as the last argument of the function. Let&#39;s see how we can modify our old code to a new callback function.</p>
<h3 id="example-">Example:</h3>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> callMeFirst = (callback) =&gt; {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"I'll run first"</span>);
  callback();
}
</code></pre>
<h3 id="or-">Or,</h3>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> callMeFirst = (callback) =&gt; {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"I'll run first"</span>);
  <span class="hljs-keyword">return</span> callback();
}
</code></pre>
<p>Now our function is ready to accept a callback function. We can call another function as a parameter in our <code>callMeFirst</code> function now. And the other function passed as the second parameter will always be called after the first function executes.</p>
<pre><code class="lang-javascript">callMeFirst(() =&gt; {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"I'll run second"</span>);
});
</code></pre>
<p>Here, we are passing an anonymous function as a parameter in the <code>callMeFirst</code> function.</p>
<h3 id="output-">Output:</h3>
<p><img src="https://i.ibb.co/c1g2mq7/3.png" alt=""></p>
<p>Here, the callback function is an anonymous function. We can also define a named function and pass it as a callback.</p>
<h3 id="example-">Example:</h3>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> callMeFirst = (callback) =&gt; {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"I'll run first"</span>);
  callback();
}

<span class="hljs-keyword">let</span> callMeSecond = () =&gt; {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"I'll Run second"</span>);
}

callMeFirst((callMeSecond));
</code></pre>
<h3 id="output">Output</h3>
<p><img src="https://i.ibb.co/72s78VV/4.png" alt=""></p>
<p>We just passed a named function as a callback in the above example. </p>
<p>I&#39;d suggest using named functions over anonymous functions as callbacks because it makes the code more readable and also the named functions can be used anywhere in the code.</p>
<hr>
<p>I hope this article put some light on your understanding of what are callbacks and how to use them. If you liked the article, or it helped you leave a ♥, share it and leave a comment. 😎</p>
]]></content:encoded></item><item><title><![CDATA[Object Destructuring in JavaScript for Beginners]]></title><description><![CDATA[Introduction
The ES6 introduced the concept of object destructuring along with other things like let, const, arrow functions. Object destructuring is a very useful feature in JavaScript. It extensively used in frontend framework like React as well as...]]></description><link>https://blog.nemotivity.dev/object-destructuring-in-javascript-for-beginners</link><guid isPermaLink="true">https://blog.nemotivity.dev/object-destructuring-in-javascript-for-beginners</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[ES6]]></category><category><![CDATA[2Articles1Week]]></category><dc:creator><![CDATA[Subha Chanda]]></dc:creator><pubDate>Thu, 30 Jul 2020 16:15:14 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1596125485195/M_NOqiUOz.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="introduction">Introduction</h1>
<p>The ES6 introduced the concept of object destructuring along with other things like let, const, arrow functions. Object destructuring is a very useful feature in JavaScript. It extensively used in frontend framework like React as well as backend services like Node.js also. This article is focused to give you some knowledge about the object destructuring.</p>
<h1 id="what-is-destructuring-">What is Destructuring?</h1>
<p>Destructuring means extracting data from arrays or objects. With destructuring, we can break a complex object or array into smaller parts. Destructuring also gives us the ability to extract multiple data at once from an object or array. It also provides the ability to set a default value of the property if it&#39;s already not set.</p>
<h1 id="destructuring-with-example">Destructuring with Example</h1>
<p>To understand the concept of object destructuring, we need to take an example in the count.</p>
<p>Suppose we have an object with the following key-value properties,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> person = {
 firstName: <span class="hljs-string">"Captain"</span>,
 lastName: <span class="hljs-string">"Nemo"</span>
}
</code></pre>
<p>Before ES6, to use the values we needed to write code like this,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> firstName = person.firstName;
<span class="hljs-keyword">const</span> lastName = person.lastName;
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Hi <span class="hljs-subst">${firstName}</span> <span class="hljs-subst">${lastName}</span>! Nice to meet you. 😄`</span>);
</code></pre>
<p>It&#39;s a small object, but imagine we have a large object having a lot of key-value pairs, then to access the properties, our code will be very much repetitive and we don&#39;t want to disobey the God of DRY! 😅
<img src="https://media.giphy.com/media/kH5famqWhd1W51tUvg/giphy.gif" alt=""></p>
<p>To solve this issue, ES6 provides us with the power of destructuring. Using destructuring, we can easily extract the properties using the following code,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> { firstName, lastName } = person;
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Hi <span class="hljs-subst">${firstName}</span> <span class="hljs-subst">${lastName}</span>! Nice to meet you. 😄`</span>);
</code></pre>
<p>This might seem confusing if you&#39;re seeing this for the first time. The first question that popped in my mind when I first saw the syntax for the first time was, why the curly braces are on the left? Is it a block? Or is it an Object? </p>
<p>Actually it&#39;s none of the both. It&#39;s just how destructuring syntax looks like.</p>
<p>Basically, it&#39;s just saying </p>
<blockquote>
<p><strong><strong>Give me a variable called firstName and a variable called lastName from the object called person.</strong></strong></p>
</blockquote>
<h1 id="destructuring-a-nested-object">Destructuring a Nested Object</h1>
<p>Object destructuring comes handier when we are working with a nested object. </p>
<p>Imagine an object like the below one,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> person = {
 firstName: <span class="hljs-string">"Captain"</span>,
 lastName: <span class="hljs-string">"Nemo"</span>,
 address: {
  street: <span class="hljs-string">"1234 Ave"</span>,
  city: <span class="hljs-string">"Antilaw State"</span>,
  zip: <span class="hljs-number">1234</span>
 }
}
</code></pre>
<p>To access the elements using the old approach, the code will be too much repetitive and will look very dirty.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(person.firstName);
<span class="hljs-built_in">console</span>.log(person.lastName);
<span class="hljs-built_in">console</span>.log(person.address.street);
<span class="hljs-built_in">console</span>.log(person.address.city);
<span class="hljs-built_in">console</span>.log(person.address.zip);
</code></pre>
<h3 id="output">Output</h3>
<p><img src="https://i.ibb.co/D8q2j4h/1.png" alt=""></p>
<p>And now, let&#39;s take a look using the ES6 object destructuring,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> { firstName, lastName, address: { street, zip, city } } =  person;
<span class="hljs-built_in">console</span>.log(firstName);
<span class="hljs-built_in">console</span>.log(lastName);
<span class="hljs-built_in">console</span>.log(street);
<span class="hljs-built_in">console</span>.log(city);
<span class="hljs-built_in">console</span>.log(zip);
</code></pre>
<p>This is clearly a better approach to access the elements. And moreover we have to write less lines.</p>
<p><img src="https://i.ibb.co/qgP199c/2.png" alt=""></p>
<p>There&#39;s a beautiful quotation I read in the <strong>Eloquent JavaScript</strong> Book about writing less code. Here it follows,</p>
<blockquote>
<p>Tzu-li and Tzu-ssu were boasting about the size of their latest programs. ‘Two-hundred thousand lines,’ said Tzu-li, ‘not counting comments!’ Tzu-ssu responded, ‘Pssh, mine is almost a <em>million</em> lines already.’ Master Yuan-Ma said, ‘My best program has five hundred lines.’ Hearing this, Tzu-li and Tzu-ssu were enlightened.</p>
<p>Master Yuan-Ma, <em>The Book of Programming</em></p>
</blockquote>
<h1 id="storing-object-values-to-custom-variables">Storing Object Values to Custom Variables</h1>
<p>Now, let&#39;s say we need to store the extracted properties to custom variables. We can also do this with the object destructuring. Suppose we want to store the <code>firstName</code> element of the <code>person</code> object to a variable called <code>first</code> and the<code>lastName</code> to a variable called <code>last</code>. This can be achieved using the following code,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> { firstName: first, lastName: last } =  person;
<span class="hljs-built_in">console</span>.log(first);
<span class="hljs-built_in">console</span>.log(last);
</code></pre>
<p>And yes, we can also extract only the elements we want. In the above code, we extracted only the <code>firstName</code> and the <code>lastName</code> from the object.</p>
<h1 id="destructuring-arrays">Destructuring Arrays</h1>
<p>At the beginning of this article, I told you that we can use destructuring for arrays also. How?</p>
<p>Here&#39;s an example,</p>
<p>Suppose an array contains scores of a student in 3 subjects.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> scores = [<span class="hljs-number">85</span>, <span class="hljs-number">90</span>, <span class="hljs-number">74</span>];
</code></pre>
<p>We can destructure the scores easily using the following code,</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> [maths, geography, biology] = scores;
<span class="hljs-built_in">console</span>.log(maths);
<span class="hljs-built_in">console</span>.log(geography);
<span class="hljs-built_in">console</span>.log(biology);
</code></pre>
<p>So, using the simple <code>array literal</code> to the left, we can destructure the array. The array elements are getting stored in local variables we defined. Each of the local variables will map with the corresponding array element.</p>
<h3 id="output-">Output:</h3>
<p><img src="https://i.ibb.co/mTF3gKZ/4.png" alt=""></p>
<h1 id="conclusion">Conclusion</h1>
<p>I think this article has given you a quite understanding using the destructuring used in ES6. If this article helped you or you&#39;ve feedback, please comment below. I&#39;d love to hear from you. 😊</p>
]]></content:encoded></item></channel></rss>