<?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>Forem: Ishraq Tanvir</title>
    <description>The latest articles on Forem by Ishraq Tanvir (@devishraq).</description>
    <link>https://forem.com/devishraq</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%2F1745073%2F5a319a2f-11cd-4a31-83bf-2bb31df358d2.jpg</url>
      <title>Forem: Ishraq Tanvir</title>
      <link>https://forem.com/devishraq</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://forem.com/feed/devishraq"/>
    <language>en</language>
    <item>
      <title>⚡ Understanding JavaScript Web Workers: Harnessing the Power of Multithreading</title>
      <dc:creator>Ishraq Tanvir</dc:creator>
      <pubDate>Wed, 31 Jul 2024 11:52:23 +0000</pubDate>
      <link>https://forem.com/devishraq/mastering-javascript-web-workers-an-in-depth-guide-496e</link>
      <guid>https://forem.com/devishraq/mastering-javascript-web-workers-an-in-depth-guide-496e</guid>
      <description>&lt;p&gt;Hello fellow developers! 🚀 If you’re on a quest to make your JavaScript code faster and more efficient, Web Workers might be your new best friend! Today, we're diving into a cool concept that’s like having a superhero sidekick for your web apps — &lt;strong&gt;Web Workers&lt;/strong&gt;. Imagine having a helper who takes care of all the heavy lifting while you focus on the main stuff. That’s exactly what Web Workers can do!&lt;/p&gt;

&lt;p&gt;It's like having a homemaker who takes care of the cleaning, cooking, and washing while you focus on what matters most...your code!&lt;/p&gt;

&lt;h3&gt;
  
  
  What Exactly Are Web Workers?
&lt;/h3&gt;

&lt;p&gt;Think of Web Workers as your secret agents who run in the background, handling tasks like complex calculations or data processing without slowing down your main thread. This means your web app stays smooth and snappy, even when you’re dealing with heavy tasks.&lt;/p&gt;

&lt;p&gt;Here’s a fun way to look at it:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F2o9f6uvb4eq727a1upa7.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F2o9f6uvb4eq727a1upa7.png" alt="JavaScript Web Workers" width="800" height="149"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Why Bother with Web Workers?
&lt;/h3&gt;

&lt;p&gt;JavaScript is single-threaded, which means it can only do one thing at a time. When you’re running a long task on the main thread, your web app can freeze or take a while to load, making users wait and possibly causing frustration. Web Workers come to the rescue by handling these tasks on a separate thread, so your app remains responsive. And users get happy with a faster application!&lt;/p&gt;

&lt;h3&gt;
  
  
  Let’s Be a Bit Practical!
&lt;/h3&gt;

&lt;p&gt;We’ll break it down into a few simple steps so you can understand how it actually works!&lt;/p&gt;

&lt;h4&gt;
  
  
  Step 1: Creating the Worker Script
&lt;/h4&gt;

&lt;p&gt;First up, we need a separate JavaScript file for our worker. Let’s call it &lt;code&gt;worker.js&lt;/code&gt; or any name you choose!&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;worker.js&lt;/strong&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;onmessage&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;function &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;e&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;number&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;e&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;data&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;result&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;fibonacci&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;number&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="nf"&gt;postMessage&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;result&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="p"&gt;};&lt;/span&gt;

&lt;span class="kd"&gt;function&lt;/span&gt; &lt;span class="nf"&gt;fibonacci&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;n&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;if &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;n&lt;/span&gt; &lt;span class="o"&gt;&amp;lt;=&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nx"&gt;n&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="nf"&gt;fibonacci&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;n&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="mi"&gt;1&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;+&lt;/span&gt; &lt;span class="nf"&gt;fibonacci&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;n&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this file, we set up our worker to listen for messages with &lt;code&gt;self.onmessage&lt;/code&gt;, perform some heavy lifting (like calculating a Fibonacci number), and then send the result back with &lt;code&gt;postMessage&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;You might be wondering, what is &lt;code&gt;self&lt;/code&gt;? Or what are &lt;code&gt;postMessage&lt;/code&gt; and &lt;code&gt;onmessage&lt;/code&gt;? &lt;/p&gt;

