<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Md. Imran Hossain</title>
    <description>The latest articles on DEV Community by Md. Imran Hossain (@mdimran1409036).</description>
    <link>https://dev.to/mdimran1409036</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F733694%2F734fea29-44a0-41e6-b97e-f8935922b413.jpeg</url>
      <title>DEV Community: Md. Imran Hossain</title>
      <link>https://dev.to/mdimran1409036</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/mdimran1409036"/>
    <language>en</language>
    <item>
      <title>Asynchronous Javascript and Some advanced use cases</title>
      <dc:creator>Md. Imran Hossain</dc:creator>
      <pubDate>Wed, 25 Oct 2023 18:19:13 +0000</pubDate>
      <link>https://dev.to/mdimran1409036/asynchronous-javascript-and-some-advanced-use-cases-2357</link>
      <guid>https://dev.to/mdimran1409036/asynchronous-javascript-and-some-advanced-use-cases-2357</guid>
      <description>&lt;p&gt;Although Javascript is a single-threaded programming language and it executes programs synchronously, It also handles asynchronous tasks using &lt;code&gt;Web API, Task queue and event loop&lt;/code&gt;. Whenever an asynchronous code block comes to the call stack following things happen:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;It gets deferred to &lt;code&gt;Web API&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;Web API&lt;/code&gt; tries to resolve the code, and whenever it gets resolved, goes to the Callback Queue&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;Event Loop&lt;/code&gt; always watches the call stack&lt;/li&gt;
&lt;li&gt;The moment the &lt;code&gt;Call Stack&lt;/code&gt; gets empty, &lt;code&gt;Event Loop&lt;/code&gt; pushes the resolved task to the &lt;code&gt;Call Stack&lt;/code&gt;
&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;Call Stack&lt;/code&gt; executes the code&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;During this process, after the asynchronous tasks get resolved from Web API, the Callback Queue gets populated with the following tasks:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Macro Tasks (Task Queue)&lt;/li&gt;
&lt;li&gt;Micro Tasks (Job Queue)&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The Task Queue is responsible for these tasks: &lt;code&gt;setTimeout, setInterval, setImmediate,  I/O tasks, etc.&lt;/code&gt;&lt;br&gt;
The Job Queue handles these tasks: &lt;code&gt;Promises, processes.nextTick, etc.&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;As Event Loop takes the resolved tasks from the Callback Queue and the Callback Queue has two task Queues, So the obvious question is how Event Loop decides which queue to dequeue from.&lt;/p&gt;

&lt;p&gt;This answer depends on the following rules:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;For each loop of the &lt;code&gt;Event loop&lt;/code&gt;, one &lt;code&gt;Macro Task&lt;/code&gt; is completed out of the Macro Task Queue.&lt;/li&gt;
&lt;li&gt;Once that task is complete, the event loop visits the &lt;code&gt;Micro Task Queue&lt;/code&gt;. The entire &lt;code&gt;Micro Task Queue&lt;/code&gt; is completed before the &lt;code&gt;Event Loop&lt;/code&gt; looks into the next thing.&lt;/li&gt;
&lt;li&gt;At any point in time, if both the queues got entries, &lt;code&gt;Job Queue(Micro Task Queue)&lt;/code&gt; gets higher precedence than &lt;code&gt;Task Queue (Macro Task Queue)&lt;/code&gt;.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fiuk11b718qjr59hakr0u.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fiuk11b718qjr59hakr0u.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;These are all the magic that happens behind Asynchronous code execution. Now let's move into some examples to validate the above discussion.&lt;br&gt;
&lt;strong&gt;Example 1:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;console.log("first");

fetch("https://jsonplaceholder.typicode.com/todos/1")
    .then((response) =&amp;gt; response.json())
    .then((json) =&amp;gt; console.log("json placeholder result", json));

setTimeout(() =&amp;gt; {
    console.log("after 1000 millisecond");
}, 500);

setTimeout(() =&amp;gt; {
    console.log("after 0 millisecond");
}, 0);

const promise = new Promise((resolve, reject) =&amp;gt; {
    resolve("I am promise and I am resolved");
});
promise.then((response) =&amp;gt; console.log(response));

console.log("second");
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So what do you think is the output of the result?&lt;br&gt;
the output should be like this:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;first
second
I am promise and I am resolved
after 0 millisecond
json placeholder result {
    "userId": 1,
    "id": 1,
    "title": "delectus aut autem",
    "completed": false
}
after 1000 millisecond
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;em&gt;Explanation:&lt;/em&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;The first line comes to the call stack, it is synchronous so executes immediately and logs "first";&lt;/li&gt;
&lt;li&gt;The asynchronous operations (fetch, setTimeout(0 &amp;amp; 1000 milliseconds), and Promise) are deferred to the Web API.&lt;/li&gt;
&lt;li&gt;The last line is also synchronous and so it is executed by the Call stack and logs "second". Now the call stack is empty.&lt;/li&gt;
&lt;li&gt;Although fetch is called before setTimeout, it takes some time to be resolved as it communicates with external API. so it's still pending in the Web API. &lt;/li&gt;
&lt;li&gt;Meanwhile the setTimeout with 0 milliseconds and promise gets resolved immediately. The promise gets pushed to the Micro Task Queue and setTimeout with 0 milliseconds gets pushed to the Macro Task Queue. The Micro Task Queue gets more priority than the Macro Task Queue for both entries. So Event Loop will take the promise first and the setTimeout second. so the log order should be 
"I am promise and I am resolved" 
"after 0 millisecond"&lt;/li&gt;
&lt;li&gt;At this point Web API resolves(hopefully i.e. depends on the external server "jsonplaceholder") the fetch and goes to Micro Task Queue. Event Loop takes the resolved result and push to Call Stack. Call stack then prints the result.&lt;/li&gt;
&lt;li&gt;Lastly, the setTimeout with 1000 milliseconds gets resolved and moves to Macro Task. Event Loop then push it to the call stack and logs "after 1000 millisecond"&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Example 2&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const p1 = new Promise((resolve, reject)=&amp;gt;{
    setTimeout(()=&amp;gt;{
        resolve("p1")
    },4000)
}) 
const p2=new Promise((resolve, reject)=&amp;gt;{
    setTimeout(()=&amp;gt;{
        resolve("p2")
    },8000)
}) 
const p3= new Promise((resolve, reject)=&amp;gt;{
    setTimeout(()=&amp;gt;{
        resolve("p3")
    },0)
}) 

async function main(){
    console.log(await p1)   
    console.log(await p2) 
    console.log(await p3) 
}
main()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;What will be the output and how much time will take for p1, p2 and p3 to be executed?&lt;/p&gt;

&lt;p&gt;The answer should be:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;p1 - 4 second
p2 - 8 second
p3 - 8 second
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;em&gt;Explanation:&lt;/em&gt;&lt;br&gt;
when the code starts to get executed:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;p1, p2 and p3 will all be deferred to Web API before executing the main() function. &lt;/li&gt;
&lt;li&gt;As the new Promise is an instance of the Promise class, the constructor method will already be executed before executing main() function which results as setTimeout with 4000 milliseconds, 8000 milliseconds, and  0 milliseconds all will be in the Web API and will be in the pending state.&lt;/li&gt;
&lt;li&gt;Now, the main() function is called which is implemented using async await.&lt;/li&gt;
&lt;li&gt;Now, the compiler will try to execute p1 and wait until p1 is resolved from Web API and it will take minimum 4 second&lt;/li&gt;
&lt;li&gt;Secondly, the compiler will try to execute p2 and wait until p2 is resolved from Web API. As it was previously in the Web API in pending state it will take 8 seconds from the very beginning. &lt;/li&gt;
&lt;li&gt;Thirdly, p3 is already resolved as it has 0 millisecond timeout. But it had to wait until the p2 is finished. p2 took 8 second so it will also take 8 second. &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;strong&gt;Example 3&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const p1 =()=&amp;gt; new Promise((resolve, reject)=&amp;gt;{
    setTimeout(()=&amp;gt;{
        resolve("p1")
    },4000)
}) 
const p2=()=&amp;gt;new Promise((resolve, reject)=&amp;gt;{
    setTimeout(()=&amp;gt;{
        resolve("p2")
    },8000)
}) 
const p3=()=&amp;gt; new Promise((resolve, reject)=&amp;gt;{
    setTimeout(()=&amp;gt;{
        resolve("p3")
    },0)
}) 

