<?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[Wahab Seidu's Blog]]></title><description><![CDATA[Wahab Seidu's Blog]]></description><link>https://wahabseidu.hashnode.dev</link><generator>RSS for Node</generator><lastBuildDate>Mon, 31 Aug 2026 12:15:36 GMT</lastBuildDate><atom:link href="https://wahabseidu.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Understanding CSS Flexbox]]></title><description><![CDATA[Introduction
A core aspect of CSS you will use many times as a front-end developer is the flexbox layout. Flexbox is quite easy, yet, a lot of developers struggle with it as I once did.
One mistake many developers make is emphasizing more on learning...]]></description><link>https://wahabseidu.hashnode.dev/understanding-css-flexbox</link><guid isPermaLink="true">https://wahabseidu.hashnode.dev/understanding-css-flexbox</guid><category><![CDATA[flexbox]]></category><category><![CDATA[CSS]]></category><category><![CDATA[CSS3]]></category><category><![CDATA[css flexbox]]></category><category><![CDATA[css layout ]]></category><dc:creator><![CDATA[Wahab Seidu]]></dc:creator><pubDate>Sat, 23 Sep 2023 18:07:18 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1695487919637/27c634e0-6726-4067-a7d9-39fd71b03754.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-introduction">Introduction</h1>
<p>A core aspect of CSS you will use many times as a front-end developer is the flexbox layout. Flexbox is quite easy, yet, a lot of developers struggle with it as I once did.</p>
<p>One mistake many developers make is emphasizing more on learning various Flexbox values at the expense of understanding how the layout works in general.</p>
<p>Sure, knowing the various flex properties and their values is useful, but that's not the important part. The important things to understand are:</p>
<ul>
<li><p>how to identify the main and the cross axis,</p>
</li>
<li><p>the components of a flex layout and the relationship between them,</p>
</li>
<li><p>the properties that can be applied to each component,</p>
</li>
<li><p>the properties that you can use to adjust the behavior of items on each flex axis (i.e. the main and the cross axis), and</p>
</li>
<li><p>the behavior of each property and how it can be adjusted to achieve the desired layout.</p>
</li>
</ul>
<p>This article will address the important points listed above. It will also provide you with the right way to think about certain things in Flexbox.</p>
<p>Well, let’s get right into it.</p>
<h2 id="heading-prerequisite">Prerequisite</h2>
<ul>
<li>Basic understanding of HTML and CSS</li>
</ul>
<h2 id="heading-what-is-flexbox">What is Flexbox?</h2>
<p>Flexbox is a layout model that is useful for <em>arranging</em> a group of items in <strong><em>one direction</em></strong>. The direction may be a row or a column as opposed to the normal/default flow layout of:</p>
<ul>
<li><p>Block - which only stacks items vertically (top to bottom), and</p>
</li>
<li><p>Inline - which only stacks items horizontally (left to right).</p>
</li>
</ul>
<p>Flexbox gives tremendous control over the behavior of a group of items (as a whole), and each of the items in the group. It achieves this by using a flex container to represent the group of items and a flex item to represent each item in the container.</p>
<p>With Flexbox, you can:</p>
<ul>
<li><p>Control the distribution of extra space among flex items in the container,</p>
</li>
<li><p>control the behavior of flex items as the size of the container is increased or decreased,</p>
</li>
<li><p>explicitly specify the gap that you want between flex items, among other things.</p>
</li>
</ul>
<p>As you proceed in this article, you will discover more things that you can do with the flex layout.</p>
<h2 id="heading-the-flex-direction-property"><strong>The Flex direction property</strong></h2>
<p>The flex-direction property specifies the direction of items in the flex container. It also helps to determine the <strong>main axis</strong> (or primary axis), and the <strong>cross axis</strong> (or perpendicular axis). This is one of the most important properties you need to understand, so pay attention to it.</p>
<p>The default value of <code>flex-direction</code> is <code>row</code>, but it can accept three other values as shown in this code</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.flex-container</span> {
    <span class="hljs-attribute">flex-direction</span>: row | column | row-reverse | column-reverse
}
</code></pre>
<p>The main axis and the cross axis do not have a fixed direction. Their direction depends on the value that flex-direction is set to. If the <code>flex-direction</code> is:</p>
<ul>
<li><strong>Row -</strong> the main axis spans horizontally from left to right, while the cross axis, is vertical (from top to bottom)</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1695048479901/cde56aac-0692-46e1-8393-0558b0c2f4cf.png" alt class="image--center mx-auto" /></p>
<ul>
<li><strong>Column -</strong> the main axis spans vertically from top to bottom, while the cross axis, is horizontal (from left to right)</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1695048501292/d6ccee64-a7d9-4bfb-8985-1797980ced1d.png" alt class="image--center mx-auto" /></p>
<ul>
<li><strong>Row-reverse -</strong> same as when flex-direction is set to row. The only difference is the direction of the main axis which runs from right to left</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1695048515091/42353344-cddc-41ab-bb66-f4e1833c8070.png" alt class="image--center mx-auto" /></p>
<ul>
<li><strong>Column-reverse -</strong> same as when flex-direction is set to the column. The only difference is the direction of the main axis which runs from bottom to top.</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1695048529079/24c0191d-fc9d-4ef6-b44d-bcd50d3f7556.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-bonus-tip-a-simple-trick-to-instantly-identify-the-two-flex-axes"><strong>Bonus Tip: A Simple Trick to Instantly Identify the Two Flex Axes</strong></h2>
<p>You can use a simple trick to identify the main axis and cross axis. All you need to know is how to draw a simple line.</p>
<p>If you draw an imaginary line that cuts through the group of flex items, the direction that the line passes is the main axis.</p>
<p>To get the cross-axis, draw another imaginary line perpendicular to the main axis line.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1695056447754/a0b28f45-8233-4a6e-8736-d031d5939445.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-the-components-of-a-flexbox-flex-container-and-flex-items"><strong>The Components of a Flexbox:</strong> <strong>Flex container and Flex items</strong></h2>
<p>Understanding the relationship between these two is crucial to understanding Flexbox.</p>
<p>A flex container serves as a shell or box for the flex items. It is also the parent element that controls the layout and arrangement of the flex items inside it.</p>
<p>Just as a teacher controls the arrangement of students in a classroom, the flex container controls the arrangement of the flex items and can determine:</p>
<ul>
<li><p>Whether the elements should be in a row or column (<em>flex-direction</em>)</p>
</li>
<li><p>the amount of space between flex items (<em>gap,</em> or <em>justify-content</em>)</p>
</li>
<li><p>whether the item will wrap into multiple lines (or not) if it cannot fit into one line (<em>flex-wrap</em>), and so on.</p>
</li>
</ul>
<p>This does not mean that the flex items have no control of their own. They are like rebellious students that you can't completely restrict. They can determine:</p>
<ul>
<li><p>Whether they want to grow or shrink to fill the available space (<em>flex-grow/flex-shrink</em>)</p>
</li>
<li><p>the order in which they want to appear along their direction (<em>order</em>)</p>
</li>
<li><p>their position relative to other flex items (<em>align-self</em>).</p>
</li>
</ul>
<p>You're right, the italicized terms in brackets (in the bullet points above) are actual flexbox properties which we will soon discuss.</p>
<h2 id="heading-content-vs-items">Content vs Items</h2>
<p>Before proceeding to explain the various Flexbox properties, it is vital to differentiate between content and items. You will encounter these two terms many times when using Flexbox. Understanding these terms now will save you a lot of stress later.</p>
<ul>
<li><p><strong>Content -</strong> simply refers to a group of flex items that can be arranged along either of the flex axes i.e. main or cross axis. When you encounter this term, it refers <mark>to all the items</mark> in the container and not one item individually.</p>
</li>
<li><p><strong>Items -</strong> refers <mark>to each item </mark> in a flex container <mark>individually</mark>. This term is usually found in flex item properties (which will soon be discussed) useful for directly targeting a specific flex item in a flex container.</p>
</li>
</ul>
<h2 id="heading-flexbox-properties">Flexbox Properties</h2>
<p>At this stage, you should already be familiar with how the Flexbox layout works at a broad level.</p>
<p>Here, we go into the specifics. You will learn about the various properties that you can use to move things around in a flex layout.</p>
<p>Pay special attention to the flex axes (i.e. main or cross axis) which the property explained can be applied.</p>
<h3 id="heading-flex-container-or-parent-properties"><strong>Flex Container or Parent properties</strong></h3>
<p>These properties are applied to the flex container to control the arrangement or behavior of the flex item. They are:</p>
<h3 id="heading-display">display:</h3>
<p><code>display</code> defines the HTML element or the selector representing it as a flex container. This ensures that the elements under this container behave as flex items. A flex container can be any HTML container element like <code>&lt;div&gt;</code> or <code>&lt;ul&gt;</code>.</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.flex-container</span> {
    <span class="hljs-attribute">display</span>: flex;
}
</code></pre>
<h3 id="heading-justify-content">justify-content:</h3>
<p><code>justify-content</code> decides the arrangement of flex items along the <strong>main axis</strong>. It also helps to distribute extra spaces among flex items (along the <strong>main axis</strong>).</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.flex-container</span> {
    <span class="hljs-attribute">justify-content</span>: flex-start | flex-end | center | space-around | space-between | space-evenly | start | end | left | right;
}
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1695463264749/ac8d48b4-4b5f-4450-9562-be1431ed8aee.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-align-items">align-items:</h3>
<p><code>align-items</code> defines the behavior or alignment of items along the <strong>cross axis</strong>. Think of it as the equivalent of <code>justify-content</code> for the cross axis.</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.flex-container</span> {
    <span class="hljs-attribute">align-items</span>: stretch | flex-start | flex-end | baseline | center | first baseline | last baseline | start | end | self-start | self-end
}
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1695463300469/e05e8aff-f1eb-4099-83aa-4c9b54bfac2a.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-flex-wrap">flex-wrap:</h3>
<p>When there isn’t enough space to accommodate all the flex items on a line, flexbox tries to cram them together to fit that line. By setting <code>flex-wrap</code> to <code>wrap</code>, flex-items are pushed to the next line when there isn’t enough space.</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.flex-container</span> {
    <span class="hljs-attribute">flex-wrap</span>: wrap | nowrap;
}
</code></pre>
<p>Check this codepen to see how it works</p>
<iframe height="380" style="width:100%" src="https://codepen.io/Wahab-Seidu/embed/preview/NWeXXpa?default-tab=html%2Cresult&amp;editable=true&amp;theme-id=dark">
  See the Pen <a href="https://codepen.io/Wahab-Seidu/pen/NWeXXpa">
  flex-wrap</a> by Wahab Seidu (<a href="https://codepen.io/Wahab-Seidu">@Wahab-Seidu</a>)
  on <a href="https://codepen.io">CodePen</a>.