&lt;p&gt;Web Workers operate in a different global context, not the familiar &lt;code&gt;window&lt;/code&gt;. We call this special global context &lt;code&gt;self&lt;/code&gt;!&lt;/p&gt;

&lt;p&gt;Web Workers communicate with the main thread using events. By using events, they can send and receive messages or data. In the code, &lt;code&gt;onmessage&lt;/code&gt; typically gets messages or data from the main thread, and &lt;code&gt;postMessage&lt;/code&gt; sends processed data from the Web Worker back to the main thread.&lt;/p&gt;

&lt;h4&gt;
  
  
  Step 2: Creating and Talking to the Worker
&lt;/h4&gt;

&lt;p&gt;Now, let’s see how to create a worker and send messages/data to it from our main script.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;main.js&lt;/strong&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="c1"&gt;// Create a new Web Worker using Worker()&lt;/span&gt;
&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;worker&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;Worker&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;worker.js&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="c1"&gt;// Send data to the worker.&lt;/span&gt;
&lt;span class="nx"&gt;worker&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;postMessage&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;40&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt; &lt;span class="c1"&gt;// Calculate the 40th Fibonacci number&lt;/span&gt;

&lt;span class="c1"&gt;// Receive data from the worker&lt;/span&gt;
&lt;span class="nx"&gt;worker&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;onmessage&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;function &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;e&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;The result is:&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;e&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;data&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="p"&gt;};&lt;/span&gt;

&lt;span class="c1"&gt;// Handle worker errors&lt;/span&gt;
&lt;span class="nx"&gt;worker&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;onerror&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;function &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;error&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;error&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;Worker error:&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;error&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="p"&gt;};&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here, we create a new worker with &lt;code&gt;new Worker('worker.js')&lt;/code&gt;, send a message to it with &lt;code&gt;worker.postMessage&lt;/code&gt;, and get results with &lt;code&gt;worker.onmessage&lt;/code&gt;. We also handle any potential errors with &lt;code&gt;worker.onerror&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;postMessage&lt;/code&gt;: sends data to the worker&lt;/p&gt;

&lt;p&gt;&lt;code&gt;onmessage&lt;/code&gt;: receives processed data from the worker&lt;/p&gt;

&lt;p&gt;&lt;code&gt;onerror&lt;/code&gt;: handles errors&lt;/p&gt;

&lt;h3&gt;
  
  
  Cool Ways to Use Web Workers
&lt;/h3&gt;

&lt;p&gt;Web Workers can be super useful in a variety of scenarios. Let’s check out a couple of practical examples.&lt;/p&gt;

&lt;h4&gt;
  
  
  Example 1: Sorting a Massive Array
&lt;/h4&gt;