async function main(){
    console.log(await p1())   
    console.log(await p2()) 
    console.log(await p3()) 
}
main()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This problem is identical to example 2. But slightly different as p1,p2 and p3 are functions. So what will be the result now?&lt;/p&gt;

&lt;p&gt;The answer should be:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;p1 - 4 second
p2 - 12 second
p3 - 12 second
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now why the answer is different?&lt;br&gt;
&lt;em&gt;Explanation&lt;/em&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;The promises are not executed before main() function gets called. &lt;/li&gt;
&lt;li&gt;p1,p2, and p3 are just function reference not promise. &lt;/li&gt;
&lt;li&gt;When p1() is called inside the main function it waits for 4 seconds to be executed, then p2() gets called. &lt;/li&gt;
&lt;li&gt;till now, we have already passed 4 seconds, p2() takes another 8 seconds. So, total 8+4=12 seconds will be taken. &lt;/li&gt;
&lt;li&gt;p3() resolves immediately, so the total time taken for p3  is 12+0=12 seconds. &lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;(will be continued...)&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>asynchronousjavascript</category>
    </item>
    <item>
      <title>useEffect = comoponentDidMount + ComponentDidUpdate + componentWillUnmount
</title>
      <dc:creator>Md. Imran Hossain</dc:creator>
      <pubDate>Thu, 13 Jan 2022 06:38:45 +0000</pubDate>
      <link>https://dev.to/mdimran1409036/useeffect-comoponentdidmount-componentdidupdate-componentwillunmount-4g5p</link>
      <guid>https://dev.to/mdimran1409036/useeffect-comoponentdidmount-componentdidupdate-componentwillunmount-4g5p</guid>
      <description>&lt;p&gt;React offers two types of components as you already know which are:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Class component&lt;/li&gt;
&lt;li&gt;Functional component&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Those who are familiar with class components, know it uses life cycle methods to keep track of the states and work with &lt;code&gt;side effects&lt;/code&gt;. React is solely responsible for UI rendering and reacting to user actions by rendering JSX code,  managing states and props, managing events, and evaluating state/props change. Side effect means anything that is not react’s responsibility like(fetching data from an API, updating the DOM, setting any subscriptions or timers)    &lt;/p&gt;

&lt;p&gt;Three lifecycle methods: componentDidMount, componentDidUpdate and componentWillUnmount are extremely useful from loading the components for the first time in the DOM to unmount the components(navigating to other pages, conditional rendering of certain components of a page, etc). Here is a short description of those three life cycle methods.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;componentDidMount:
This method triggers when a component loads for the first time. We may need to connect with an external API, perform certain DOM operations ( a side effect), perform asynchronous tasks i.e. setting intervals, etc. &lt;/li&gt;
&lt;li&gt;ComponentDidUpdate:
As we have certain states in our component, often we need to update them. We update states by emitting events, input changes in the form, etc. So in these cases, we must update our states, that’s where componentDidMount lifecycle comes to play.&lt;/li&gt;
&lt;li&gt;componentWillUnmount:
This method is necessary to prevent memory leaks and performance optimization. We mostly need this to perform certain operations like clearing timer and subscription which will not be needed when the page will unmount.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;These life cycle methods are very useful and necessary, and we couldn’t think not to use them. But these methods have some disadvantages as well. Some of them:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Duplicate code&lt;/li&gt;
&lt;li&gt;Sharing same logic&lt;/li&gt;
&lt;li&gt;Complex states&lt;/li&gt;
&lt;li&gt;Using the tiresome lifecycle methods repeatedly(some may disagree)&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;I will discuss the disadvantages by demonstrating a class component base application and later, I will use the &lt;code&gt;useEffect&lt;/code&gt;hook to avoid using those lifecycle methods.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React, { Component } from "react";
import "./App.css";
export default class App extends Component {
    state = {
        time: new Date(),
        count: 0,
        show: true,
    };