</iframe>

<p>In the codepen above, change the flex-wrap property on the flex-container to see the effect.</p>
<h3 id="heading-align-content">align-content:</h3>
<p>This property works only when you have flex items on multiple lines. This is usually due to setting <code>flex-wrap</code> to <code>wrap</code>. You should use this property instead of <code>align-items</code> when you have more than one line of flex items along your <strong>cross axis</strong>.</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.flex-container</span> {
    <span class="hljs-attribute">align-content</span>: flex-start | flex-end | center | space-between | space-around | space-evenly | stretch | start | end | baseline | first baseline | last baseline;
}
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1695464052827/0e297b2c-a0da-4244-b677-25dc46eafa03.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-gap">gap:</h3>
<p>This property allows you to directly control the space between flex items. <code>gap</code> is a shorthand property that represents both row-gap and column-gap (in that order). For example, If you set <code>gap</code> to</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.flex-container</span> {
    <span class="hljs-attribute">gap</span>: <span class="hljs-number">20px</span>; <span class="hljs-comment">/* represents both row-gap and column-gap */</span>
    <span class="hljs-attribute">gap</span>: <span class="hljs-number">20px</span> <span class="hljs-number">45px</span>; <span class="hljs-comment">/* row-gap is set to 20px while column-gap is set to 45px */</span>
  <span class="hljs-comment">/* You can also set them explicitly */</span>
    <span class="hljs-attribute">row-gap</span>: <span class="hljs-number">20px</span>;
    <span class="hljs-attribute">column-gap</span>: <span class="hljs-number">45px</span>;
}
</code></pre>
<p>You can play around with the gap properties in the codepen (in the CSS) below to see how it works</p>
<iframe height="380" style="width:100%" src="https://codepen.io/Wahab-Seidu/embed/preview/mdappzW?default-tab=html%2Cresult&amp;editable=true&amp;theme-id=dark">
  See the Pen <a href="https://codepen.io/Wahab-Seidu/pen/mdappzW">
  gap</a> by Wahab Seidu (<a href="https://codepen.io/Wahab-Seidu">@Wahab-Seidu</a>)
  on <a href="https://codepen.io">CodePen</a>.
