<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Kazi Mashry on Medium]]></title>
        <description><![CDATA[Stories by Kazi Mashry on Medium]]></description>
        <link>https://medium.com/@kazi-mashry?source=rss-fb8472c54deb------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*9ITtf7DKGYnW11LQ3XK3lg.jpeg</url>
            <title>Stories by Kazi Mashry on Medium</title>
            <link>https://medium.com/@kazi-mashry?source=rss-fb8472c54deb------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 02:17:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kazi-mashry/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Swift concurrency — Part 2: GCD]]></title>
            <link>https://kazi-mashry.medium.com/swift-concurrency-part-2-gcd-32b68d62a32d?source=rss-fb8472c54deb------2</link>
            <guid isPermaLink="false">https://medium.com/p/32b68d62a32d</guid>
            <category><![CDATA[gcd]]></category>
            <category><![CDATA[dispatchqueue]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Kazi Mashry]]></dc:creator>
            <pubDate>Tue, 16 Apr 2024 00:44:59 GMT</pubDate>
            <atom:updated>2024-04-16T00:44:59.859Z</atom:updated>
            <content:encoded><![CDATA[<h3>Swift concurrency — Part 2: GCD</h3><p>Hello folks. In part 2 on swift concurrency, we will explore a few topics on GCD. In part 1 I have covered a few basic topics and terminologies that might require in this article. So let’s get started.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/1*CSTeRsUX7Uwj-qv9VsoOeA.png" /></figure><p><strong>What is GCD?</strong><br>GCD or Grand Central Dispatch is the queue-based API, provided by Apple, to manage concurrent operations. We can submit our tasks to a concurrent or serial queue in sync or async manner using GCD. GCD takes care of the rest. Of course, we have much more control over this. This article will cover a few of them.</p><p><strong>Dispatch Queue:</strong> The dispatch queue is the abstraction layer on top of the queues. GCD manages those queues and tasks are submitted to the thread pool to be executed. We can submit a task to the dispatch queue in the form of closure. This submission of the tasks might be synchronous or asynchronous based on whether we want our current working thread should wait for the task to be completed or not. There are three types of queues,<br>1. Main queue<br>2. Global concurrent queue<br>3. Custom queue<br>Let’s look at each of the queues one by one.</p><p><strong>Main Queue:</strong> Main queue is a system-provided serial queue that uses the main thread. UIKit is tied to the main queue. So, if we want to update the UI we have to do it using the main queue only. Here is how we can use the main queue.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/762f9a4c43728701629242aa200082fa/href">https://medium.com/media/762f9a4c43728701629242aa200082fa/href</a></iframe><p><strong>Global concurrent queue:</strong> Global concurrent queues are the system-provided concurrent queues. These queues don’t use the main thread. Rather they use other threads of the thread pool. Quality of service or QoS prioritizes these queues. There are four types of quality of services:<br><strong>1. User-interactive:</strong> It’s used when dealing with updating UI or animation. It has the highest priority. The task is done virtually instantaneously.<br><strong>2. User-initiated:</strong> It is used when we need immediate results. It has the second highest priority. The task is done nearly instantaneously, such as a few seconds or less.<br><strong>3. Utility:</strong> It’s used for long-running tasks where a user is aware of this. It has the third-highest priority. It takes a few seconds to a few minutes.<br><strong>4. Background:</strong> If a user is not aware of the task or the task is not visible to the user immediately this QoS is used. It has the lowest priority among all the QoSs. It takes significant time, such as minutes or hours.<br>There are two more QoS<br><strong>1. Default:</strong> The task that has no QoS information assigned is treated as default. It has priority between user-initiated and utility. <br><strong>2. Unspecified:</strong> It has the lowest among all six QoSs<br>Let’s look at the code below</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/65f2e366e72a8f07e657d24d0d434b0c/href">https://medium.com/media/65f2e366e72a8f07e657d24d0d434b0c/href</a></iframe><p>What do you think, what will be the output? Well, We can’t exactly guess the output, since the closures are in the concurrent queue asynchronously. But we can be sure that <br>1. the execution of the user-interactive will be completed before the user-initiated. <br>2. user-initiated will be completed before the utility<br>3. utility will be completed before the background</p><p><strong>Custom Queue:</strong> Apple has provided the power to create our own queues besides the main and global concurrent queues. Custom queues are created on the system-provided queues, but we can customize them through parameters according to our needs.</p><p><strong>Dispatch Group:</strong> We can execute tasks asynchronously and concurrently in the dispatch queue. Where we don’t know when all the tasks are completed. But in some cases, we might need to know that all the tasks are finished executing. For example, in the splash screen, we might proceed further if all the responses from the APIs are received. In such cases, we can group the tasks and have a callback when all of them are completed. Dispatch group provides us with such power. Dispatch group gives us four functions to achieve this goal:<br>1. enter(): We call this function when a new task is added to the dispatch group<br>2. leave(): We call this function when the task execution is completed <br>3. notify(): This function is called when all the tasks are done executing. We pass a callback with the notify() function. When the system calls the notify() function, it executes the callback passed to it.<br>4. wait(): We use this function in such cases where we don’t need all the concurrent tasks to be finished within a certain period and we also need to know whether every task execution is finished or not. It holds the execution on the current thread. So we must be aware not to call it from the main thread.</p><p>Here’s how we can use enter, leave, and notify functions to achieve our goal:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5570321607f9a3bd7ad1e0710fb560c6/href">https://medium.com/media/5570321607f9a3bd7ad1e0710fb560c6/href</a></iframe><p>Here is how we can use the wait() function instead of the notify() function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dbd9d7aeea69393e0fba3927d5c9690b/href">https://medium.com/media/dbd9d7aeea69393e0fba3927d5c9690b/href</a></iframe><p><strong>Dispatch work item:</strong> Dispatch work item is a feature of GCD where we can encapsulate a block of code, dispatch it in the dispatch queue or dispatch group, and cancel the task if the execution has not started. The main feature of this API is to cancel the task anytime before the execution starts. Imagine, in a weather app search box, we need to do an API call to get the list of all the suggested cities as per user click. But instead of an immediate API call for per-user keystroke, we’ll wait for 1 second for the last keystroke and then call the API. Here is how we can do that:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/03ed8337f3ef1c6586e4407c91b7a30b/href">https://medium.com/media/03ed8337f3ef1c6586e4407c91b7a30b/href</a></iframe><p><strong>Dispatch barrier:</strong> Dispatch barrier is another cool feather of GCD where we can set a barrier for the next tasks of a queue to be executed before the previous task is completed. It causes the work item to act as a barrier block when it is submitted to the queue. Here is a diagram for visual representation:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/774/1*Jd7cVhHLGgR39u9NbKRXcw.png" /><figcaption>Barrier for completing the previous tasks before starting the new tasks.</figcaption></figure><p>Here is an example of a dispatch barrier:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ce2c1d180cd8c14ec932fb12ef5f0469/href">https://medium.com/media/ce2c1d180cd8c14ec932fb12ef5f0469/href</a></iframe><p>Even though we’re using a concurrent queue, the output will be like this below because of the barrier flag used to update the shared array:</p><pre>Added 1 to array<br>Added 2 to array<br>Added 3 to array<br>Array contents: [1, 2, 3]<br>Array contents: [1, 2, 3]<br>Added 4 to array<br>Array contents: [1, 2, 3, 4]</pre><p><strong>Dispatch Semaphore:</strong> GCD didn’t just stop there by giving us features, like the dispatch barrier, where we can make the shared resource accessible to one thread at a time. It gave programmers further power to control the number of threads that have permission to access a shared resource simultaneously. Here is how we can use semaphore:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d3a2f6c55d0bbdd2ad3746b932fafd27/href">https://medium.com/media/d3a2f6c55d0bbdd2ad3746b932fafd27/href</a></iframe><p>This will make sure that the shared array is accessed by one thread at a time since the value of <em>numberOfThreadsAllowedToAccessSharedReource</em> is 1.</p><p>So, that’s it for this article. Thank you for making it so far. If you have any doubts, or if you think there is any misexplained topic let me know in the comment section. Happy coding!!</p><p><strong>References:</strong><br>1. <a href="https://www.youtube.com/playlist?list=PLSbpzz0GJp5RTrjum9gWTqPhM4L3Kop0S">https://www.youtube.com/playlist?list=PLSbpzz0GJp5RTrjum9gWTqPhM4L3Kop0S</a><br>2. <a href="https://developer.apple.com/library/archive/documentation/Performance/Conceptual/EnergyGuide-iOS/PrioritizeWorkWithQoS.html">https://developer.apple.com/library/archive/documentation/Performance/Conceptual/EnergyGuide-iOS/PrioritizeWorkWithQoS.html</a><br>3. <a href="https://betterprogramming.pub/the-complete-guide-to-concurrency-and-multithreading-in-ios-59c5606795ca">https://betterprogramming.pub/the-complete-guide-to-concurrency-and-multithreading-in-ios-59c5606795ca</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=32b68d62a32d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift concurrency — Part 1: Basics]]></title>
            <link>https://kazi-mashry.medium.com/swift-concurrency-part-1-basics-a8433910d141?source=rss-fb8472c54deb------2</link>
            <guid isPermaLink="false">https://medium.com/p/a8433910d141</guid>
            <category><![CDATA[threads]]></category>
            <category><![CDATA[swif]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[synchronous]]></category>
            <dc:creator><![CDATA[Kazi Mashry]]></dc:creator>
            <pubDate>Sat, 13 Apr 2024 10:05:34 GMT</pubDate>
            <atom:updated>2024-04-13T10:05:34.413Z</atom:updated>
            <content:encoded><![CDATA[<h3>Swift concurrency — Part 1: Basics</h3><p>This series of articles is about swift concurrency and GCD(Grand Central Dispatch). I’ll try to explain the relevant topics in my language. But before jumping into the “Swift concurrency”, we need to know a few basics first. So what are those basics?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z8ymEnb8Cmmay0IUYX4mOw.jpeg" /><figcaption>Credit: freepik.com</figcaption></figure><h3><strong>Basics:</strong></h3><p>We need to know about a few terms like concurrency, parallelism, thread, thread pool, serial queue, concurrent queue, synchronous, and asynchronous. So let’s start one by one.</p><p><strong>Concurrency:</strong> Imagine, you have two books opened in front of you. You’re reading those two books at the “same time”. Is it possible for you to read those two books at the “same time”? Or is it something like you’re reading one line from a book, then “switching back” to another book and reading one line from that? Of course, you’ll go for the second approach. And it’s the concurrency.<br>Now, think about a CPU core. It does the same for achieving concurrency. How? When two or more tasks have to be executed, it executes a few things of a task, then switches the context and executes a few things of another task. <br>So, in concurrency, multiple tasks are executed by the shared resource(Or, CPU core in this case).</p><p><strong>Parallelism:</strong> Now, think of a scenario where you’re reading through your monitor and typing with the keyboard at the same time. Here, multiple resources like, your eyes for reading and hands for typing, are involved. <br>In the modern computer system, we have multiple CPU cores. These cores can do their tasks. So for an 8-core CPU, 8 tasks can be simultaneously executed.</p><p>So the key difference between concurrency and parallelism is that, in concurrency, a single resource is involved for executing multiple tasks. Whereas, in parallelism, we have multiple resources for executing multiple tasks.</p><p><strong>Thread:</strong> A thread is the smallest sequence of programmed instruction. It has its own set of registers, stacks, and other resources. The scheduler manages it and it’s part of OS. So the question might arise why do we need threads? <br>Well, in concurrency, the CPU core needs to switch the context. So context switching means, the next high-priority task from the task queue will be loaded into the registers and be prepared for the execution. This seems to be quite time-consuming, right? So we can minimize this time using threads. How? The answer is, that tasks from the task queue(serial or concurrent, we’ll discuss it later) are dequeued from the queue and loaded into the registers of unassigned threads. Now whenever the CPU core decides to hop into another task to execute it comes to a thread, that is preloaded. Other than that, a thread has other tasks to do which are managed by OS.</p><p><strong>Threadpool:</strong> By name, we can understand, that it is a collection of threads. The OS manages threadpool. Whenever any thread of a thread pool gets freed, a task from task queue(serial or concurrent), is dequeued and loaded into the thread.</p><p><strong>Serial queue:</strong> To manage multiple tasks, OS uses queues to store the unexecuted tasks and assign them to a thread in the FIFO manner(since this is a queue). But what is the serial queue? The serial queue is a queue where a task is dequeued only when a thread is free and the previous task is completed. <br>So you might ask a question, does a serial queue use one thread only, since it’s fetching a task only after the previous task is completed?</p><blockquote><strong>The answer is, yes, it uses one thread at a time, but not necessarily the same thread(NSThread object).</strong></blockquote><p><strong>Concurrent queue:</strong> Unlike serial queue, concurrent queue dequeue tasks only when threads are available. It doesn’t require to finish the previous task. So, multiple tasks can be dequeued depending on thread availability.</p><p><strong>Synchronous:</strong> If we mark a function or chunk of code as synchronous it will block the current thread, execute first(no matter how long it might take), and then jump to the next piece of code.</p><p><strong>Asynchronous:</strong> If a chunk of code or a function is marked as asynchronous, it will not block the current thread. Rather, it’ll go to the task queue and execute. In the meantime, other pieces of code will execute in the current thread.</p><p>Sometimes, we get confused between serial and sync, concurrent and async. But serial and concurrent are the <strong><em>order of execution</em></strong>. On the other hand, sync and async are the <strong><em>manner of execution</em></strong>.</p><p>So that’s it for this article. Hopefully, it covered all the basics needed to understand concurrency. In the next article, I’ll discuss GCD(Grand Central Dispatch), which is an Apple-provided API for managing concurrency.</p><p><strong>References:</strong><br>1. <a href="https://en.wikipedia.org/wiki/Thread_(computing)">https://en.wikipedia.org/wiki/Thread_(computing)</a><br>2. <a href="https://stackoverflow.com/a/59803364/24035369">https://stackoverflow.com/a/59803364/24035369</a><br>3. <a href="https://youtu.be/X9H2M7xMi9E?si=obgX-uGc2QnwD6zH">https://youtu.be/X9H2M7xMi9E?si=obgX-uGc2QnwD6zH</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a8433910d141" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React hook: useCallback()]]></title>
            <link>https://kazi-mashry.medium.com/react-hook-usecallback-bcbd4e6b3aca?source=rss-fb8472c54deb------2</link>
            <guid isPermaLink="false">https://medium.com/p/bcbd4e6b3aca</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[react-hook]]></category>
            <dc:creator><![CDATA[Kazi Mashry]]></dc:creator>
            <pubDate>Wed, 16 Jun 2021 12:42:00 GMT</pubDate>
            <atom:updated>2022-10-05T10:53:13.220Z</atom:updated>
            <content:encoded><![CDATA[<p>Hooks are new features of React Js which are introduced in React 16.8 version. React brings hooks to enable the powers of class components, like state management, life-cycle methods, into the functional components. As far today there are three basic hooks useState, useEffect, and useContext. There are some additional hooks as well. In this article, I’ll explain the useCallback hook, which will help you make your application more performant. So let’s begin.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*YKfRvG0bHmB0VSrnQIf6rA.png" /></figure><p>Let’s say we have only two components, one is the parent and another is the child.</p><p>The parent component is like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b5ed494a9898e2e543014920b30026e4/href">https://medium.com/media/b5ed494a9898e2e543014920b30026e4/href</a></iframe><p>Child function is like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7f2423fc3040c81da3185e9ec2e7be94/href">https://medium.com/media/7f2423fc3040c81da3185e9ec2e7be94/href</a></iframe><p>Here in Child.tsx isEven() function indicates a costly function. That means it takes time to execute. So the overall Child component becomes a costly component. So you also added React.memo() while exporting the costly component so that it caches the component and doesn’t re-render. Now when you run the command npm start it’ll take some time to load as the child component is costly. And let’s say overall UI is like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_6O6gxv7gYBINFRiWfjfqA.png" /></figure><p>Now click on the add parent count button. What did you observe? it took some time to update the parent count and it printed isEven called into the console. Why did this happen? Hmm…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2lCECJfNDM_lc4Oq" /><figcaption>Photo by <a href="https://unsplash.com/@earbiscuits?utm_source=medium&amp;utm_medium=referral">Juan Rumimpunu</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>As it’s printing the text into the console that means it&#39;s re-rendering the child component also. But we already used React.memo() there. So why does this happen?</p><p>Ok. Here is the basic thing. We know a component re-renders if the state changes or if the props change. Here when we clicked on the add parent count button it re-renders the whole component. That means the reference of the printFunction also changed. As the printFunction is passed as a prop into the child component thus, the Child.tsx also re-rendered, which is a costly component. Thus, it took time to re-render and update the DOM. So what’s the hack to make it performant?</p><p>To make it performant we need a hack so that the reference of the printFunction doesn’t change until we developers say logically to change it. If the printFunction doesn’t change that means the props of the Child will also not be changed. So it’ll not re-render since it’s also cached.</p><p>That’s where the useCallback comes into the picture. We need to use it to cache the function reference. As a result, it’ll not change when the parent re-renders. As like, useEffect hook, useCallback hook also takes two parameters. First one is the function and the second one is the array of the dependencies. Function reference will be changed if any of the dependencies changes. Otherwise, it’ll remain the same. So, in our case above, it’ll not re-render our Child component.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2670cd5c65751e1743ae64135c69aec2/href">https://medium.com/media/2670cd5c65751e1743ae64135c69aec2/href</a></iframe><p>Now, if you click on that add parent count button, it’ll not take time to re-render the component and update the DOM.</p><p>I hope, you got the basic concept of useCallback hook and you can use it from your next awesome project. Happy coding.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bcbd4e6b3aca" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Things you should know about react]]></title>
            <link>https://kazi-mashry.medium.com/things-you-should-know-about-react-344f150931dd?source=rss-fb8472c54deb------2</link>
            <guid isPermaLink="false">https://medium.com/p/344f150931dd</guid>
            <category><![CDATA[reactjs]]></category>
            <dc:creator><![CDATA[Kazi Mashry]]></dc:creator>
            <pubDate>Wed, 04 Nov 2020 15:31:24 GMT</pubDate>
            <atom:updated>2020-11-04T15:32:25.671Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/750/0*a3f1u9XoegtKw8Dm.jpg" /></figure><p><strong>1. What is react?</strong></p><p>ReactJs is a JavaScript library use for building reusable UI components. So, there are two parts in the definition, a) react is a JavaScript library and b) used for building reusable UI components.</p><p>By definition, react is not a framework. That means, it’s not a complete solution for making the whole web application. Rather react focuses on only one thing and the thing is building reusable UI components.</p><p><strong>2. Why is react called react?</strong></p><p>When any state of a react component changes, the UI also changes. The change have to be displayed in the device. To do this, the DOM tree must be updated but we don’t do that manually. Rather, react reacts to the changes and automatically update the DOM where needed.</p><p><strong>3. React tree reconciliation</strong></p><p>Before making any DOM operation that will make the tree show up in the browser, react first generate a virtual representation of that tree. Then when any change takes place, that means when react has to update the DOM tree, it creates another virtual tree. Now react has two virtual trees.</p><p>To render the updated tree react doesn’t discard the whole tree which is already rendered. Rather, It will compare the two virtual trees, compute the differences between them, figure out which sub-tree to update. Then it will update only that subtree of the DOM tree, which is shown in the browser. This process is known as the react tree reconciliation algorithm.</p><p><strong>4. Name of the component:</strong></p><p>The name of the must start with a capital letter. Otherwise JSX compiler (like Babel) will consider it as a HTML tag. This is important because HTML element passed as string to React.createElement while react element must be passed as variabe.</p><p><strong>5. Component vs element:</strong></p><p>It is very easy for anyone new to be confused over these two terms. Basically, react component is a template or you can say a global declaration. This can be either a function or a class with render function.</p><p>On the other hand, element is the object which gets returned from the component. It describes the DOM node that a component represents.</p><p><strong>6. What is react hook?</strong></p><p>React hook is a special type of function that can be used from function components only. Hook functions starts with the word “use”. Some of hook functions are useState, useEffect, useCallback. Every time we define a variable that changes state and so we have to update the DOM, we use hook function.</p><p><strong>7. Data goes down:</strong></p><p>In react, data can be passed from parent component to the child component. You can not directly pass data from child component to parent component through props. Props drilling only works in top to down approach. To pass data from child to parent, you have to use storage or other technics.</p><p><strong>8. Default props:</strong></p><p>Some times we don’t pass a props or pass a null value in the child component but the child component insert the props value in the element. As a result, error occurs. To avoid the error we can simply use defaultProps. For instance,</p><pre>export default const Greeting = (props) =&gt; {<br>    return &lt;h1&gt;Good morning, {props.name}&lt;/h1&gt;<br>}</pre><pre>Greeting.defaultProps = {<br>    name: &quot;Sir&quot;<br>}</pre><p>Now, if the name is not provided while declaring the component, it will set “sir” as name by default.</p><p>So that’s basically it. Never stop learning. Happy coding.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=344f150931dd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JS error handling]]></title>
            <link>https://kazi-mashry.medium.com/js-error-handling-c45e32025bac?source=rss-fb8472c54deb------2</link>
            <guid isPermaLink="false">https://medium.com/p/c45e32025bac</guid>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Kazi Mashry]]></dc:creator>
            <pubDate>Tue, 03 Nov 2020 14:39:51 GMT</pubDate>
            <atom:updated>2020-11-03T14:39:51.451Z</atom:updated>
            <content:encoded><![CDATA[<p>Shut the errors out! <br>It is okay if you have errors in your script. It is not your mistake every time to have those errors. Rather, it might occur for unexpected user-input or any server errors. For those errors, your script can die(immediately stop). So as a good programmer, your responsibility is to handle those errors. In this article, we’ll see how to handle those errors. So, let’s jump into it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4Ma68hTpx_CiEP-_" /><figcaption>Photo by <a href="https://unsplash.com/@vimarovi?utm_source=medium&amp;utm_medium=referral">Victor Rodriguez</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>Try-catch block:</strong></p><p>A try-catch has two blocks: try and catch.</p><pre> try {<br>     // code...<br> } catch (error) {<br>     // error handling code...<br> }</pre><p>It works like this:</p><ol><li>First, the code in the try block is executed.</li><li>If there is no error, then the full code under the try block will execute and ignore the catch block.</li><li>If an error occurs, the execution of the try block stops immediately, and the catch block executes.</li></ol><p>Let’s illustrate those points with 2 examples:</p><p>Example-1:</p><pre>try {<br>    let a = 5, b = 2;<br>    console.log(a+b);<br> } catch (error) {<br>     console.log(error.name);<br> }</pre><p>Here, in the example-1 there is no error in the try block. So the code in try block will execute and the catch block will completely ignored.</p><p>Example-2:</p><pre>try {<br>    let a = 5, b = 3, c = 7, d = 8;<br>    console.log(a + b);<br>    undefinedVariable; // error<br>    console.log(c + d);<br>} catch (error) {<br>    console.log(error.name);<br>}</pre><p>Here, in the example-2 the first two lines of the code will execute. But, as there is an error occurred in the 3rd line of the try{} block, so the rest of the line of the try{} block will be ignored and catch{} block will be executed.</p><p>You should remember two things while using try-catch block.</p><ol><li>try-catch works for runtime errors. It won’t work if there is syntactical errors or the codes in the block are not runnable</li><li>It is works synchronously.</li></ol><p><strong>Error object:</strong></p><p>JavaScript generates an object when an error occurs. It contains three attributes-</p><ol><li>name: It’s a string containing the name of the error like, SyntaxError, ReferenceError, RangeError, EvalError etc.</li><li>message: It’s a text message about the error details.</li><li>stack: It’s the current call stack where the error occurred.</li></ol><p><strong>Throwing error:</strong></p><p>You can generate error object and throw it by yourself. You can also modify the existing runtime errors message attribute, and throw the error. For instance,</p><p>Example-1</p><pre>try {<br>    const user = { id: &quot;cs-1001&quot;, cgpa: 3.60 }<br>    if( !user.name ) throw new Error(&#39;No name found&#39;);<br>    console.log(user);<br>} catch (error) {<br>    console.log(error.message); // &#39;No name found&#39;<br>}</pre><p>Example-2</p><pre>try {<br>    const user = { id: &quot;c-1001&quot;, cgpa: 3.60 }<br>    if( user.name.startsWith(&#39;cs-&#39;) )<br>        throw new SyntaxError(&#39;Id is not valid&#39;)<br>    console.log(user);<br>} catch (error) {<br>    console.log(error.message); // &#39;Id is not valid&#39;<br>}</pre><p><strong>try-catch-finally:</strong></p><p>Now we have a new block called finally. finally{} is the block of code which will execute after the try…catch… block, no matter which one executed. The finally statement is used when we start doing something and finalize it regardless of the output.</p><pre>try {<br>    const user = { id: &quot;c-1001&quot;, cgpa: 3.60 }<br>    if( user.name.startsWith(&#39;cs-&#39;) )<br>        throw new SyntaxError(&#39;Id is not valid&#39;)<br>    console.log(user);<br>} catch (error) {<br>    console.log(error.message); // &#39;Id is not valid&#39;<br>} finally {<br>    console.log(&#39;It must execute&#39;);<br>}</pre><p>So, that’s basically it. Hope, you could gain the primary knowledge about handling errors through try…catch… block. Happy coding.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c45e32025bac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Use of JS context API]]></title>
            <link>https://kazi-mashry.medium.com/use-of-js-context-api-7fd8507dbdec?source=rss-fb8472c54deb------2</link>
            <guid isPermaLink="false">https://medium.com/p/7fd8507dbdec</guid>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[context-api]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Kazi Mashry]]></dc:creator>
            <pubDate>Sat, 19 Sep 2020 16:04:33 GMT</pubDate>
            <atom:updated>2020-11-12T10:54:25.479Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to use JS context API</h3><p>Okay, first thing first. If you’re searching for a formal description of context API, probably this article is not for you. Here I’ll discuss my concept of using context API. So, let’s get started.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*00hJzeQWV0rJBeLR" /><figcaption>Photo by <a href="https://unsplash.com/@filisantillan?utm_source=medium&amp;utm_medium=referral">Filiberto Santillán</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Let’s say, you’re just making a single-page website where there are multiple components, and you want to pass data from one component to another component. In that case, how could you pass values from one component to another? Indeed, using props, right?</p><p>But, what if you used routing in your application and pass multiple values from one component of one route to another component to another route. Let’s demonstrate the question more precisely with the image below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/353/0*JlsMA3E-wIc175yj.png" /></figure><p>Let’s say, you want to pass data from component-B to component-D. In that, you can simply by passing props. The same goes for component-E to component-F. But in that case, you have to declare the state to their parent component (component-C in this case). But what if we want to pass data from component-D to component-I? Will we declare a state to component-A and pass the whole state from component-A -&gt; component-B-&gt; component-D and component-A-&gt; component-C -&gt; component-F -&gt; component-I? Surely, it’ll be a painful task and even more painful when we have to pass those state(s) two or more components. So, what can be done here? Hmm…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ne39avgvQz30FjgN" /><figcaption>Photo by <a href="https://unsplash.com/@earbiscuits?utm_source=medium&amp;utm_medium=referral">Juan Rumimpunu</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Here, context API brings the solution. The solution is you can simply declare all your states in the root component and pass them through a context provider. Then, if a component needs a certain state or variable, it can simply use that context and use it in the component body.</p><p>For example, if we want to check a user is logged in from different components then we can use context like below in the root component.</p><pre>import React, { useState } from &#39;react&#39;;<br>import View from &#39;./components/View/View&#39;; </pre><pre><strong>export const userContext = React.createContext();</strong> </pre><pre>function App() {<br>  const [loggedinUser, setLoggedinUser] = useState({});</pre><pre>  return (<br>    <strong>&lt;userContext.Provider value={[loggedinUser, setLoggedinUser]}&gt;</strong><br>       &lt;View /&gt;<br>    &lt;/userContext.Provider&gt;<br>  );<br>}<br>export default App;</pre><p>In the code above, first, we create a context and export them. As a result, other components can get the context and grab the values passed by the context. Then we passed the state through the context provider.</p><p>Now, if we want to set the value of the loggedinUser or want to use the data of the loggedinUser then we have to grab the userContext and use the state or values that are passed by the userContext provider. So the code will be like below,</p><pre>import React, { useContext } from &#39;react&#39;;<br>import { userContext } from &#39;../../App&#39;;</pre><pre>const Component = () =&gt; {<br>    <strong>const [loggedinUser, setLoggedinUser] = useContext(userContext);</strong><br>    // code<br>    return (<br>        &lt;&gt; <br>            // some HTML<br>       &lt;/&gt;<br>    );<br>}<br>export default Component;</pre><p>So now you can easily get the values or state from different components without even passing them by yourself as props. But what about if we want to pass multiple states?</p><p>Well, in that case, we can make an object and pass them through the context provider. For example,</p><pre>import React, { useState } from &#39;react&#39;;<br>import View from &#39;./components/View/View&#39;;</pre><pre><strong>export const userContext = React.createContext();</strong></pre><pre>function App() {<br>  const [loggedinUser, setLoggedinUser] = useState({});<br>  const [bookingDetails, setBookingDetails] = useState({});<br>  const [whiteBg, setWhiteBg] = useState(false);</pre><pre>return (<br>    <strong>&lt;userContext.Provider <br>      value={<br>                {<br>                     user: [loggedinUser, setLoggedinUser],<br>                     booking: [bookingDetails, setBookingDetails],<br>                     background: [whiteBg, setWhiteBg]<br>                }<br>      }&gt;</strong><br>       &lt;View /&gt;<br>    &lt;/userContext.Provider&gt;<br>  );<br>}<br>export default App;</pre><p>In this case, the method of grabbing the expected state is slightly different. First, you have to destructor the object, then you can get the required state. For example, in one component we need to use user and background state. So the code will be like,</p><pre>import React, { useContext } from &#39;react&#39;;<br>import { userContext } from &#39;../../App&#39;;</pre><pre>const Component = () =&gt; {<br>    <strong>const { user, background } = useContext(userContext);<br>    [loggedinUser, setLoggedinUser] = user;<br>    [whiteBg, setWhiteBg] = background;</strong><br>    // code<br>    return (<br>        &lt;&gt; <br>            // some HTML<br>       &lt;/&gt;<br>    );<br>}<br>export default Component;</pre><p>So, by using context API we can avoid props drilling and use state or any value where we need that.</p><p>That’s all for today. Thanks for reading the article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7fd8507dbdec" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Some confusing JS stuff]]></title>
            <link>https://kazi-mashry.medium.com/some-confusing-js-stuff-861cb16199fc?source=rss-fb8472c54deb------2</link>
            <guid isPermaLink="false">https://medium.com/p/861cb16199fc</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Kazi Mashry]]></dc:creator>
            <pubDate>Fri, 07 Aug 2020 19:33:23 GMT</pubDate>
            <atom:updated>2020-08-07T19:33:23.895Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><strong>Disclaimer:</strong> If you’re not a beginner then probably this article is not for you😊</blockquote><h3><strong>slice() vs splice():</strong></h3><p>As a beginner, we have confusion about JavaScript slice() and splice(). Both of them are almost the same by syntax and used as array method. So in this article, I’ll write about their usage and differences. Stay tuned. 😉</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*663WFkcUAFjz2HRb" /><figcaption>Photo by <a href="https://unsplash.com/@hugoaitken?utm_source=medium&amp;utm_medium=referral">Hugo Aitken</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Let&#39;s understand these two methods with an example. Let&#39;s say, we have an array named numbers, declared like below:</p><pre>let numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];</pre><p>So here, if we want to use these two methods we simply have to do this:</p><pre>let part = numbers.slice(starting_index, end_index);</pre><pre>let removed = numbers.splice(starting_index, number_of_element_removed, values_that_eill_replace(optional));</pre><p>Let’s say, we want to fetch the values of the range which starts from index 2 and ends with index 5. That means we want an array with [2, 3, 4] that will be fetched from the numbers array. In this case, we’ll use the slice() method. So the code will be like,</p><pre>let part = numbers.slice(2, 5);</pre><p>Basically, the slice() method has no effect on the main array, (numbers array in our example).</p><p>Now, let’s say, we want to remove or cut off a part from the numbers array. In this case, we’ll use the splice() method. In this method, firstly, we have to pass the index value as a parameter that’ll indicate from where we want to remove or cut off the array. Secondly, we have to pass the number of elements we want to cut off from the original array. Then we can pass several values as parameters that will be positioned from the starting index of the removed part.</p><p>For example, let’s say, we want to remove a part from index 3 and remove 5 elements. Then,</p><pre>let removed = numbers.splice(3, 5);</pre><p>So, now, the numbers array has become,</p><pre>numbers = [0, 1, 2, 8, 9, 10, 11, 12, 13, 14, 15];</pre><p>As the splice() method returns an array so the removed array has become</p><pre>removed = [3, 4, 5, 6, 7];</pre><p>Now, if we pass more values that’ll be positioned from the first removed position then the syntax will be like,</p><pre>let removed = numbers.splice(3, 5, 10, 44, 45, 55, 32, 44, 54, 66);</pre><p>So, now, the numbers array has become,</p><pre>numbers = [0, 1, 2, 10, 44, 45, 55, 32, 44, 54, 66, 8, 9, 10, 11, 12, 13, 14, 15].;</pre><p>And the removed array will be the same as before.</p><h3><strong>map() vs filter():</strong></h3><p>There is another confusing topic to me was the map() and the filter(). Let’s dig into it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6_GSdfP9qPguTI8u" /><figcaption>Photo by <a href="https://unsplash.com/@calebscamera?utm_source=medium&amp;utm_medium=referral">Caleb Dow</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>map():</strong></p><p>Let’s say, someone asked you to double every value of an array and store them into another array. As a beginner, we’ll use for loop(or while loop sometimes). But there is another smart way to do this thing. We can use a map() for this. It’ll be like,</p><pre>const numbers = [1, 2, 3, 4, 5, 6, 7, 8];</pre><pre>const result_1 = [], result_2 = [];</pre><pre>// Beginner’s way:</pre><pre>for(let i = 0; i &lt; numbers.length; i++) {</pre><pre>result_1.push(numbers[i] * 2);</pre><pre>}</pre><pre>// Smart way(😎)</pre><pre>result_2 = numbers.map(element =&gt; element*2);</pre><p>Both of them will generate the same output.</p><p><strong>filter():</strong></p><p>Now, if we want to fetch those values that are divisible by 2 or 3 then we can do it with a loop.</p><pre>let result = [];</pre><pre>for(let i = 0; i &lt; numbers.length; i++) {<br>    if(numbers[i]%2 == 0 || numbers[i]%3==0){<br>        result.push(numbers[i]);<br>    }<br>}</pre><p>Or, we can simply use filter() like this,</p><pre>let result = numbers.filter(element =&gt; element%2==0 || element%3==0);</pre><p>Both results will be the same.</p><p>Basically, the filter() method filters out those values which meet the condition and return an array. On the other hand, the map() method operates a certain operation inside it and captures the returned values and finally returns an array.</p><p><strong>Put them together:</strong></p><p>Now, let’s say we want to double those values which are odd in the numbers array and fetch them into another array. So we can do that using map() and filter() methods together like this,</p><pre>const result = numbers.filter(x =&gt; x%2==0).map(x =&gt; x*2);</pre><p>So the result array will be,</p><pre>result = [2, 6, 10, 14];</pre><h3><strong>Hoisting:</strong></h3><p>Hoisting means raise. Like, if you want to build a multi-floor building then you have to hoist some metallic or heavy things with the help of a crane to the top of the building.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GZlFYwssVQC7eP-W" /><figcaption>Photo by <a href="https://unsplash.com/@arc_sotto?utm_source=medium&amp;utm_medium=referral">Arc Sotto</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In the same way, JS hoist or raise a variable declaration and a function declaration to the top of the function scope. Those variables and functions can be used from any part of the function without raising any reference error.</p><pre>console.log(value); //output: undefined<br>var value = 10;</pre><p>The code above is equivalent to the code below:</p><pre>var value;<br>console.log(value);<br>value = 10;</pre><p>That means, JS hoist the declaration part of a variable to the top of the scope. As a result, it doesn’t show any error rather it shows undefined. If here we used let instead of var then there would be an error.</p><p><strong>For functions:</strong></p><p>Any function declaration will be hoisted at the top.</p><pre>function myFunction() {</pre><pre>    var innerFunction = function() {<br>        anotherFunction();<br>    }</pre><pre>    innerFunction();</pre><pre>    function anotherFunction() {<br>        console.log(&quot;another function&quot;);<br>    }</pre><pre>}</pre><pre>myFunction(); // output: another function</pre><p>The above code is equivalent to the code below:</p><pre>function myFunction() {</pre><pre>    function anotherFunction() {<br>        console.log(&quot;another function&quot;);<br>    }</pre><pre>    var innerFunction = function() {<br>        anotherFunction();<br>    }</pre><pre>    innerFunction();</pre><pre>}</pre><pre>myFunction(); // output: another function</pre><p>But for the below code there will generate an error:</p><pre>function myFunction() {</pre><pre>    function callInnerFunction() {<br>        innerFunction();<br>    }</pre><pre>    callInnerFunction();</pre><pre>    var innerFunction = function() {<br>        console.log(&quot;inner function&quot;);<br>    }<br>}</pre><pre>myFunction();</pre><p>The error will be like, TypeError: innerFunction is not a function</p><p>That means the function callInnerFunction() recognized innerFunction but it isn’t any function but as a declared variable or something. The code above is equivalent to the code below:</p><pre>function myFunction() {<br>    var innerFunction;</pre><pre>    function callInnerFunction() {<br>        innerFunction();<br>    }</pre><pre>    callInnerFunction();</pre><pre>    innerFunction = function() {<br>        console.log(&quot;inner function&quot;);</pre><pre>    }</pre><pre>}</pre><pre>myFunction();</pre><p>If we run this code it’ll also generate an error as above.</p><p>So, from above, we can get that, only the declaration part is hoisted. The value assigned remains at its location. A function declaration is hoisted. If you have a function expression only the variable part of the function expression will be hoisted. The definition part will remain at its place.</p><h3>Closure:</h3><blockquote>According to the <a href="https://developer.mozilla.org/">MDN web docs</a>, a closure is a combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment).</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1q-ubcoiHvhEiHqp" /><figcaption>Photo by <a href="https://unsplash.com/@timmossholder?utm_source=medium&amp;utm_medium=referral">Tim Mossholder</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Very tough definition, right? Okay, let’s look at the code below:</p><pre>function stopWatch() {<br>    let count = 0;<br>    function increase() {<br>        ++count;<br>        return count;<br>    }<br>    return increase;<br>}</pre><pre>let clock1 = stopWatch();<br>let clock2 = stopWatch();</pre><pre>clock1() // 1<br>clock1() // 2<br>clock1() // 3<br>clock2() // 1<br>clock1() // 4<br>clock2() // 2</pre><p>Here, an outer function stopWatch contains a local variable named count and returning a function.</p><p>In this example, function increase() preserved the value of count when the stopWatch() function is called. Now, when the outer function stopWatch is called and it returns the function increase(), so the value of clock1 and clock2 will be increase() function(returning function). So for both the clock the value of the count is 0. when clock1() is called for several times, the value of the count of clock1 will increase by 1. So, when we call it three times the value of the count has become 3. Again, when we called clock2(), the value of count for clock2 has increased by 1. You would not be able to access (get or set) the value of count from outside. Hence the privacy of the value of “i” is maintained secretly. This is called encapsulation in object-oriented programming.</p><h3>Conclusion:</h3><p>Still confused, right? 🤯 Doesn’t matter. It’ll take some time to grasp all the concepts. You know, there is a popular saying that, practice makes a man perfect. So, as a beginner, we need to practice a lot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dExdbn29MGGoJ34h" /><figcaption>Photo by <a href="https://unsplash.com/@designwilde?utm_source=medium&amp;utm_medium=referral">Melanie Dretvic</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3><strong>References:</strong></h3><ol><li><a href="http://thatjsdude.com/jsConcepts/concepts/scope.html">http://thatjsdude.com/jsConcepts/concepts/scope.html</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures</a></li><li><a href="https://medium.com/@prashantramnyc/javascript-closures-simplified-d0d23fa06ba4">https://medium.com/@prashantramnyc/javascript-closures-simplified-d0d23fa06ba4</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=861cb16199fc" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>