    componentDidMount() {
        document.title = `you have count ${this.state.count} times`;
        this.interval = setInterval(this.tick, 1000);
    }
    componentDidUpdate() {
        document.title = `you have count ${this.state.count} times`;
    }
    componentWillUnmount() {
        clearInterval(this.interval);
    }
    tick = () =&amp;gt; {
        this.setState({ time: new Date() });
    };
    handleCount = () =&amp;gt; {
        this.setState(({ count }) =&amp;gt; ({
            count: count + 1,
        }));
    };
    handleShow = () =&amp;gt; {
        this.setState(({ show }) =&amp;gt; ({
            show: !show,
        }));
    };
    render() {
        const { time, show } = this.state;
        return (
            &amp;lt;div className="container"&amp;gt;
                &amp;lt;div className="post"&amp;gt;
                    {show &amp;amp;&amp;amp; (
                        &amp;lt;div&amp;gt;
                            &amp;lt;p&amp;gt;Current time {time.toLocaleTimeString()} &amp;lt;/p&amp;gt;
                            &amp;lt;button onClick={this.handleCount}&amp;gt;
                                Count start
                            &amp;lt;/button&amp;gt;
                        &amp;lt;/div&amp;gt;
                    )}
                &amp;lt;/div&amp;gt;
                &amp;lt;div className="controlPost"&amp;gt;
                    &amp;lt;button onClick={this.handleShow}&amp;gt;
                        {show ? "Hide post" : "Show post"}
                    &amp;lt;/button&amp;gt;
                &amp;lt;/div&amp;gt;
            &amp;lt;/div&amp;gt;
        );
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Output:&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--Fk9-T_Mc--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ie2hk8nnrrc4wup340j5.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--Fk9-T_Mc--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ie2hk8nnrrc4wup340j5.png" alt="Image description" width="880" height="380"&gt;&lt;/a&gt;&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--M4z8CB7i--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/l8e1fro7yt052vewt5il.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--M4z8CB7i--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/l8e1fro7yt052vewt5il.png" alt="Image description" width="880" height="303"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This is a simple application that shows the clicks user performed by clicking the "count start" button in the web page title and has a clock that shows the current time. Additionally, a button "Hide post" that shows or hides "the clock "and "count start" button. &lt;/p&gt;

&lt;p&gt;Pretty simple application right? Here are the things we need to understand,&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;The clock will start ticking when the page is loaded &lt;/li&gt;
&lt;li&gt;At each click in the "count start" button, it will increase the count in the web page title.&lt;/li&gt;
&lt;li&gt;When clicking the "hide post" button it will hide the "clock" and "count start" button and display the "show post" button and clicking again, the "clock" and "count start" button will be visible again&lt;/li&gt;
&lt;li&gt;Finally, When we hide post, the clock shall be unmounted as it leads to memory leaks and performance issues.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;So we clearly see, we have three states 1. count 2. time 3.show . In the above code snippet, I have loaded the clock by setting a time interval in the &lt;code&gt;componetDidMount&lt;/code&gt; method and initialized the document title, as both of them are side effects((I have mentioned earlier about the side effects ) and needed to render at the first time page loading. I have used a click event(&lt;code&gt;handleCount&lt;/code&gt;) to increase the value of count at each click using &lt;code&gt;setState&lt;/code&gt;. &lt;br&gt;
Now the state is changed but that will still not be rendered to the UI unless the &lt;code&gt;componentDidUpdate&lt;/code&gt;lifecycle method is used. Using this method we updated the document title. &lt;br&gt;
Clicking the hide post button will unmount the "clock" and "count start" button, but still, the clock will be running in the background  unless we use the &lt;code&gt;componentWillUnmount&lt;/code&gt;method to clear the interval. Using this method we have cleared the interval &lt;/p&gt;

&lt;p&gt;If we have a closer look at the above code snippet we may notice that we didn’t follow the DRY principle and repeated code in the life cycle methods, we also had to share same logic between the life cycle methods. Also, the states aren’t handled properly, we see a mixture of complex states and using the states in the same lifecycle method(i.e. In &lt;code&gt;componentDidMount&lt;/code&gt; setting interval and setting the document title) which are not desirable.&lt;/p&gt;

&lt;p&gt;Before the introduction of &lt;code&gt;useEffect&lt;/code&gt;, we had to handle the side effects and different component life cycle methods using those life cycle methods. But now most of the problems that we encountered using class component is taken care of by using useEffect hook and functional components.&lt;br&gt;
So let’s see how we can use the useEffect hook and git rid of those life cycle methods. &lt;br&gt;
At first let’s see, what actually a useEffect hook is!&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;useEffect(() =&amp;gt; {
        effect
        return () =&amp;gt; {
            cleanup
        }
    }, [dependency])
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;useEffect hook is  actually a function which takes two parameters. 1. A callback function 2. An array of dependency(optional).The rules are:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;The callback function is the side effect that we need to perform which loads at the first rendering of the component. It is much like the &lt;code&gt;componentDidMount&lt;/code&gt; life cycle method. If the second parameter is not given this callback function will render every time if any state or props change.&lt;/li&gt;
&lt;li&gt;The second parameter is the dependency(state) which tells react to render the callback function only when the dependency changes. So when the dependency changes or updates, it will re-render. This is much like &lt;code&gt;componentDidMount&lt;/code&gt; lifecycle method. It can be empty, if it is empty the callback function will render only once when the component mounts for the first time. &lt;/li&gt;
&lt;li&gt;The callback function can also have a return value(cleanup). The return value only fires when the component will be unmount. So it will serve the &lt;code&gt;componentWillUnmount&lt;/code&gt; cycle methods purpose.
So in these way, we achieve the three cycle methods only using a single hook and that is useEffect hook.
Now let’s do the application again but this time using functional component and useEffect hook.
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { useEffect, useState } from "react";
import "./App.css";
const App = () =&amp;gt; {
    const [count, setCount] = useState(0);
    const [time, setTime] = useState(new Date());
    const [show, setShow] = useState(true);
    const tick = () =&amp;gt; {
        setTime(new Date());
    };
    useEffect(() =&amp;gt; {
        document.title = `you have clicked ${count} times`;
    }, [count]);
    useEffect(() =&amp;gt; {
        const interval = setInterval(tick, 1000);
        return () =&amp;gt; clearInterval(interval);
    }, []);
    const handleCount = () =&amp;gt; {
        setCount((count) =&amp;gt; count + 1);
    };
    const handleShow = () =&amp;gt; {
        setShow((show) =&amp;gt; !show);
    };

    return (
        &amp;lt;div className="container"&amp;gt;
            &amp;lt;div className="post"&amp;gt;
                {show &amp;amp;&amp;amp; (
                    &amp;lt;div&amp;gt;
                        &amp;lt;p&amp;gt;Current time {time.toLocaleTimeString()} &amp;lt;/p&amp;gt;
                        &amp;lt;button onClick={handleCount}&amp;gt;Count start&amp;lt;/button&amp;gt;
                    &amp;lt;/div&amp;gt;
                )}
            &amp;lt;/div&amp;gt;
            &amp;lt;div className="controlPost"&amp;gt;
                &amp;lt;button onClick={handleShow}&amp;gt;
                    {show ? "Hide post" : "Show post"}
                &amp;lt;/button&amp;gt;
            &amp;lt;/div&amp;gt;
        &amp;lt;/div&amp;gt;
    );
};
export default App;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This will give the same output as the previous one. Now you may notice, unlike class components we have used useEffect hook two times(we can use life cycle methods only once in a  component). Also, we defined states, using three different useState hooks and used separate useEffect hooks for separate states. This is the recommended way to handle states by isolating states.&lt;br&gt;
We used &lt;code&gt;count&lt;/code&gt; dependency in the first useEffect hook because whenever the state of count changes the function will re-render. And in the second useEffectHook, we returned a cleanup function to clear the timer when it will unmount. &lt;/p&gt;

&lt;p&gt;Now let’s discuss how we accomplished the three life cycle methods using only one hook.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;When component first mount, &lt;code&gt;useEffect&lt;/code&gt; hook sets the document title and starts the clock which serves the &lt;code&gt;componentDidMount&lt;/code&gt; purpose.&lt;/li&gt;
&lt;li&gt;When the &lt;code&gt;count&lt;/code&gt; is updated, It will again re-render the component using the &lt;code&gt;count&lt;/code&gt; dependency. Again it serves the &lt;code&gt;componentDidUpdate&lt;/code&gt; method's purpose&lt;/li&gt;
&lt;li&gt;In the second &lt;code&gt;useEffect&lt;/code&gt; hook, the callback function returns a clean-up function that clears the interval of the clock at component unmount. So this time useEffect hook works like the &lt;code&gt;componentWillUnmount&lt;/code&gt; method.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The summary is useEffect hook gives us the advantage of using a single function to perform three different lifecycle methods which help us perform side effects in functional components and solves all the problems of lifecycle methods in class components.&lt;/p&gt;

</description>
      <category>useeffect</category>
      <category>react</category>
      <category>classcomponent</category>
      <category>functionalcomponent</category>
    </item>
    <item>
      <title>binding "this"</title>
      <dc:creator>Md. Imran Hossain</dc:creator>
      <pubDate>Sun, 09 Jan 2022 10:57:37 +0000</pubDate>
      <link>https://dev.to/mdimran1409036/binding-this-3db4</link>
      <guid>https://dev.to/mdimran1409036/binding-this-3db4</guid>
      <description>&lt;p&gt;&lt;code&gt;this&lt;/code&gt; keyword references an object. Using &lt;code&gt;this&lt;/code&gt; keyword we may access the properties and methods of a class/object.  Previously, I discussed the use-cases of &lt;code&gt;this&lt;/code&gt; &lt;a href="https://dev.to/mdimran1409036/this-keyword-in-javascript-3039"&gt;in this article&lt;/a&gt;. The summery is:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;If a function is not part of any object, it will simply reference the global window object.&lt;/li&gt;
&lt;li&gt;If a function is a part of an object, we call it as method. Inside a method &lt;code&gt;this&lt;/code&gt;references the object.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The main problem arises when we use a function(i.e. &lt;a href="https://developer.mozilla.org/en-US/docs/Glossary/Callback_function" rel="noopener noreferrer"&gt;a callback function&lt;/a&gt;) inside that method of an object, &lt;code&gt;this&lt;/code&gt; references the global window object and we may want to access(bind) the object and redefine the &lt;code&gt;this&lt;/code&gt; inside the callback function.&lt;br&gt;
Let’s see the problem first:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const books = {
  author: "john doe",
  books: ["history", "english", "math"],
  findBooks() {
    this.books.forEach(function (item) {
      console.log(`${this.author} like ${item}`);
    });
  },
};
books.findBooks();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Books is a simple object which has author and books properties and a method "findbooks".&lt;br&gt;
"findBooks" simply logs the author and books information. Inside the "findBooks" function we have used a "foreach" method that has a callback function. Now the output should print:&lt;/p&gt;

&lt;p&gt;‘john doe like history’, &lt;br&gt;
‘jhon doe like english’ &lt;br&gt;
‘john doe like math’&lt;/p&gt;

&lt;p&gt;Let’s see the output:&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fgjp9ietyjnv2hlcdoocp.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fgjp9ietyjnv2hlcdoocp.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;So we see &lt;code&gt;this.author&lt;/code&gt; does not print the author name. So what’s happened actually? You see, this line of code &lt;code&gt;console.log(&lt;/code&gt;${this.author} like ${item}&lt;code&gt;)&lt;/code&gt; is inside the callback function and the callback function is a regular function, has different execution context and references the window object(recalling the summery 1 above). In short, callback function is not a part of the object it is inside.&lt;/p&gt;

&lt;p&gt;So how do we access the object using &lt;code&gt;this&lt;/code&gt;?&lt;br&gt;
This is the concept behind binding data or binding object.&lt;br&gt;
There are three different scenarios by which may access/bind the object inside the callback function.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;1. Using Arrow function:&lt;/strong&gt;&lt;br&gt;
Unlike regular function, Arrow function uses the surrounding scope as the scope of this, So whatever the surrounding scope is becomes the scope of an arrow function.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const books = {
  author: "john doe",
  books: ["history", "english", "math"],
  findBooks() {
    this.books.forEach((item) =&amp;gt; {
      return console.log(`${this.author} like ${item}`);
    });
  },
};
books.findBooks();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Output:&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F6n9k66jmollu85w9o1oo.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F6n9k66jmollu85w9o1oo.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now, the callback function doesn’t have it’s own scope rather it uses the findbooks methods scope.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;2. Explicit bind method:&lt;/strong&gt;&lt;br&gt;
So I was thinking, If we stick to the regular function(as callback), there must be a way to bind the object. &lt;br&gt;
This question has an answer too. We may use bind method to get access the object.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const books = {
  author: "john doe",
  books: ["history", "english", "math"],
  findBooks() {
    this.books.forEach(
      function (item) {
        return console.log(`${this.author} like ${item}`);
      }.bind(this)
    );
  },
};
books.findBooks();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Output:&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F6n9k66jmollu85w9o1oo.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F6n9k66jmollu85w9o1oo.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;code&gt;this&lt;/code&gt; inside the bind method creates a little confusion. But fear not! see, we have access to this (books) object inside foreach. So, bind method also have access too. Now the regular callback function is binded with this object.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;3. Assigning ‘this’ to a variable:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const books = {
  author: "john doe",
  books: ["history", "english", "math"],
  findBooks() {
    let self = this;
    this.books.forEach(function (item) {
      return console.log(`${self.author} like ${item}`);
    });
  },
};
books.findBooks();
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Output:&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F6n9k66jmollu85w9o1oo.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F6n9k66jmollu85w9o1oo.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;We have assigned this to a variable(self) and use it inside the callback function. It is basically the closure concept that will not be covered in this article. But what it does, we get access to the variable declared in the parent function inside the child function . In this way, the self variable gets the reference of this, and later we used it inside the callback function. &lt;/p&gt;

</description>
      <category>javascript</category>
      <category>this</category>
    </item>
    <item>
      <title>This keyword in Javascript</title>
      <dc:creator>Md. Imran Hossain</dc:creator>
      <pubDate>Thu, 06 Jan 2022 13:05:52 +0000</pubDate>
      <link>https://dev.to/mdimran1409036/this-keyword-in-javascript-3039</link>
      <guid>https://dev.to/mdimran1409036/this-keyword-in-javascript-3039</guid>
      <description>&lt;p&gt;&lt;code&gt;This&lt;/code&gt; means the object that is executing the current function.&lt;br&gt;
There are two cases mainly using the &lt;code&gt;this&lt;/code&gt;keyword.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;If a function is not part of any object, it will simply reference the global window object.&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;If a function is a part of an object, we call it as method. Inside a method &lt;code&gt;this&lt;/code&gt;reference the object.&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Let’s see the &lt;code&gt;this&lt;/code&gt;use cases: &lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;code&gt;This&lt;/code&gt;by default references the window object. So, inside a normal function (not method in an object) &lt;code&gt;this&lt;/code&gt;references the global window object.
&lt;/li&gt;
&lt;/ol&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function greeting() {
    console.log(this)
}
greeting()

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Feqe2rbw28imcxn3ejuxl.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Feqe2rbw28imcxn3ejuxl.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Now, let’s see what &lt;code&gt;this&lt;/code&gt;references inside an object.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F61urtnzd4jqmxc6rus3a.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F61urtnzd4jqmxc6rus3a.png" alt="Image description"&gt;&lt;/a&gt;&lt;br&gt;
&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ffc86rjv0adnij7fyr8d1.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Ffc86rjv0adnij7fyr8d1.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Unlike the first case,  here &lt;code&gt;this&lt;/code&gt;references the object itself it is in. So using &lt;code&gt;this&lt;/code&gt;the properties and methods of an object can be accessed.&lt;br&gt;
Now if we consider a constructor function, let’s see what the this method references.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;function Greeting(fname) {
   this.fname = fname
   console.log(this)
}
const greetingObj = new Greeting('john')
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fzus200au57lexv193q2j.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fzus200au57lexv193q2j.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Again, we see this referencing Greeting object (We call the constructor function using new keyword which creates an empty object, so &lt;code&gt;this&lt;/code&gt; keyword eventually references the empty object)&lt;br&gt;
Now, Let’s see what will happen if we use &lt;code&gt;this&lt;/code&gt; keyword inside a function of a method.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const books = {
    author: 'john doe',
    books: ['history', 'english', 'math'],
    findBooks() {
        this.books.forEach(function (item) { console.log(this.author, item) })
    }
}
books.findBooks()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;output:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F2087j58yh9xjnj23t9oe.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F2087j58yh9xjnj23t9oe.png" alt="Image description"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The output should print the author name instead of undefined. So what’s wrong here! The callback function inside &lt;code&gt;foreach&lt;/code&gt;is not a part of findbooks method, rather it’s a regular function which references the &lt;code&gt;global window object&lt;/code&gt;, that’s why &lt;code&gt;this.author&lt;/code&gt; yields to undefined. &lt;br&gt;
To access the author property of book object, we use the second argument of &lt;code&gt;forEach&lt;/code&gt; method. The second argument provides the object value that is required for this.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const books = {
    author: 'john doe',
    books: ['history', 'english', 'math'],
    findBooks() {
        this.books.forEach(function (item) { console.log(this.author, item) }, this)
    }
}
books.findBooks()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fytpz4skjsrlqa384vdlo.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fytpz4skjsrlqa384vdlo.png" alt="Image description"&gt;&lt;/a&gt;&lt;br&gt;
&lt;code&gt;this&lt;/code&gt; as the second argument is the reference of books object which is accessed from inside of the callback function. But all the Javascript methods don't provide &lt;code&gt;this&lt;/code&gt;(object) as argument.&lt;br&gt;
In this case, we use some techniques like, 1. data binding 2. arrow function 3. Assigning this to another variable(closure concept). All the details is discussed &lt;a href="https://dev.to/mdimran1409036/binding-this-3db4"&gt;in this article&lt;/a&gt;&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>this</category>
    </item>
    <item>
      <title>CRUD operation with Expressjs and MongoDB</title>
      <dc:creator>Md. Imran Hossain</dc:creator>
      <pubDate>Thu, 23 Dec 2021 17:50:20 +0000</pubDate>
      <link>https://dev.to/mdimran1409036/crud-operation-with-expressjs-and-mongodb-4ni7</link>
      <guid>https://dev.to/mdimran1409036/crud-operation-with-expressjs-and-mongodb-4ni7</guid>
      <description>&lt;p&gt;We will create a &lt;strong&gt;CRUD&lt;/strong&gt;(create, read, update and delete) application in this article with &lt;code&gt;express&lt;/code&gt;and &lt;code&gt;MongoDB&lt;/code&gt;. You need to have basic understandings of &lt;code&gt;MongoDB&lt;/code&gt;,  &lt;code&gt;express.js&lt;/code&gt;, &lt;code&gt;javascript&lt;/code&gt;, and &lt;code&gt;node package manager (npm)&lt;/code&gt; to install some packages. At the end of this tutorial, we will be able to create CRUD API’s.&lt;/p&gt;

&lt;p&gt;I will use &lt;a href="https://www.postman.com/"&gt;Postman &lt;/a&gt;to send the HTTP requests to the API  created by this application. Before dive in, make sure your computer has node installed&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Installations of necessary packages:&lt;/strong&gt; &lt;br&gt;
At first, we need to go to our command terminal and run following commands:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;mkdir crud-operation
cd crud operation
npm init -y
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;These will create a folder name crud-operation and install necessary node packages&lt;br&gt;
Now, install &lt;code&gt;nodemon&lt;/code&gt;using this command&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install -g nodemon
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;code&gt;nodemon&lt;/code&gt;is a tool that helps develop node.js-based applications by automatically restarting the node application when file changes in the directory are detected. This way we won’t have to start the server manually after a change in the index.js(we will talk about it later)&lt;/p&gt;

&lt;p&gt;We will need some more packages to install&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install dotenv cors mongodb express
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;dotenv is used to access the environment variables and cors is required to share cross origin resources.&lt;br&gt;
Create index.js file in the root directory of the application.&lt;br&gt;
Add the following two lines in the scripts object of  package.json file.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; "start": "node index.js",
 "start-dev": "nodemon index.js",
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So the basic configuration is completed. Now we will populate our index.js file to create our first-ever API.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const express = require('express')
const app = express()
const port = 5000

//middleware goes here section

app.get('/', (req, res) =&amp;gt; {
    res.send('Hello World!')
})

app.listen(port, () =&amp;gt; {
    console.log(`Example app listening at http://localhost:${port}`)
})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Run &lt;code&gt;npm run start-dev&lt;/code&gt; command in the terminal. I am using postman to load the HTTP request. So place this link  &lt;a href="http://localhost:5000/"&gt;http://localhost:5000/&lt;/a&gt; in the get request. &lt;strong&gt;Congratulation!&lt;/strong&gt; It will display the http response.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;hello world! &lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The Postman API response will be like so.&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--wbP8-sqJ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zq0tviw36wqru6r8wj5i.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--wbP8-sqJ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zq0tviw36wqru6r8wj5i.png" alt="Image description" width="880" height="310"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now, Let’s decode the above code. We essentially get an express instance and assign it to app. The server needs a port to load to API response, we used port 5000. Then we created a get request in the root URL ( ‘/’ means &lt;a href="http://localhost:5000/"&gt;http://localhost:5000/&lt;/a&gt;). The get request in reply gives us a response which is ‘hello world’. To access the server port 5000, we used the listen method which takes the port as the first argument and a callback function as second argument.&lt;/p&gt;

&lt;p&gt;Create a MongoDB account unless you have one. Add a user in the database access section. Put the user name and password in the .env file. Set ip address to 0.0.0.0/0 in the network access section. Add the following in the index.js file.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const { MongoClient } = require('mongodb');
require('dotenv').config()
const uri = `mongodb+srv://${process.env.DB_USER}:${process.env.DB_PASS}@cluster0.krune.mongodb.net/myFirstDatabase?retryWrites=true&amp;amp;w=majority`;
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });

async function run() {
    try {
        await client.connect();
        const database = client.db("CRUD");
        const blogsCollection = database.collection("blogs");

         //CRUD API’s goes here   
    } finally {
        // await client.close();
    }
}
run().catch(console.dir);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We have imported the MongoDB client. MongoDB gives us a connection uri to connect with MongoDB and using the username and password previously stored in the .env file, the uri string is updated. A database and a collection of the database are also created in the run function.&lt;/p&gt;

&lt;p&gt;So far we have covered the basic building blocks to start an express app.&lt;br&gt;
Now, we will create CRUD API’s. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Insert Data(create):&lt;/strong&gt;&lt;br&gt;
Add &lt;code&gt;app.use(express.json())&lt;/code&gt; in the "middleware goes here" section, and add following codes in the "CRUD API goes here" section.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;app.post('/blogs', async (req, res) =&amp;gt; {
    const blog = req.body
    const result = await blogsCollection.insertOne(blog);
    res.json(result)
})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;There are lots of HTTP request methods i.e. GET, POST, PUT, PATCH, DELETE. To create data, we use post method. The first argument is the request API and the callback function is used to perform the create operation. The callback function also take two arguments 1. req(the API request) 2. res(response of the API from server)&lt;br&gt;
The post data(i.e. Form data) from the request is assigned to the blog variable. The request body by default is a JSON object, to convert the JSON object into plain object, we need to use a middleware &lt;code&gt;app.use(express.json())&lt;/code&gt;.&lt;br&gt;
insertOne method is used to add the parsed request data to insert the blogCollection. In the end, the response of the api is sent through res.json(result).&lt;/p&gt;

&lt;p&gt;If the data is inserted, the response will be 200 like so, &lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--LH5AnKst--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/aaqw9k4ndz6ia3pqpw5x.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--LH5AnKst--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/aaqw9k4ndz6ia3pqpw5x.png" alt="Image description" width="880" height="344"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Find data : (Read)&lt;/strong&gt;&lt;br&gt;
Get all blogs:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;app.get('/blogs', async (req, res) =&amp;gt; {
    const query = {};
          const cursor = blogsCollection.find(query);
          const result = await cursor.toArray();
           res.json(result)
        })
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now we use the get method and the URL is the same as the post method. As we want to get all the data, the query is empty, and the find method is used to fetch all the data. The fetched data is converted into an array and sent as a response. &lt;br&gt;
The postman response will be like so,&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--s7fLpL8B--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9csbyex3dbcjl5ytift6.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--s7fLpL8B--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9csbyex3dbcjl5ytift6.png" alt="Image description" width="880" height="362"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Find a single blog:&lt;/strong&gt;&lt;br&gt;
First we need to add &lt;code&gt;const ObjectID = require('mongodb').ObjectID&lt;/code&gt; at the top.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;app.get('/blogs/:id', async (req, res) =&amp;gt; {
     const blogId = req.params.id;
     const query = { _id: ObjectID(blogId) };
     const result = await blogsCollection.findOne(query);
     res.json(result)
   })
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;To find a single blog we have passed the id parameter to the API and the parameter is accessed by req.params.id. Now we have to match the blogId to the id of blogs of the server. The result is sent as a response. The ObjectId is required to match the id to blogId.&lt;br&gt;
The postman response will be like so,&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--hT5SXGW6--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q7uxlr3vew63d7q5bm1v.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--hT5SXGW6--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q7uxlr3vew63d7q5bm1v.png" alt="Image description" width="880" height="286"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Update:(put method)&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;app.put('/blogs/:id', async (req, res) =&amp;gt; {
      const blogId = req.params.id;
      const blog = req.body;
      const filter = { _id: ObjectID(blogId) };
      const updateBlog = {
            $set: {
                title: blog.title,
                body: blog.body
               },
            };
      const result = await blogsCollection.updateOne(filter, updateBlog);
      res.json(result)
})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;At first, we make a query to find the id we want to update using the api params and fetched the data that needs to be updated. The update fields are set and updateOne method is used to update the data.&lt;br&gt;
Postman response will be like so,&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--0GdV5PeH--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/om4sub8s43b0qwp20o74.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--0GdV5PeH--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/om4sub8s43b0qwp20o74.png" alt="Image description" width="880" height="368"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Delete:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;app.delete('/blogs/:id', async(req,res)=&amp;gt;{
      const blogId = req.params.id;
      const query = { _id: ObjectID(blogId) };
      const result = await blogsCollection.deleteOne(query);
      res.json(result)
 })
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;‘Delete’ method is used to delete a document from the database. Using the parameter, query is made and then deleteOne method is used to delete that. Finally, the response result is sent as JSON.&lt;br&gt;
The postman response will be like so,&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--3f6eI2yI--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7jjzremvgkz6unykzn9i.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--3f6eI2yI--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7jjzremvgkz6unykzn9i.png" alt="Image description" width="880" height="357"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;So that’s pretty much it. This way we can perform CRUD operation with node and MongoDB.&lt;br&gt;
See codes at &lt;a href="https://github.com/mdimran1409036/crud-api-blog"&gt;Github&lt;/a&gt;&lt;/p&gt;