</iframe>

<p>The gap property only specifies the space between flex items. Unlike <code>justify-content</code>, It does not control the space between the edge of the container and the first item (or the last flex item).</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1695464473395/8dbd415c-5197-49d3-b2e2-b3bee72fbef4.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-properties-for-the-flex-items"><strong>Properties For the Flex items:</strong></h3>
<p>Now that you know the flex container properties, you will learn about properties that can be used on flex items.</p>
<p>These properties control the behavior of individual flex items and <strong>not the group as a whole</strong>. Some of these properties are:</p>
<h3 id="heading-flex-basis">flex-basis:</h3>
<p>This property works as the width or height of a flex item. When the <code>flex-direction</code> property is <code>row</code>, it sets the width of the flex item. Conversely, it sets the height when <code>flex-direction</code> is <code>column</code>.</p>
<p>Even though <code>flex-basis</code> works as width or height, it is different from the “width” or “height” in the default layout.</p>
<p><code>Flex-basis</code> is not a fixed dimension that is always applied no matter what. It is more of a suggestion of what size the width or height of the flex item should be if there is enough space to contain that size.</p>
<p>For the normal width or height properties, if the container available cannot accommodate their size, the item will overflow i.e. jump out of its container. Whereas in the case of <code>flex-basis</code>, the item will try to fill all the space available in its container even though it will do so at a size smaller than its original size.</p>
<p>As an example, check this codepen</p>
<iframe height="380" style="width:100%" src="https://codepen.io/Wahab-Seidu/embed/preview/poqdObZ?default-tab=html%2Cresult&amp;editable=true&amp;theme-id=dark">
  See the Pen <a href="https://codepen.io/Wahab-Seidu/pen/poqdObZ">
  Flex-basis</a> by Wahab Seidu (<a href="https://codepen.io/Wahab-Seidu">@Wahab-Seidu</a>)
  on <a href="https://codepen.io">CodePen</a>.