&lt;p&gt;Sorting a huge array can take a lot of time. Let’s let a Web Worker handle that.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;worker.js&lt;/strong&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;onmessage&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;function &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;e&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;array&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;e&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;data&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="nx"&gt;array&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;sort&lt;/span&gt;&lt;span class="p"&gt;((&lt;/span&gt;&lt;span class="nx"&gt;a&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;b&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nx"&gt;a&lt;/span&gt; &lt;span class="o"&gt;-&lt;/span&gt; &lt;span class="nx"&gt;b&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="nf"&gt;postMessage&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;array&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="p"&gt;};&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;main.js&lt;/strong&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;worker&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;Worker&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;worker.js&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;largeArray&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nb"&gt;Array&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;from&lt;/span&gt;&lt;span class="p"&gt;({&lt;/span&gt; &lt;span class="na"&gt;length&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;1000000&lt;/span&gt; &lt;span class="p"&gt;},&lt;/span&gt; &lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="o"&gt;=&amp;gt;&lt;/span&gt; &lt;span class="nb"&gt;Math&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;floor&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nb"&gt;Math&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;random&lt;/span&gt;&lt;span class="p"&gt;()&lt;/span&gt; &lt;span class="o"&gt;*&lt;/span&gt; &lt;span class="mi"&gt;1000000&lt;/span&gt;&lt;span class="p"&gt;));&lt;/span&gt; &lt;span class="c1"&gt;// The array has been generated dynamically as it's a demo scenario.&lt;/span&gt;

&lt;span class="nx"&gt;worker&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;postMessage&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;largeArray&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="nx"&gt;worker&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;onmessage&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;function &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;e&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;Sorted array:&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;e&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;data&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
&lt;span class="p"&gt;};&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In this example, we create a massive array of random numbers, send it to the worker for sorting, and then get the sorted array back.&lt;/p&gt;

&lt;h4&gt;
  
  
  Example 2: Fetching Data from an API
&lt;/h4&gt;

&lt;p&gt;Web Workers can also handle API requests without blocking the main thread.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;worker.js&lt;/strong&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="nb"&gt;self&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;onmessage&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;async&lt;/span&gt; &lt;span class="nf"&gt;function &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;e&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;url&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nx"&gt;e&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;data&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="k"&gt;try&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;response&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nf"&gt;fetch&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;url&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
        &lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;data&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;await&lt;/span&gt; &lt;span class="nx"&gt;response&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;json&lt;/span&gt;&lt;span class="p"&gt;();&lt;/span&gt;
        &lt;span class="nf"&gt;postMessage&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;data&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;catch &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;error&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="nf"&gt;postMessage&lt;/span&gt;&lt;span class="p"&gt;({&lt;/span&gt; &lt;span class="na"&gt;error&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;Failed to fetch data&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt; &lt;span class="p"&gt;});&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;};&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;main.js&lt;/strong&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight javascript"&gt;&lt;code&gt;&lt;span class="kd"&gt;const&lt;/span&gt; &lt;span class="nx"&gt;worker&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;Worker&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;worker.js&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="nx"&gt;worker&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;postMessage&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;https://api.example.com/data&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;

&lt;span class="nx"&gt;worker&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;onmessage&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nf"&gt;function &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;e&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="k"&gt;if &lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;e&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;data&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;error&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;error&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nx"&gt;e&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;data&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;error&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;else&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="nx"&gt;console&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;log&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="s1"&gt;Fetched data:&lt;/span&gt;&lt;span class="dl"&gt;'&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nx"&gt;e&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nx"&gt;data&lt;/span&gt;&lt;span class="p"&gt;);&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;};&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here, we send a URL to the worker, which fetches the data and sends it back. If something goes wrong, the worker sends an error message.&lt;/p&gt;

&lt;h3&gt;
  
  
  Best Practices for Web Workers
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Keep Them Lightweight&lt;/strong&gt;: Web Workers don’t have direct access to the DOM, so keep their tasks focused.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Efficient Messaging&lt;/strong&gt;: Pass only essential data between the main thread and workers to avoid overhead.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Handle Errors&lt;/strong&gt;: Always include error handling to catch any issues.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Visualizing Web Workers
&lt;/h3&gt;

&lt;p&gt;Imagine Web Workers as a team of specialists in a factory. The main thread is the manager, and each worker handles different tasks.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F8smcu1ieb302k4t7oi4n.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/cdn-cgi/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F8smcu1ieb302k4t7oi4n.png" alt="JavaScript Web Workers" width="800" height="240"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Each worker focuses on a specific task, keeping the main manager (thread) free to oversee the big picture.&lt;/p&gt;

&lt;h3&gt;
  
  
  Resources
&lt;/h3&gt;

&lt;p&gt;For more detailed information about Web Workers, check out these resources:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers" rel="noopener noreferrer"&gt;Web Workers by MDN&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://web.dev/learn/performance/web-worker-overview" rel="noopener noreferrer"&gt;Web Workers by web.dev&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.w3schools.com/html/html5_webworkers.asp" rel="noopener noreferrer"&gt;Web Workers by W3Schools&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Wrapping Up
&lt;/h3&gt;

&lt;p&gt;Web Workers are like having a superpower in JavaScript. They let you offload heavy tasks to background threads, keeping your web apps fast and responsive. Next time your app seems to be lagging, remember your superhero sidekick—Web Workers are here to save the day!&lt;/p&gt;

&lt;p&gt;Happy coding! 🌟&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>javascript</category>
      <category>tutorial</category>
      <category>beginners</category>
    </item>
    <item>
      <title>🧠 Understanding JavaScript Proxies: Harnessing the Power of Metaprogramming</title>
      <dc:creator>Ishraq Tanvir</dc:creator>
      <pubDate>Sat, 27 Jul 2024 18:29:40 +0000</pubDate>
      <link>https://forem.com/devishraq/understanding-javascript-proxies-harnessing-the-power-of-metaprogramming-1l4d</link>
      <guid>https://forem.com/devishraq/understanding-javascript-proxies-harnessing-the-power-of-metaprogramming-1l4d</guid>
      <description>&lt;p&gt;Hello fellow developers! Have you ever needed more control over how objects behave in JavaScript? Today, we will delve into the powerful yet often misunderstood feature of JavaScript: Proxies. &lt;strong&gt;&lt;em&gt;Proxies are not hard but the syntax is a bit strange at first sight!&lt;/em&gt;&lt;/strong&gt; Let’s explore what they are, how they work, and some practical use cases.&lt;/p&gt;

&lt;h3&gt;
  
  
  What is a Proxy?
&lt;/h3&gt;

&lt;p&gt;A Proxy in JavaScript is an object that wraps another object (called the target) and intercepts fundamental operations performed on it, such as property access, assignment, and function invocation. By defining custom behavior for these operations, Proxies allows developers to create highly dynamic and flexible applications.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;‘In Small terms Proxy is a Wrapper over an object for advanced capability over objects’&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h3&gt;
  
  
  Syntax
&lt;/h3&gt;

&lt;p&gt;Creating a Proxy is straightforward. Here’s the basic syntax:&lt;/p&gt;

&lt;p&gt;const proxy = new Proxy(target, handler);&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;target&lt;/code&gt;: The object that the proxy will wrap.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;handler&lt;/code&gt;: An object containing traps (functions) that define the custom behavior for various operations.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Traps
&lt;/h3&gt;

&lt;p&gt;Traps are the methods provided in the handler object to intercept operations. Some common traps include:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;code&gt;get&lt;/code&gt;: Handles property access.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;set&lt;/code&gt;: Handlesproperty assignment.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;has&lt;/code&gt;: Handles the &lt;code&gt;in&lt;/code&gt; operator.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;deleteProperty&lt;/code&gt;: Handles property deletion.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;apply&lt;/code&gt;: Handles function calls.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;construct&lt;/code&gt;: Handles the &lt;code&gt;new&lt;/code&gt; operator.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Creating a Simple Proxy
&lt;/h3&gt;

&lt;p&gt;Let’s create a simple proxy to log property access and assignments.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const target = {
       name: 'Ishraq',
       age: 15      
};

const handler = {
       get: function(target, property, receiver) {
       console.log(\`Getting property ${property}\`);
          return target\[property];
       },
       set: function(target, property, value, receiver) {
       console.log(\`Setting property ${property} to ${value}\`);
       target\[property] = value;
       return true;
   }
};

const proxy = new Proxy(target, handler);
console.log(proxy.name);  // Logs "Getting property name"
proxy.age = 19;           // Logs "Setting property age to 19"
console.log(proxy.age);   // Logs "Getting property age"

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

&lt;/div&gt;



&lt;h3&gt;
  
  
  Validation
&lt;/h3&gt;

&lt;p&gt;Proxies can be used to enforce validation rules on objects. This is especially useful when dealing with user input or API responses. It opens a new layer of validation checking!&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const user = {
      name: '',
      age: 0
};

const handler = {
       set: function(target, property, value, receiver) {
         if (property === 'age' &amp;amp;&amp;amp; (typeof value !== 'number' || value \&amp;lt; 0)) {
           throw new Error('Age must be a non-negative number');
         }
         target\[property] = value;
         return true;
       }
};

const proxy = new Proxy(user, handler);
proxy.age = 25;  // Works fine
proxy.age = -5;  // Throws an error: Age must be a non-negative number

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

&lt;/div&gt;



&lt;h3&gt;
  
  
  Data Binding
&lt;/h3&gt;

&lt;p&gt;Proxies can be used for data binding in frameworks, allowing automatic updates to the UI when the underlying data changes.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
const data = {
       text: 'Hello, world!'
};

const handler = {
       set: function(target, property, value, receiver) {
         target\[property] = value;
         document.getElementById('output').textContent = value;
         return true;
       }
};

const proxy = new Proxy(data, handler);
document.getElementById('input').addEventListener('input', function(event) {
       proxy.text = event.target.value;
});
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;blockquote&gt;
&lt;p&gt;‘Currently, I am working on a reactive javascript library focused on speed &amp;amp; efficiency. There I’ve used proxies at great extinct for data binding…I really don’t appreciate the phrase &lt;strong&gt;data binding&lt;/strong&gt; it’s good to tell it &lt;strong&gt;reactive data binding.&lt;/strong&gt;’&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h3&gt;
  
  
  Tracing
&lt;/h3&gt;

&lt;p&gt;Proxies can help trace property access and modifications, useful for debugging and profiling. It has a great usage in application testing.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const profile = {
       name: 'John Doe',
       email: 'john@example.com'
};

const handler = {
       get: function(target, property, receiver) {
         console.log(\`Property ${property} accessed\`);
         return target\[property];
       },
       set: function(target, property, value, receiver) {
         console.log(\`Property ${property} set to ${value}\`);
         target\[property] = value;
         return true;
       }
};

const proxy = new Proxy(profile, handler);
proxy.name;       // Logs: Property name accessed
proxy.email = 'john.doe@example.com';  // Logs: Property email set to john.doe@example.com
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;blockquote&gt;
&lt;p&gt;‘In my reactive framework, I’ve implemented some robust test cases and while testing props of dom elements, I’ve used this for tracking any updates in props, which helped me to reflect any changes in props to the dom elements’&lt;/p&gt;
&lt;/blockquote&gt;

&lt;h3&gt;
  
  
  Immutable Objects
&lt;/h3&gt;

&lt;p&gt;Proxies are also used to create immutable objects, where properties cannot be changed once they are set. It’s like object properties but constant type, can’t be changed in any meaning.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const target = {
       name: 'Immutable Object'
};
const handler = {
       set: function(target, property, value, receiver) {
         console.log(\`Cannot set property ${property} to ${value}. Object is immutable.\`);
         return false; // indicate failure to set property
       }
};

const proxy = new Proxy(target, handler);
proxy.name = 'New Name'; // Logs: Cannot set property name to New Name. Object is immutable.
console.log(proxy.name); // Logs: Immutable Object
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Meta Programming
&lt;/h3&gt;

&lt;p&gt;Meta Programming means to program at the meta-level of JavaScript. JavaScript proxies unlock this meta layer/level of programming to help programmers define custom behaviors. &lt;strong&gt;&lt;em&gt;I will publish a very much detailed Post later on about meta programming. But, if you wanna learn about this meta layer of JavaScript check the resources section!&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  Resources
&lt;/h3&gt;

&lt;p&gt;To further deepen your understanding of JavaScript Proxies and their various applications, here are some valuable resources including meta programming!:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy" rel="noopener noreferrer"&gt;&lt;strong&gt;&lt;em&gt;Proxy by MDN&lt;/em&gt;&lt;/strong&gt;&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Meta_programming" rel="noopener noreferrer"&gt;&lt;strong&gt;&lt;em&gt;Meta Programming By MDN&lt;/em&gt;&lt;/strong&gt;&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://www.geeksforgeeks.org/javascript-proxy-handler/" rel="noopener noreferrer"&gt;&lt;strong&gt;&lt;em&gt;Proxy by greeksforgreeks&lt;/em&gt;&lt;/strong&gt;&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  Conclusion
&lt;/h3&gt;

&lt;p&gt;JavaScript Proxies are a powerful feature that allows developers to intercept and redefine fundamental operations on objects. They can be used for a wide range of applications, from validation and data binding to tracing and debugging. My favorite one is data binding. But, other real-world use cases have made it one of the most powerful features ever lived in the JavaScript Ecosystem. By understanding and utilizing Proxies, you can add a new level of dynamism and flexibility to your JavaScript code.&lt;/p&gt;

&lt;p&gt;Experiment with Proxies in your projects and discover how they can help to establish greater control over your code. &lt;strong&gt;Happy coding!&lt;/strong&gt;&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>javascript</category>
      <category>tutorial</category>
      <category>beginners</category>
    </item>
  </channel>
</rss>