</description>
      <category>node</category>
      <category>mongodb</category>
      <category>javascript</category>
    </item>
    <item>
      <title>Context API: Why and How</title>
      <dc:creator>Md. Imran Hossain</dc:creator>
      <pubDate>Wed, 22 Dec 2021 17:23:48 +0000</pubDate>
      <link>https://dev.to/mdimran1409036/context-api-why-and-how-lph</link>
      <guid>https://dev.to/mdimran1409036/context-api-why-and-how-lph</guid>
      <description>&lt;h2&gt;
  
  
  Motivation:
&lt;/h2&gt;

&lt;p&gt;One of the key features of React is one-way data binding which enables us to send props data from only parents to children. This is very useful as it’s easy to understand from where the data is passed into that component. But imagine a situation, where we are required to send data to more than 5 layers down! &lt;/p&gt;

&lt;p&gt;The code starts to get messy from now on. Besides, it requires a lot of code repetition, unnecessary data passing to children which don’t need the data for themselves but to pass to their children, and difficult to maintain. This scenario is termed ‘prop drilling’.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;div user={user}&amp;gt;  —(1)
  &amp;lt;div  user={user}&amp;gt; —(2) 
    &amp;lt;div  user={user}&amp;gt;  —(3)  
      &amp;lt;div  user={user}&amp;gt;  —(4)
        &amp;lt;div  user={user}&amp;gt;  —(5)
          &amp;lt;div  user={user}&amp;gt;  —(6)
         &amp;lt;div  user={user}&amp;gt; —(7)
           &amp;lt;h2&amp;gt; {user.name} &amp;lt;/h2&amp;gt;
             &amp;lt;div&amp;gt;
          &amp;lt;/div&amp;gt;
        &amp;lt;/div&amp;gt;
      &amp;lt;/div&amp;gt;
    &amp;lt;/div&amp;gt;
  &amp;lt;/div&amp;gt;
&amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;From the above abstraction, we see the prop is drilled to 7 layers down to get the user props data which is very difficult to keep track of. There is a better approach to avoid this situation which is using &lt;code&gt;context API&lt;/code&gt;. Context API is used to create centralized data, much like global variables which can be accessed from anywhere. One may think of &lt;code&gt;Redux&lt;/code&gt;(acts like a store that stores data and the store can be accessed from anywhere), but that is used in large and complex applications that require a lot of states to maintain. But that’s another story, we will stick to context API for now. &lt;/p&gt;

&lt;h2&gt;
  
  
  How to use:
&lt;/h2&gt;

&lt;ol&gt;
&lt;li&gt;First, we will create a folder in the src folder named contexts (not required. just a convention)&lt;/li&gt;
&lt;li&gt;Now, we will create a provider, our case it’s AuthProvider. I will use functional component for this tutorial. So, let’s create AuthProvider component like so.
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt; import React from 'react';
  const AuthProvider = () =&amp;gt; {
    return (
        &amp;lt;div&amp;gt;         
        &amp;lt;/div&amp;gt;
    );
  };
  export default AuthProvider;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;Now create a context (AuthContext) above the AuthProvider component and rename ‘div’ inside the component to AuthContext.Provider like so.
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import AuthProvider from './Context/AuthProvider';
import User from './Component/User';
function App() {
  return (
    &amp;lt;div&amp;gt;
      &amp;lt;AuthProvider&amp;gt;
        &amp;lt;h2&amp;gt;Context API intro&amp;lt;/h2&amp;gt;
        &amp;lt;User&amp;gt;&amp;lt;/User&amp;gt;
      &amp;lt;/AuthProvider&amp;gt;
    &amp;lt;/div&amp;gt;

  );
}
export default App;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;React provides createContext API, which Creates a Context object. When React renders a component that subscribes to this Context object it will read the current context value from the closest matching Provider above it in the tree. &lt;br&gt;
Notice, the created AuthContext is used is AuthProvider and provided a user as value. Also, children is taken as props and AuthContext is exported as the context will be consumed later.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;So far we have created a context and provided a value to the AuthProvider. Now we will create a custom hook inside a hooks folder named useAuth, where we will consume the context like so
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { useContext } from "react";
import { AuthContext } from "../Context/AuthProvider";
const useAuth = () =&amp;gt; useContext(AuthContext)
export default useAuth;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;useContext hook is used to consume the context we created earlier. &lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Use AuthProvider component to the top of App.js so that every children gets access to the context api provided value. Meanwhile, create another component inside component folder named User.js like so
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import AuthProvider from './Context/AuthProvider';
  import User from './Component/User';
  function App() {
    return (
      &amp;lt;div&amp;gt;
        &amp;lt;AuthProvider&amp;gt;
          &amp;lt;h2&amp;gt;Context API intro&amp;lt;/h2&amp;gt;
          &amp;lt;User&amp;gt;&amp;lt;/User&amp;gt;
        &amp;lt;/AuthProvider&amp;gt;
      &amp;lt;/div&amp;gt;
    );
  }
  export default App;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;Now we will use the context api provided value using the custom hook useAuth and display the user info.
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React from 'react';
 import useAuth from './../hooks/useAuth';
 const User = () =&amp;gt; {
    const user = useAuth()
    console.log(user);
    return (
        &amp;lt;div&amp;gt;
            user name: {user.name}
        &amp;lt;/div&amp;gt;
    );
 };
 export default User;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Finally, we have access to the value that was provided in the AuthProvider.&lt;/p&gt;