</iframe>

<p>The above codepen shows one flex container and one normal container. In the CSS, each container was declared a width of 200px.</p>
<p>When we declare a flex-basis (representing width) of 300px on our flex container, it sits comfortably within it without spilling out. Conversely, when we set the width of our normal item to 300px, it overflows.</p>
<p>Play around with the flex-basis and width to get a hang of things.</p>
<details><summary>NOTE</summary><div data-type="detailsContent">Using the <code>width</code> property within a flex item will behave the same way as <code>flex-basis</code>. The only exception is that <code>flex-basis</code> can serve as either the width or height of the item depending on the flex-direction. For instance, by using <code>flex-basis</code>, the width of an item will change to its height when flex-direction is changed from <code>row</code> to <code>column</code> and vice versa. The same transformation is not possible when you use the <code>width</code> or <code>height</code> property within a container.</div></details>

<h3 id="heading-flex-grow">flex-grow:</h3>
<p>We said earlier that you can use <code>justify-content</code> for distributing extra space among flex items. What if you didn’t want to distribute the extra space but wanted a flex item to take it up? That’s where <code>flex-grow</code> comes in. <code>flex-grow</code> defines the <strong>portion</strong> or <strong>percentage</strong> of the extra space that a flex item should take up.</p>
<p>The word <em>portion</em> is important in this context. Any value assigned to the flex-grow on a flex item represents a portion of the extra space available. The flex item takes up that portion by <strong>“growing”</strong> to fill it. For this reason, <code>flex-grow</code> is better defined as the rate at which a flex item grows to take up extra space in the flex container.</p>
<p>Check this codepen</p>
<iframe height="380" style="width:100%" src="https://codepen.io/Wahab-Seidu/embed/preview/qBLpvyJ?default-tab=html%2Cresult&amp;editable=true&amp;theme-id=dark">
  See the Pen <a href="https://codepen.io/Wahab-Seidu/pen/qBLpvyJ">
  flex-grow</a> by Wahab Seidu (<a href="https://codepen.io/Wahab-Seidu">@Wahab-Seidu</a>)
  on <a href="https://codepen.io">CodePen</a>.
</iframe>

<p>In the codepen above, make the following changes in the CSS:</p>
<ul>
<li><p>Change the <code>flex-grow</code> of <code>flex-item-one</code> from 0 to 1 and see what happens. You can see that <code>flex-item-one</code> now takes up all the extra space</p>
</li>
<li><p>Change the <code>flex-grow</code> of <code>flex-item-two</code> from 0 to 1 so that both flex items now have a <code>flex-grow</code> of 1. This makes each item take up equal space in the container. To understand what happened, think of the value of each flex item as a ratio such that 1:1. In this context, the extra space available is 2 (1 + 1) and each flex item takes ½ of that portion.</p>
</li>
<li><p>Change the <code>flex-grow</code> of <code>flex-item-one</code> from 1 to 2. This makes <code>flex-item-one</code> grow twice as much as <code>flex-item-two</code>. That means the total portion is now 3 (1 + 2). <code>flex-item-one</code> takes 2/3 while <code>flex-item-two</code> takes 1/3 .</p>
</li>
<li><p>If you change the <code>flex-grow</code> on <code>flex-item-two</code> to 2 (so that both flex items have an <strong>equal</strong> <code>flex-grow</code> of 2), both items grow equally again.</p>
</li>
</ul>
<h3 id="heading-flex-shrink">flex-shrink:</h3>
<p><code>flex-shrink</code> is the opposite of <code>flex-grow</code>. It specifies how flex items should <strong>reduce in size</strong> due to insufficient space.</p>
<p><code>flex-shrink</code> only takes effect when the size of flex items is higher than the size of the container. It specifies the rate at which each flex item “shrinks” (reduces in size) to make up for that deficit.</p>
<p>Like <code>flex-grow</code>, <code>flex-shrink</code> also defines the <strong>portion</strong> or <strong>percentage</strong> of the deficit space that a flex item should reduce from its size. Also, <code>flex-shrink</code> would be more accurately defined as the rate at which a flex item <strong>"shrinks"</strong> or reduces in size to settle any space deficit.</p>
<p>This codepen gives a better illustration:</p>
<iframe height="380" style="width:100%" src="https://codepen.io/Wahab-Seidu/embed/preview/jOXZmxR?default-tab=html%2Cresult&amp;editable=true&amp;theme-id=dark">
  See the Pen <a href="https://codepen.io/Wahab-Seidu/pen/jOXZmxR">
  flex-shrink</a> by Wahab Seidu (<a href="https://codepen.io/Wahab-Seidu">@Wahab-Seidu</a>)
  on <a href="https://codepen.io">CodePen</a>.
</iframe>

<p>Currently, the flex items don't fit within the container. Let's go to our CSS to find out why. In the CSS, the flex container has a width of 200px while each flex item has a <code>flex-basis</code> (which serves the same purpose as width) of 160px. Of course, the items are wider than the container and should overflow, but shouldn't they stay within the container since <code>flex-basis</code> is used?</p>
<p>Remember we learned that using <code>flex-basis</code> on an item within a container will allow the item to stay within that container. The reason for the overflow of items is that <code>flex-shrink</code> is currently set to 0 on each flex item!</p>
<p>By setting <code>flex-shrink</code> to 0 on both items, we're essentially saying that none of them should take up the deficit space hence the overflow of items.</p>
<p>Now that we've settled this potential confusion, make the following changes in the CSS:</p>
<ul>
<li><p>Change the <code>flex-shrink</code> of <code>flex-item-one</code> from 0 to 1 and see what happens. You can see that <code>flex-item-one</code> now settles all the deficit space and the overflow no longer exists.</p>
</li>
<li><p>Change the <code>flex-shrink</code> of <code>flex-item-two</code> from 0 to 1 so that both flex items now have a <code>flex-shrink</code> of 1. This makes each item take up equal space in the container sharing the deficit equally. To understand what happened, think of the value of each flex item as a ratio such that 1:1. In this context, the deficit space is 2 (1 + 1) and each flex item takes ½ of that portion.</p>
</li>
<li><p>Change the <code>flex-shrink</code> of flex-item-one from 1 to 2. This makes <code>flex-item-one</code> shrink twice as much as flex-item-two. That means the total deficit is now 3 (1 + 2). <code>flex-item-one</code> takes 2/3 while <code>flex-item-two</code> takes 1/3.</p>
</li>
<li><p>If you change the <code>flex-shrink</code> on <code>flex-item-two</code> to 2 (so that both flex items have an equal flex-grow of 2), both items shrink equally again.</p>
</li>
</ul>
<h3 id="heading-order">order:</h3>
<p>The <code>order</code> property specifies the order in which items are laid out in the flex container. By default, the <code>order</code> property of any item is 0. This means that the item retains its source order. However, this property can be adjusted to change the normal or initial order of a flex item.</p>
<p>The rule for using <code>order</code> is simple, the item with the least order value comes first in the container. Also, if all the items have the same order, they retain their normal position.</p>
<p>Change the <code>order</code> values of the flex items in the codepen below to see how it works</p>
<iframe height="380" style="width:100%" src="https://codepen.io/Wahab-Seidu/embed/preview/BavYOqR?default-tab=html%2Cresult&amp;editable=true&amp;theme-id=dark">
  See the Pen <a href="https://codepen.io/Wahab-Seidu/pen/BavYOqR">
  testing</a> by Wahab Seidu (<a href="https://codepen.io/Wahab-Seidu">@Wahab-Seidu</a>)
  on <a href="https://codepen.io">CodePen</a>.
</iframe>

<h2 id="heading-games-to-improve-your-flexbox-skills">Games to Improve Your Flexbox Skills</h2>
<p>Yeah! you heard me right. Certain games can make learning CSS Flexbox fun and engaging. I highly recommend the following:</p>
<ul>
<li><p><a target="_blank" href="https://flexboxfroggy.com/">Flexbox froggy</a></p>
</li>
<li><p><a target="_blank" href="http://www.flexboxdefense.com/">Flexbox defense</a></p>
</li>
<li><p><a target="_blank" href="https://mastery.games/flexboxzombies/">Flexbox zombies</a></p>
</li>
<li><p><a target="_blank" href="https://codingfantasy.com/games/flexboxadventure/play">Flex Box adventure</a></p>
</li>
</ul>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Congrats on coming to the end of this article 🎉🎉🎉. I know, it's a lengthy article, but we can both admit that every piece of information in the article is relevant to your understanding.</p>
<p>You should know that the Flexbox layout is one of the most important things you need to master to conquer CSS. For this reason, I implore you not to stop at this article and go ahead to build projects and get your hands dirty using CSS Flexbox. Playing the games listed in the previous section can also solidify your understanding.</p>
<p>If you found this article informative, kindly drop a like ❤️ and leave your thoughts in the comments section. You can also share this article to help someone facing difficulties with CSS Flexbox. And lastly, follow me for more engaging content!</p>
<p>Good luck and happy coding!</p>
]]></content:encoded></item><item><title><![CDATA[Understanding JavaScript Errors]]></title><description><![CDATA[Introduction
The ability to understand errors and fix them with error messages is a vital skill that every developer should have. Even though errors might seem daunting at first glance, they are quite easy to understand and very helpful.
An Error usu...]]></description><link>https://wahabseidu.hashnode.dev/understanding-javascript-errors</link><guid isPermaLink="true">https://wahabseidu.hashnode.dev/understanding-javascript-errors</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[error handling]]></category><category><![CDATA[coding]]></category><category><![CDATA[Developer]]></category><dc:creator><![CDATA[Wahab Seidu]]></dc:creator><pubDate>Tue, 29 Aug 2023 03:06:44 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1695426357346/04900bc9-599b-492d-a6d3-9f308586cfd9.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-introduction">Introduction</h1>
<p>The ability to understand errors and fix them with error messages is a vital skill that every developer should have. Even though errors might seem daunting at first glance, they are quite easy to understand and very helpful.</p>
<p>An Error usually contains an error message, which points you in the right direction, by giving you the information required to resolve it.</p>
<p>Apart from helping you to effectively debug your code, error messages also help in receiving help from other developers when you get stuck.</p>
<p>This article will simplify JavaScript errors and provide you with the necessary knowledge to start resolving them in no time.</p>
<h2 id="heading-prerequisite"><strong>Prerequisite</strong></h2>
<ul>
<li>Basic knowledge of JavaScript</li>
</ul>
<h2 id="heading-types-of-javascript-errors">Types of JavaScript errors</h2>
<p>There are several types of JavaScript errors, this article will only cover the major ones you are most likely to encounter while writing JavaScript as a beginner.</p>
<p><strong>NOTE:</strong> The statement "throw an error/ throw error" used many times in this article, is the technical term for when an error occurs, or is displayed on the console.</p>
<h3 id="heading-reference-error">Reference error</h3>
<p>A reference error (usually written in the console as <code>ReferenceError</code>) is thrown when you reference or use a variable that does not exist (has not been declared or defined). As an example, this code</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> fruit = <span class="hljs-string">"Apple"</span>;
<span class="hljs-keyword">let</span> randomNumber = <span class="hljs-number">21</span>;