&lt;p&gt;All the corresponding codes will be available &lt;a href="https://github.com/mdimran1409036/context-api-blog"&gt;here&lt;/a&gt;. &lt;/p&gt;

</description>
      <category>react</category>
      <category>javascript</category>
      <category>contextapi</category>
    </item>
    <item>
      <title>Diving into array methods and loops</title>
      <dc:creator>Md. Imran Hossain</dc:creator>
      <pubDate>Tue, 21 Dec 2021 08:24:25 +0000</pubDate>
      <link>https://dev.to/mdimran1409036/diving-into-array-methods-and-loops-3l9f</link>
      <guid>https://dev.to/mdimran1409036/diving-into-array-methods-and-loops-3l9f</guid>
      <description>&lt;h2&gt;
  
  
  Introduction:
&lt;/h2&gt;

&lt;p&gt;Array is a collection of items.  An array has two basic properties.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Index&lt;/li&gt;
&lt;li&gt;value&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Let’s consider a number array with 10 elements.&lt;/p&gt;

&lt;p&gt;const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]&lt;/p&gt;

&lt;p&gt;Array elements are kept inside a square bracket and Its index starts with 0. So, the numbers array index starts from 0 to 9 and the values are 1 to 10. Array is one of the most important topics in Javascript and you should have a basic understanding of its methods and iteration procedure.&lt;/p&gt;

&lt;p&gt;We will discuss in brief all the methods related to array and later we will talk about the array iteration.&lt;/p&gt;