<span class="hljs-built_in">console</span>.log(food);
</code></pre>
<p>will throw the following error because the variable <code>food</code> was neither declared nor defined.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1693223431578/68109292-0509-4576-9ea5-0a086264f013.png" alt class="image--center mx-auto" /></p>
<p>Note that if a variable was declared but not defined, the browser console simply displays <code>undefined</code> (and not a <code>ReferenceError</code>). For example, this code</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> myName;
<span class="hljs-built_in">console</span>.log(myName);
</code></pre>
<p>will simply display <code>undefined</code> as shown below because the variable <code>myName</code> was only declared but not defined.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1693214264482/29736a22-dfda-4a06-af82-f34a49b983e6.png" alt class="image--center mx-auto" /></p>
<p>This means to avoid a reference error, you should at least declare the variable you want to reference.</p>
<h3 id="heading-syntax-error">Syntax error</h3>
<p>You will get a syntax error when your code cannot be parsed by the JavaScript engine because it is not written properly. It simply means that your code does not follow the grammatical rules of JavaScript.</p>
<p>This may be due to the following:</p>
<ul>
<li><p>Missing opening or closing parenthesis.</p>
</li>
<li><p>Improper use of reserved keywords like <code>let</code>, <code>const</code>, <code>for</code>, etc.</p>
</li>
<li><p>Use of incorrect cases (uppercase or lowercase) for reserved keywords, among others.</p>
</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> food = <span class="hljs-string">"Rice"</span>;
<span class="hljs-comment">// any of the following will throw a syntax error</span>
<span class="hljs-built_in">console</span>.log(food; <span class="hljs-comment">// missing parenthesis</span>
<span class="hljs-keyword">let</span> <span class="hljs-keyword">for</span> = <span class="hljs-string">"you"</span>; <span class="hljs-comment">// improper use of reserved keyword</span>
C0nsole.log(food); <span class="hljs-comment">// use of incorrect case -- "C and O in console should be in lowercase"</span>
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1693223337670/a28ca839-3b91-4676-937d-2512642d7682.png" alt class="image--center mx-auto" /></p>
<h3 id="heading-type-error">Type error</h3>
<p>It's difficult to pinpoint a specific reason for getting a type error as they are thrown for different reasons. But the underlying reason a type error is thrown is due to inappropriate usage, or modification of a particular data type. As an example, the code</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> myName = <span class="hljs-string">"John"</span>;
<span class="hljs-keyword">let</span> operation = myName.toFixed(<span class="hljs-number">2</span>);
<span class="hljs-built_in">console</span>.log(operation);
</code></pre>
<p>will throw this error</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1693216535159/2bd6ac0e-45a7-4649-9a3e-eb468f2a67d3.png" alt class="image--center mx-auto" /></p>
<p>Here, we have an error and you probably already know the reason if you are familiar with the <code>.toFixed()</code> method.</p>
<p>The <code>.toFixed()</code> method is used when we want a <strong>number</strong> to have a fixed number of digits after the decimal point. This tells us that it should never be used with a string as we've done in our code and this is why it throws a <strong>type</strong> error!</p>
<p>The error message displayed by a <code>TypeError</code> seems somewhat confusing. We know that <code>.toFixed()</code> is a function (i.e. as all javascript methods are essentially functions) yet the error message tells us that it's not a function.</p>
<p>To understand this error message, it needs to be put into context. In this context, the error message tells us that <code>.toFixed()</code> is "not a function (or method)" that can be used with a string hence "<code>myName.toFixed(2)</code> is not a function".</p>
<p>Let's use a more practical example. This code</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> greeting = <span class="hljs-string">"Hello"</span>;
<span class="hljs-keyword">const</span> currentUser = <span class="hljs-string">"Smith"</span>;
<span class="hljs-keyword">const</span> message = greeting.push(currentUser);
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1693220167983/14bbe4ba-a665-4fc9-902d-1e629983adf0.png" alt class="image--center mx-auto" /></p>
<p>In this case, the original intention was to add the two strings stored in <code>greetings</code> and <code>currentUser</code> respectively. However, we wrongly used <code>push()</code> (an array method) for that purpose, which resulted in a type error.</p>
<p>If we used a string method like <code>.concat()</code> (which adds two strings together) our code will work as planned.</p>
<p>The most common reason for getting a type error is trying to modify a constant value i.e. a variable defined with the keyword <code>const</code></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> color = <span class="hljs-string">"Black"</span>;
color = <span class="hljs-string">"White"</span>;
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1693232246675/3de39bea-0adf-4f29-9009-2b3a8c5f9b7e.png" alt class="image--center mx-auto" /></p>
<p>The right way to think about type errors is that they either indicate when you are using a particular data type wrongly, or you're using the wrong method for a data type.</p>
<h3 id="heading-logical-error">Logical error</h3>
<p>This error occurs when the program or application fails to work as expected due to a mistake in your code structure or logic. The program works but not as expected. As an example, this code</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">calculateTotalProfit</span>(<span class="hljs-params">pricePerUnit, costPerUnit, quantitySold</span>) </span>{
  <span class="hljs-keyword">return</span> pricePerUnit - costPerUnit * quantitySold; <span class="hljs-comment">// will multiply price by quantity first</span>
}

<span class="hljs-keyword">let</span> totalProfit = calculateTotalProfit(<span class="hljs-number">15</span>, <span class="hljs-number">10</span>, <span class="hljs-number">6</span>);
<span class="hljs-built_in">console</span>.log(totalProfit); <span class="hljs-comment">// will display -45 in error instead of 30.</span>
</code></pre>
<p>will give an incorrect output.</p>
<p>As you might have guessed, our intention here is to write a function that deducts the <code>costPerUnit</code> from the <code>pricePerUnit</code> of a product and multiply the result by the <code>quantitySold</code>.</p>
<p>However, we get -45 (in error) instead of 30 when we use our function. This is because the return statement handles the multiplication (of <code>costPerUnit</code> by <code>quantitySold)</code> before subtracting the result from <code>pricePerUnit</code>. Of course, this is not what we want.</p>
<p>We can easily rectify this error by wrapping the subtraction in parenthesis. This ensures that <code>costPerUnit</code> is deducted from <code>pricePerUnit</code> before multiplying it by <code>quantitySold</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">calculateTotalProfit</span>(<span class="hljs-params">pricePerUnit, costPerUnit, quantitySold</span>) </span>{
  <span class="hljs-keyword">return</span> (pricePerUnit - costPerUnit) * quantitySold; <span class="hljs-comment">// will handle the subtraction first</span>
}

<span class="hljs-keyword">let</span> totalProfit = calculateTotalProfit(<span class="hljs-number">15</span>, <span class="hljs-number">10</span>, <span class="hljs-number">6</span>);
<span class="hljs-built_in">console</span>.log(totalProfit); <span class="hljs-comment">// will give the correct output, 30</span>
</code></pre>
<p>No error message? Yeah, an error message is not displayed for a logical error. Why? Nothing is interrupting the execution of the program. Your program will run but will supply an unexpected output.</p>
<h2 id="heading-the-analysis-of-an-error">The Analysis of an Error</h2>
<p>An error itself is a JavaScript object that contains information about the <strong><em>type</em></strong> of the error and a <strong><em>message</em></strong> providing further details. This information is produced whenever the execution of the code is interrupted due to an incorrect entry in the code.</p>
<p>As an example, take a look at this error message below</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1693223458053/d3bceb71-fee4-4d1d-a03d-a7c155529cde.png" alt class="image--center mx-auto" /></p>
<p>In this error, you can identify the type of the error and the error message. The first line shows a ReferenceError <strong>(type)</strong> which says "food is not defined" <strong>(message)</strong> which gives us a sneak peek into what to look for.</p>
<p>The second line is a link that specifies the file where the error came from (in this example, script.js), and the line of code causing the error in that file (in this case, line 4). With this information, you can easily go to the line causing the error and make necessary corrections.</p>
<p>Some browsers provide additional information on the specific character/column causing the error. In our example (script.js:4:<strong>13</strong>), this would be the 13th character on line 4. You will find this feature very useful when the line of code that throws an error is very long or complex.</p>
<p>If you are coding along using a browser console, you can just click the link showing the file and it will take you to that particular line in the sources panel of the developer tools.</p>
<p>Take a look at another example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> firstNum = <span class="hljs-number">5</span>;
<span class="hljs-keyword">const</span> secondNum = <span class="hljs-number">10</span>;
<span class="hljs-keyword">const</span> thirdNum = <span class="hljs-number">8</span>;

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

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">display</span>(<span class="hljs-params"></span>) </span>{
  multiply();
}