&lt;h2&gt;
  
  
  Array methods:
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;Array length&lt;/strong&gt;: To compute the array length this method is used.&lt;br&gt;
The length of the above array:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;numbers.length // 10
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This will return 10&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Finding index of an element:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;numbers.indexOf(5) //4
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If the number will be not found, it will return -1&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Array to string:&lt;/strong&gt;&lt;br&gt;
Sometimes we need to convert array elements to simple string.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;numbers.toString() //1,2,3,4,5,6,7,8,9,10
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Array join method:&lt;/strong&gt;&lt;br&gt;
Join method also converts an array to string, in addition it will add separator.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;numbers.join(' * ') //1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Add an array element at the last:&lt;/strong&gt;&lt;br&gt;
We can add elements at the end of the array by using push method.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;numbers.push(11) 
console.log(numbers)    //  [1,2,3,4,5,6,7,8,9,10,11]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Remove an item from array at the last:&lt;/strong&gt;&lt;br&gt;
Array elements can be removed using pop method from the last of an array.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;numbers.pop()  // 11 
console.log(numbers) // [1, 2, 3, 4, 5, 6, 7,8,9,10]

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Add an element at the start of an array:&lt;/strong&gt;&lt;br&gt;
Unshift method is used to add an element to the start of an array.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;numbers.unshift(0)
console.log(numbers) // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Remove an element from the start of an array:&lt;/strong&gt;&lt;br&gt;
Use Shift method to remove an element from the beginning of an array.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;numbers.shift() //0
console.log(numbers) //[1, 2, 3, 4, 5, 6, 7, 8, 9,10]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Merging Two arrays:&lt;/strong&gt;&lt;br&gt;
Two array can be merged using concat method.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const numbers2 = [11,12,13,14.15]
const mergedArray = numbers.concat(numbers2) //[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Slice Method:&lt;/strong&gt;&lt;br&gt;
To make a copy of an array element, we use slice method. Slice method is very useful because of its immutability nature. Immutability property means the original array will be unchanged after slicing elements from an array. Slice method returns a new array containing the extracted elements.&lt;br&gt;
Syntax: &lt;br&gt;
       &lt;code&gt;array.slice(start, end)&lt;/code&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;If start is undefined, slice starts from index 0&lt;/li&gt;
&lt;li&gt;If start is greater than the length of an array, an empty array is returned&lt;/li&gt;
&lt;li&gt;Slice extracts up to but not including end&lt;/li&gt;
&lt;li&gt;If end is omitted, slice extracts through the end of the sequence (&lt;code&gt;arr.length&lt;/code&gt;).&lt;/li&gt;
&lt;li&gt;If end is greater than the length of the sequence, slice extracts through to the end of the sequence (&lt;code&gt;arr.length&lt;/code&gt;).
&lt;/li&gt;
&lt;/ul&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const fruits = ['apple', 'banana', 'mango', 'orange', 'pine apple'.'guava']
let slicedFruits = fruits.slice(1,4) // ['banana', 'mango', 'orange' ] 
slicedFruits = fruits.slice(2) //['mango', 'orange', 'pine apple', 'guava']
slicedFruits = fruits.slice(2, 10) //['mango', 'orange', 'pine apple', 'guava']
slicedFruits = fruits.slice() // ['apple', 'banana', 'mango', 'orange', 'pine apple'.'guava']

console.log(fruits) // ['apple', 'banana', 'mango', 'orange', 'pine apple'.'guava']
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;Notice, after slicing elements from the fruits array, still the fruits array hasn’t been changed&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Splice method:&lt;/strong&gt;&lt;br&gt;
The splice method changes the content of an array by removing elements from the array and returning a new array with the removed elements. The main difference between slice and splice is: slice makes a copy of array elements and doesn’t modify the original array whereas splice removes elements from the array and modifies the original array (&lt;code&gt;mutability&lt;/code&gt;) in the process.&lt;/p&gt;

&lt;p&gt;Syntax:&lt;br&gt;
    &lt;code&gt;array.splice(start, deleteCount)&lt;/code&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Start is the index at which to start changing the array
deleteCount is an integer indicating the number of elements in the array to remove from start. &lt;/li&gt;
&lt;li&gt;If deleteCount is omitted, all the elements from start to the end of the array will be deleted
&lt;/li&gt;
&lt;/ul&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const fruits = ['apple', 'banana', 'mango', 'orange', 'pine apple', 'guava'] 
let splicedFruits = fruits.splice(1, 2) // ['banana', 'mango']
console.log(fruits) // ['apple', 'orange', 'pine apple','guava']
splicedFruits = fruits.splice(1) // ['orange', 'pine apple', 'guava']
console.log(fruits) // ['apple']
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;Notice, the original fruit array is changing after every split method.&lt;/p&gt;
&lt;h2&gt;
  
  
  Array Iteration/ Loops:
&lt;/h2&gt;

&lt;p&gt;Array iteration is one of the most important things to iterate every element and access its properties. This can be done in a lot of ways including the tradition for loop to higher-order functions like map, forEach, find, etc. We will cover them in detail.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;For loop:&lt;/strong&gt;&lt;br&gt;
For loop is the basic loop to loop through an array.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const fruits = ['apple', 'banana', 'mango', 'orange', 'pine apple', 'guava'] 
for(let i=0; i&amp;lt;fruits .length; i++){
        console.log(fruits [i])
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;output: apple banana mango orange pine guava&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;While loop:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let i=0; 
while(i&amp;lt;fruits .length) {
console.log(fruits [i]);
 i++;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;output : apple banana mango orange pine guava&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Do while loop:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let i=0;
do(console.log(fruits [i]))
while(i&amp;lt;fruits .length)
i++;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;output : apple banana mango orange pine guava&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;For of loop:&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;for(let fruit of fruits){
   console.log(fruit)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;output: apple banana mango orange pine guava&lt;/p&gt;

&lt;p&gt;So using these loops we can easily iterate the array elements. But what if we want to return an array after iterating the array elements or execute a certain function for each of the elements! This is really useful when we want to modify the array elements, filter array elements based on a certain condition, or find only an element based on certain criteria. These functionalities can be done using some array methods which are known as higher-order function( a function/ method which takes a function as an argument or return a function) i.e. forEach(), map(), filter(), reduce()&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;ForEach&lt;/strong&gt;:&lt;br&gt;
    forEach method takes a function( a callback function that takes index and current element as argument) as its argument and executes a provided function once for each array element. Its return value is undefined.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fruits.foreach((item, index)=&amp;gt;{console.log(item)})
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;output: apple banana mango orange pine guava&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Map:&lt;/strong&gt;&lt;br&gt;
Similar to forEach method but it returns an array and takes a function as its argument.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const mappedFruits =  fruits.map((item, index)=&amp;gt;{ return index + ' '+ item})
console.log(mappedFruits)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Output: ['0 apple', '1 banana', '2 mango', '3 orange', '4 pine apple', '5 guava']&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Filter&lt;/strong&gt;: &lt;br&gt;
The filter method is used to filter elements based on certain conditions. It also returns an array.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const filteredFruits = fruits.filter(item =&amp;gt; item.includes('an'))
console.log(filteredFruits)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Output: ['banana', 'mango', 'orange']&lt;/p&gt;

&lt;p&gt;What this code eventually does is, find the items that include the two character ‘an’ , filter them  and returns them as an array&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Find:&lt;/strong&gt;&lt;br&gt;
Find  method is self-explanatory. It finds the element from an array based on certain conditions and behaves like the filter method except for returning only the first element that matches the condition.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const findFruit = fruits.find(item=&amp;gt; item.includes('an'))
console.log(findFruit)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Output: ‘banana’&lt;br&gt;
&lt;strong&gt;Reduce:&lt;/strong&gt;&lt;br&gt;
The reduce() method executes a user-supplied “reducer” callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element. The final result of running the reducer across all elements of the array is a single value.&lt;br&gt;
Sounds overwhelming? Well, let's take an example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const numbers = [10, 20, 40, 23, 42]
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let’s calculate the sum of the array elements using reduce() method.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const sum = numbers.reduce((previousValue, currentValue)=&amp;gt; previousValue+ currentValue, 0);
console.log(sum)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Output: 135&lt;/p&gt;

&lt;p&gt;Reduce method takes two arguments: 1. Reducer call-back function 2. Initial value. In our case, the initial sum value is given 0. The reducer callback function takes 4 arguments: previous value, current value, current index, and the array to traverse. The third and fourth are optional. &lt;/p&gt;

&lt;p&gt;In our case, we took two arguments. The current value is the current array item and the previous value is the previous iteration value which is set to 0 if the initial value is set to 0 or not defined and after the first iteration the return value is assigned to the previous value and the iteration is going on.&lt;/p&gt;

</description>
      <category>javascript</category>
      <category>array</category>
    </item>
    <item>
      <title>Understanding CSS Flexbox</title>
      <dc:creator>Md. Imran Hossain</dc:creator>
      <pubDate>Sun, 19 Dec 2021 16:47:13 +0000</pubDate>
      <link>https://dev.to/mdimran1409036/understanding-css-flex-box-52he</link>
      <guid>https://dev.to/mdimran1409036/understanding-css-flex-box-52he</guid>
      <description>&lt;p&gt;Flexbox, The first thing that comes to our mind designing a layout. Layout designing was never been this easy before flexbox is introduced.&lt;br&gt;
From designing a simple navbar to a very complex UI, Flexbox is a must because of its simple structure and easy-to-maintain nature.&lt;br&gt;
Before diving into the brief concept, make sure you know the basic building blocks of HTML5 and also CSS.&lt;/p&gt;
&lt;h2&gt;
  
  
  Basic Building Blocks:
&lt;/h2&gt;

&lt;p&gt;A Flexbox has two major parts. First is the &lt;code&gt;flex container&lt;/code&gt; and second one is &lt;code&gt;flex items&lt;/code&gt;. Flex container is the wrapper of flex items and Flex items are the layout elements.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;section&amp;gt;
 &amp;lt;article&amp;gt;
  &amp;lt;p&amp;gt;lorem ipsum dolor ip somet&amp;lt;/p&amp;gt;
 &amp;lt;/article&amp;gt;
 &amp;lt;article&amp;gt;
  &amp;lt;p&amp;gt;lorem ipsum dolor ip somet&amp;lt;/p&amp;gt;
 &amp;lt;/article&amp;gt;
 &amp;lt;article&amp;gt;
  &amp;lt;p&amp;gt;lorem ipsum dolor ip somet&amp;lt;/p&amp;gt;
 &amp;lt;/article&amp;gt;
&amp;lt;/section&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here the section is the flex container and all the articles are flex items. To style this layout we need to use the flex property in the flex container.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;display: flex;
flex-direction: row;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The possible output of this code is the articles will be displayed in a row.&lt;br&gt;
By default, flex-direction is set as row. There is also another property of flex-direction is the column. The main concept behind this is the two major axes of displaying layout. They are 1. Main axis 2. Cross axis.&lt;br&gt;
&lt;strong&gt;Main axis:&lt;/strong&gt; The main axis is the axis running in the direction the flex items are laid out in (for example, as rows across the page, or columns down the page.) The start and end of this axis are called the main start and main end.&lt;br&gt;
&lt;strong&gt;Cross axis:&lt;/strong&gt; The cross axis is the axis running perpendicular to the direction the flex items are laid out in. The start and end of this axis are called the cross start and cross end.&lt;/p&gt;
&lt;h2&gt;
  
  
  Wrapping:
&lt;/h2&gt;

&lt;p&gt;If the number of articles will be increased to 10 or so then only a row will not capable to display the flex items properly. And that's where the wrapping comes as a savior. It organizes the flex items in such a way that every item will take the minimum width of available width and when no space is available to rest of the flex items will be wrapped to a new line. Wrapping prevents the document from overflowing.&lt;br&gt;
&lt;code&gt;flex-wrap: wrap&lt;/code&gt;&lt;br&gt;
The shorthand of flex-direction and flex-wrap:&lt;br&gt;
&lt;code&gt;flex-flow: column wrap&lt;/code&gt;&lt;/p&gt;
&lt;h2&gt;
  
  
  Horizontal and vertical alignment:
&lt;/h2&gt;

&lt;p&gt;So far, We can position our layout elements into rows or columns and if the layout elements overflow, we use wrap to prevent it.&lt;br&gt;
The biggest advantage of flexbox is, it calculates the available space and divides them equally irrespective of the width of the webpage screen. This available space can be aligned both along the horizontal and vertical axis.&lt;br&gt;
If we want to center horizontally and divide the whole space with equal spacing, we want to use the justify-content property.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;section{
 display: flex;
 justify-content: center;
 flex-flow: row wrap;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In addition to this, we may need to align them vertically center. In order to do this, we just need to add the property &lt;code&gt;align-items: center&lt;/code&gt; with the above code.&lt;br&gt;
Notice, here we used flex-direction as a row, it would be nice if you try it for direction as a column.&lt;br&gt;
Other &lt;code&gt;justify-content&lt;/code&gt; properties: &lt;em&gt;space-around, space-between, flex-start and flex-end&lt;/em&gt;&lt;br&gt;
&lt;code&gt;align-items&lt;/code&gt; properties: _center, flex-start, flex-end, stretch, baseline&lt;/p&gt;
&lt;h2&gt;
  
  
  Controlling Flex items:
&lt;/h2&gt;

&lt;p&gt;Till now, we only have worked with flex containers, there are also some properties for flex items that give us more power over flex items.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Flex&lt;/strong&gt;&lt;br&gt;
Flex property has three values specifying-&lt;br&gt;
A unitless value representing how much space an item will take, which is called &lt;code&gt;flex-grow&lt;/code&gt; property&lt;br&gt;
Another unitless value representing how much an item will shrink in order to prevent overflow, which is called &lt;code&gt;flex-shrink&lt;/code&gt;&lt;br&gt;
The last value is the minimum width an item will take, commonly known as &lt;code&gt;flex-basis&lt;/code&gt;&lt;br&gt;
There is a shorthand comprising the three values. Flex shrink is used for advanced cases, so we will omit that for now.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;article {
  flex: 1 200px;
}

article:nth-of-type(3) {
  flex: 2 200px;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;These code blocks suggest the entire width will be a total of 4(1+1+2) fractions and the first two elements will get a minimum of 200px width and if more width is available then they will take 1/4th of the remaining space each. Only the third element will get half of the total space.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Align self&lt;/strong&gt;&lt;br&gt;
In addition to the &lt;code&gt;align-items&lt;/code&gt; property that is used in the flex container, &lt;code&gt;align-self&lt;/code&gt;overrides the &lt;code&gt;align-items&lt;/code&gt; property.&lt;br&gt;
&lt;code&gt;align-self&lt;/code&gt; is specified in the flex items.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;align-self: flex-end;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Ordering flex items&lt;/strong&gt;&lt;br&gt;
By default, each flex item has the order of 0 and the order will be according to their declared position. This order can be changed using the order property of flex items.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;article:first-child{
 order:1
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This eventually moves the first element of the flex items to the last. The order value can be negative. In that case, a negative value will take the initial position.&lt;/p&gt;

&lt;p&gt;So these are the things you need to know to get started with Flexbox. To get the more clear and more brief idea, I suggest &lt;a href="https://developer.mozilla.org/en-US/docs/Learn/CSS/CSS_layout/Flexbox"&gt;MDN's CSS layout documentation&lt;/a&gt;.&lt;/p&gt;

</description>
      <category>css</category>
      <category>flexbox</category>
    </item>
  </channel>
</rss>