display();
</code></pre>
<p>As you can see from this code, a function returns a variable that has not been defined, and that function is called within another function. This throws a <code>ReferenceError</code> as follows:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1693224377742/b8332fe9-1819-41e7-8bfe-de7c29071ac0.png" alt /></p>
<p>You can see that the error message refers to different lines of the code file. This is called a stack trace and indicates the origin of the error and the order of events leading to the error. In this case, the slack trace shows that</p>
<ul>
<li><p><code>result</code> is not defined and cannot be used in the scope of multiply(), which is declared on line 6, column 3.</p>
</li>
<li><p><code>display()</code> called <code>multiply()</code> (an error-prone function), which was declared on line 10, column 3.</p>
</li>
<li><p><code>display()</code>, was called on line 12.</p>
</li>
</ul>
<p>Analyzing the error as above will help you break it down into different parts, with each part giving specific information about the error. Once you can decode the information given by these parts, you can easily</p>
<ul>
<li><p>Find the code responsible for the error,</p>
</li>
<li><p>Identify the reason for the error, and</p>
</li>
<li><p>Resolve the error.</p>
</li>
</ul>
<h2 id="heading-simple-tips-for-resolving-javascript-errors">Simple tips for resolving JavaScript errors</h2>
<p>When coding you will most likely need to resolve errors now and then. If you have been following this article so far, you should now know how to find the particular line, or lines of code responsible for your error.</p>
<p>After tracing the error to its source, the following tips can help you resolve errors effectively.</p>
<ol>
<li><p>Carefully study the error and try to interpret it. At this point, you should already know how.</p>
</li>
<li><p>If you are unable to understand the error, Google it. You can also use AI tools like chatGPT as an alternative. The idea here is to get an explanation of why you received the error and possibly get a hint to resolve it.</p>
</li>
<li><p>Use the console. console.log() is a popular option for debugging JavaScript among developers. You can use it to get the value of a variable, array, or any other data type to help you get a clearer picture of things.</p>
</li>
<li><p>You should note that console.log() does not directly resolve your errors. It is just useful to know the state of your code at specific points which can be crucial in resolving logical errors. For example, you can use console.log() within your condition statements to check if it works.</p>
<pre><code class="lang-javascript"> <span class="hljs-keyword">let</span> a = <span class="hljs-number">20</span>;
 <span class="hljs-keyword">if</span> (a &gt; <span class="hljs-number">12</span>) {
   <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"a is greater than 12"</span>);
 } <span class="hljs-keyword">else</span> {
   <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"a is NOT greater than 12"</span>);
 }
</code></pre>
<p> You can also use it to check the output of functions and check whether they work as intended.</p>
<pre><code class="lang-javascript"> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">multipl</span>(<span class="hljs-params">x, y</span>) </span>{
   <span class="hljs-keyword">return</span> x * y;
 }

 <span class="hljs-built_in">console</span>.log(multiply(<span class="hljs-number">3</span>, <span class="hljs-number">7</span>));
</code></pre>
</li>
<li><p>For more complex errors or troubleshooting, you might want to use the debugger to debug your code as this is more appropriate. This <a target="_blank" href="https://developer.chrome.com/docs/devtools/javascript">video</a> from Chrome DevTools should help.</p>
</li>
<li><p>You can also check <a target="_blank" href="https://stackoverflow.com/">StackOverflow</a> for a fix. Chances are, someone already asked the same or a similar question about the error and there is an answer to help you. If the question has not been posted before, post the question. When doing this, you should include what you've done so far to resolve it on your own, and relevant screenshots of your code.</p>
</li>
<li><p>Only use StackOverflow after trying to resolve the error on your own using the tips above. You don't want to go through the stress of posting a question and waiting for an answer for a fix that can easily be found through a Google search.</p>
</li>
</ol>
<h2 id="heading-conclusion">Conclusion</h2>
<p>To conclude, JavaScript errors are roadblocks that either prevent your code from working at all or as intended. By gaining the ability to interpret and resolve them, you have successfully removed a major roadblock in your coding adventure.</p>
<p>This article has provided you with the required knowledge to identify, find and resolve your errors on your own. It has also provided you with simple tips to receive meaningful help from others.</p>
<p>Don't hesitate to like this article, and share your experiences on JavaScript errors you've encountered in the past. Your contributions are valued and can help us learn collectively.</p>
<p>Good luck and happy coding!</p>
]]></content:encoded></item></channel></rss>