<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[JavaScript]]></title><description><![CDATA[JavaScript]]></description><link>https://javascript.co.in</link><generator>RSS for Node</generator><lastBuildDate>Mon, 20 Apr 2026 02:28:18 GMT</lastBuildDate><atom:link href="https://javascript.co.in/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[workers]]></title><description><![CDATA[index.html :
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Workers</title>
    <script src="main.js"></script>
</head>
<body>
    1 USD = <span...]]></description><link>https://javascript.co.in/workers</link><guid isPermaLink="true">https://javascript.co.in/workers</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[workers]]></category><dc:creator><![CDATA[Anjanesh Lekshminarayanan]]></dc:creator><pubDate>Fri, 14 Feb 2025 07:07:48 GMT</pubDate><content:encoded><![CDATA[<p>index.html :</p>
<pre><code class="lang-xml"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span> <span class="hljs-attr">lang</span>=<span class="hljs-string">"en"</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"UTF-8"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"viewport"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"width=device-width, initial-scale=1.0"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>Workers<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"main.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    1 USD = <span class="hljs-tag">&lt;<span class="hljs-name">span</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"currencyRate"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span> INR
<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p>main.js :</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> currencyWorker = <span class="hljs-keyword">new</span> Worker(<span class="hljs-string">"currency-rate-worker.js"</span>);

currencyWorker.postMessage(<span class="hljs-string">'INR'</span>);

currencyWorker.onmessage = <span class="hljs-function">(<span class="hljs-params">event</span>) =&gt;</span>
{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"USD to INR rate:"</span>, event.data);
    <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'currencyRate'</span>).innerText = event.data;
};
</code></pre>
<p>currency-rate-worker.js</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> get_usd2inr = <span class="hljs-keyword">async</span> () =&gt;
{
    <span class="hljs-keyword">const</span> url = <span class="hljs-string">"https://open.er-api.com/v6/latest/USD"</span>;
    <span class="hljs-keyword">try</span>
    {
        <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> fetch(url);
        <span class="hljs-keyword">const</span> data = <span class="hljs-keyword">await</span> response.json();
        <span class="hljs-keyword">const</span> usd2inr = <span class="hljs-built_in">Number</span>(data.rates.INR.toFixed(<span class="hljs-number">2</span>));
        <span class="hljs-keyword">return</span> usd2inr;
    }
    <span class="hljs-keyword">catch</span> (error)
    {
        <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Error fetching exchange rate:'</span>, error);
        <span class="hljs-keyword">throw</span> error;
    }
}

onmessage = <span class="hljs-keyword">async</span> (e) =&gt;
{
    <span class="hljs-keyword">if</span> (e.data === <span class="hljs-string">'INR'</span>)
    {
        postMessage(<span class="hljs-keyword">await</span> get_usd2inr());
    }
};
</code></pre>
]]></content:encoded></item><item><title><![CDATA[Self-Executing Functions]]></title><description><![CDATA[Let's say you wanted to call a function using await (let's call this function get_usd2inr) by calling it as in like - await get_usd2inr();, you may get this error:

Uncaught SyntaxError: await is only valid in async functions and the top level bodies...]]></description><link>https://javascript.co.in/self-executing-functions</link><guid isPermaLink="true">https://javascript.co.in/self-executing-functions</guid><category><![CDATA[self-executing-functions]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[currency]]></category><category><![CDATA[exchange rate API key]]></category><dc:creator><![CDATA[Anjanesh Lekshminarayanan]]></dc:creator><pubDate>Fri, 14 Feb 2025 04:43:47 GMT</pubDate><content:encoded><![CDATA[<p>Let's say you wanted to call a function using <code>await</code> (let's call this function <code>get_usd2inr</code>) by calling it as in like - <code>await get_usd2inr();</code>, you may get this error:</p>
<blockquote>
<p>Uncaught SyntaxError: await is only valid in async functions and the top level bodies of modules (at main.js:15:1)</p>
</blockquote>
<p>We solve this using self-executing functions - <code>()();</code> with <code>async</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> xe = <span class="hljs-number">0</span>;

<span class="hljs-keyword">const</span> get_usd2inr = <span class="hljs-keyword">async</span> () =&gt;
{
    <span class="hljs-keyword">const</span> url = <span class="hljs-string">"https://open.er-api.com/v6/latest/USD"</span>;
    <span class="hljs-keyword">try</span>
    {
        <span class="hljs-keyword">const</span> response = <span class="hljs-keyword">await</span> fetch(url);
        <span class="hljs-keyword">const</span> data = <span class="hljs-keyword">await</span> response.json();
        <span class="hljs-keyword">const</span> usd2inr = <span class="hljs-built_in">Number</span>(data.rates.INR.toFixed(<span class="hljs-number">2</span>));
        <span class="hljs-keyword">return</span> usd2inr;
    }
    <span class="hljs-keyword">catch</span> (error)
    {
        <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'Error fetching exchange rate:'</span>, error);
        <span class="hljs-keyword">throw</span> error;
    }
}

<span class="hljs-comment">// self-executing function</span>
(<span class="hljs-keyword">async</span> () =&gt;
    {
        xe = <span class="hljs-keyword">await</span> get_usd2inr();
        <span class="hljs-built_in">console</span>.log(xe); <span class="hljs-comment">// 86.97 as of 13th February 2025</span>
    }
)();

<span class="hljs-built_in">console</span>.log(xe); <span class="hljs-comment">// 0 - at this point of time, get_usd2inr() is not yet done executing</span>
</code></pre>
<p>In case you prefer a server-side fetch of open.er-api.com if at all they start blocking CORS all of a sudden :</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">exchangerate_usd2inr</span>():</span>
    url = <span class="hljs-string">"https://open.er-api.com/v6/latest/USD"</span>
    response = requests.get(url)
    usd2inr = response.json()[<span class="hljs-string">'rates'</span>][<span class="hljs-string">'INR'</span>]
    usd2inr = round(usd2inr, <span class="hljs-number">2</span>)    
    <span class="hljs-keyword">return</span> usd2inr
</code></pre>
<p>If you want to look into an example using workers check out a future blog post on using Google’s Comlink.</p>
]]></content:encoded></item><item><title><![CDATA[sleep for n seconds]]></title><description><![CDATA[My question to claude.ai for today, for which I have a PRO subscription.
myself :

whats the best and modern way to sleep for n seconds in JavaScript ? I am interested in latest browsers and not old ones. Latest can be 2024 or even 2025 also.

claude...]]></description><link>https://javascript.co.in/sleep</link><guid isPermaLink="true">https://javascript.co.in/sleep</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Sleep]]></category><category><![CDATA[ecmascript]]></category><category><![CDATA[promises]]></category><dc:creator><![CDATA[Anjanesh Lekshminarayanan]]></dc:creator><pubDate>Thu, 13 Feb 2025 11:52:33 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1739447474666/3a09edcd-7d12-4f65-aa29-18b212621b3b.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>My question to claude.ai for today, for which I have a PRO subscription.</p>
<p>myself :</p>
<blockquote>
<p>whats the best and modern way to sleep for n seconds in JavaScript ? I am interested in latest browsers and not old ones. Latest can be 2024 or even 2025 also.</p>
</blockquote>
<p>claude :</p>
<blockquote>
<p>For modern JavaScript (2024-2025), the best and cleanest way to sleep/delay execution is to use <code>Promise.sleep()</code>, which was introduced in ECMAScript 2024. Here's how to use it:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">await</span> <span class="hljs-built_in">Promise</span>.sleep(<span class="hljs-number">1000</span>); <span class="hljs-comment">// sleeps for 1 second</span>
</code></pre>
</blockquote>
<p>I searched in and out for this exciting new <code>Promise.sleep()</code> implementation … <a target="_blank" href="https://caniuse.com/?search=promise">caniuse</a>, forums, StackOverflow, <a target="_blank" href="https://support.google.com/chrome/answer/10612145?hl=en">turned on experimental features</a> in Chrome (Canary) etc etc. It was like frantically running around from pillar to post on a government initiated errand.</p>
<p>I kept getting :</p>
<blockquote>
<p>Uncaught TypeError: Promise.sleep is not a function</p>
</blockquote>
<p>Then I asked :</p>
<blockquote>
<p>“For modern JavaScript (2024-2025), the best and cleanest way to sleep/delay execution is to use Promise.sleep(), which was introduced in ECMAScript 2024”</p>
<p>Where is this mentioned ? Any references ?</p>
</blockquote>
<p>The reply I got from claude.ai :</p>
<blockquote>
<p>I apologize for my mistake. I made an incorrect statement about Promise.sleep(). After double-checking, I cannot find any official ECMAScript proposal or specification that introduces Promise.sleep() in ECMAScript 2024 or any other version.</p>
<p>The current best and modern way to implement sleep in JavaScript (as of 2024-2025) remains:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> sleep = <span class="hljs-function"><span class="hljs-params">ms</span> =&gt;</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Promise</span>(<span class="hljs-function"><span class="hljs-params">resolve</span> =&gt;</span> <span class="hljs-built_in">setTimeout</span>(resolve, ms));
<span class="hljs-comment">// Usage: await sleep(1000); // sleeps for 1 second</span>
</code></pre>
</blockquote>
<h2 id="heading-what-i-learnt-today-genai-can-take-you-for-a-ride-which-is-super-dangerous">What I learnt today: GenAI can take you for a ride which is super dangerous.</h2>
<p>I don’t think models are trained on data till the end of 2024 so it probably was my mistake in asking this question knowing that models’ training are a bit far behind and not up-to-date till last year ?</p>
<p>Let's stick to humans-led communities for now: <a target="_blank" href="https://stackoverflow.com/a/39914235/126833">https://stackoverflow.com/a/39914235/126833</a></p>
]]></content:encoded></item><item><title><![CDATA[Capture Option data on Select Change]]></title><description><![CDATA[Sometimes we want to 'listen' to an event change of the select element. Especially when the option is changed - and get the newly selected value and store it elsewhere. For this we use onchange on the select element and not on the option element.
The...]]></description><link>https://javascript.co.in/capture-option-data-on-select-change</link><guid isPermaLink="true">https://javascript.co.in/capture-option-data-on-select-change</guid><category><![CDATA[HTML]]></category><category><![CDATA[select]]></category><category><![CDATA[option]]></category><category><![CDATA[onchange]]></category><category><![CDATA[window object]]></category><dc:creator><![CDATA[Anjanesh Lekshminarayanan]]></dc:creator><pubDate>Sat, 17 Feb 2024 03:42:39 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1708141308832/c8afcc18-bd76-4495-9916-27a715e30003.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Sometimes we want to 'listen' to an event change of the <code>select</code> element. Especially when the option is changed - and get the newly selected value and store it elsewhere. For this we use <code>onchange</code> on the <code>select</code> element and not on the <code>option</code> element.</p>
<p>There are 2 ways to get the selected option's value, I'll show both, the first one being deprecated but still works but has been Legacy’d into standarization for the window object.</p>
<ol>
<li><p><a target="_blank" href="http://event.target">event.target</a>.selectedIndex</p>
</li>
<li><p>this.selectedIndex</p>
</li>
</ol>
<p>The <code>event</code> object is part of <code>window</code> object which should be <code>window.event</code> but browsers <em>may</em> drop support for it in the future. Instead use <code>this.selectedIndex</code>.</p>
<p><code>this[this.selectedIndex].getAttribute('data-email')</code></p>
<pre><code class="lang-xml"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"utf-8"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"viewport"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"width=device-width, initial-scale=1"</span> /&gt;</span>  
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">http-equiv</span>=<span class="hljs-string">"Cache-control"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"no-cache"</span>&gt;</span>  
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>capture option data on select change<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">link</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css"</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">"stylesheet"</span> <span class="hljs-attr">integrity</span>=<span class="hljs-string">"sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN"</span> <span class="hljs-attr">crossorigin</span>=<span class="hljs-string">"anonymous"</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"container d-flex flex-column"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">h3</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"mb-3"</span>&gt;</span>User<span class="hljs-tag">&lt;/<span class="hljs-name">h3</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"input-group mb-3"</span>&gt;</span>            
            <span class="hljs-tag">&lt;<span class="hljs-name">select</span>
                <span class="hljs-attr">id</span>=<span class="hljs-string">"user"</span>
                <span class="hljs-attr">onchange</span>=<span class="hljs-string">"
                document.querySelector('#user-email').value = this[this.selectedIndex].getAttribute('data-email');
                document.querySelector('#user-mobile').value = this[this.selectedIndex].getAttribute('data-mobile');
                "</span>
                <span class="hljs-attr">class</span>=<span class="hljs-string">"form-control"</span>
            &gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">option</span> <span class="hljs-attr">selected</span>&gt;</span>Select a User<span class="hljs-tag">&lt;/<span class="hljs-name">option</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">option</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"1"</span> <span class="hljs-attr">data-email</span>=<span class="hljs-string">"john@yahoo.com"</span> <span class="hljs-attr">data-mobile</span>=<span class="hljs-string">"6666666666"</span>&gt;</span>John Matthews<span class="hljs-tag">&lt;/<span class="hljs-name">option</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">option</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"4"</span> <span class="hljs-attr">data-email</span>=<span class="hljs-string">"harry@gmail.com"</span> <span class="hljs-attr">data-mobile</span>=<span class="hljs-string">"8888888888"</span>&gt;</span>Harry Smith<span class="hljs-tag">&lt;/<span class="hljs-name">option</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">option</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"5"</span> <span class="hljs-attr">data-email</span>=<span class="hljs-string">"donald@hotmail.com"</span> <span class="hljs-attr">data-mobile</span>=<span class="hljs-string">"3333333333"</span>&gt;</span>Donald More<span class="hljs-tag">&lt;/<span class="hljs-name">option</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">option</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"19"</span> <span class="hljs-attr">data-email</span>=<span class="hljs-string">"smith@matrix.com"</span> <span class="hljs-attr">data-mobile</span>=<span class="hljs-string">"1111111111"</span>&gt;</span>Agent Smith<span class="hljs-tag">&lt;/<span class="hljs-name">option</span>&gt;</span>
                <span class="hljs-tag">&lt;<span class="hljs-name">option</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"20"</span> <span class="hljs-attr">data-email</span>=<span class="hljs-string">"bruce@space.com"</span> <span class="hljs-attr">data-mobile</span>=<span class="hljs-string">"9898989898"</span>&gt;</span>Bruce Kennedy<span class="hljs-tag">&lt;/<span class="hljs-name">option</span>&gt;</span>
                <span class="hljs-tag">&lt;/<span class="hljs-name">select</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"mb-3"</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"user-email"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"user-email"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"form-control"</span> <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Email"</span> <span class="hljs-attr">disabled</span> /&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"user-mobile"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"user-mobile"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"form-control"</span> <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Mobile"</span> <span class="hljs-attr">disabled</span> /&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>    
<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p>Demo : <a target="_blank" href="https://anjanesh.s3.amazonaws.com/demo/capture-option-data-on-select-change.html">https://anjanesh.s3.amazonaws.com/demo/capture-option-data-on-select-change.html</a></p>
]]></content:encoded></item><item><title><![CDATA[Push and update object using destructuring]]></title><description><![CDATA[If you have an object like this :
const default_object = {
    vehicle: 'car',
    color: 'red',
    make: 'Honda',
};

and want to update the color then we would simply do default_object.color = 'green'
Let's say we have an array of objects like thi...]]></description><link>https://javascript.co.in/push-and-update-object-using-destructuring</link><guid isPermaLink="true">https://javascript.co.in/push-and-update-object-using-destructuring</guid><category><![CDATA[Destructuring]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[Objects]]></category><category><![CDATA[arrays]]></category><dc:creator><![CDATA[Anjanesh Lekshminarayanan]]></dc:creator><pubDate>Thu, 07 Dec 2023 02:21:11 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1701915537603/7332d83b-e125-42ce-b814-222d41e22f84.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>If you have an object like this :</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> default_object = {
    <span class="hljs-attr">vehicle</span>: <span class="hljs-string">'car'</span>,
    <span class="hljs-attr">color</span>: <span class="hljs-string">'red'</span>,
    <span class="hljs-attr">make</span>: <span class="hljs-string">'Honda'</span>,
};
</code></pre>
<p>and want to update the <code>color</code> then we would simply do <code>default_object.color = 'green'</code></p>
<p>Let's say we have an array of objects like this :</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> objects = [];
</code></pre>
<p>and we push as in <code>objects.push(default_object);</code></p>
<p>But what if you wanted to add the <code>default_object</code> and at the same time update the <code>color</code> of the newly pushed object? This is what is done to update the <code>color</code> attribute.</p>
<pre><code class="lang-javascript">objects.push({ ...default_object, <span class="hljs-attr">color</span>: <span class="hljs-string">'green'</span> });
</code></pre>
<p>This is equivalent to this writing like this :</p>
<pre><code class="lang-javascript">objects.push({ <span class="hljs-attr">vehicle</span>: <span class="hljs-string">'car'</span>, <span class="hljs-attr">color</span>: <span class="hljs-string">'red'</span>, <span class="hljs-attr">make</span>: <span class="hljs-string">'Honda'</span>, <span class="hljs-attr">color</span>: <span class="hljs-string">'green'</span> });
</code></pre>
<p>Adding <code>color</code> attribute twice only overwrites the first added <code>color</code>. So green gets assigned to the <code>color</code> value.</p>
<p>In <code>objects.push({ ...default_object, color: 'green' });</code> , <code>...default_object</code> is <em>destructured</em>, meaning it's "expanded" to <strong>vehicle: 'car', color: 'red', make: 'Honda'</strong> and then <strong>color: 'green'</strong> is added to the object overwriting <strong>color: 'red'</strong> in the expansion.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> objects = [];

<span class="hljs-keyword">const</span> default_object = {
    <span class="hljs-attr">vehicle</span>: <span class="hljs-string">'car'</span>,
    <span class="hljs-attr">color</span>: <span class="hljs-string">'red'</span>,
    <span class="hljs-attr">make</span>: <span class="hljs-string">'Honda'</span>,
};

<span class="hljs-built_in">console</span>.log(objects);

objects.push(default_object);

<span class="hljs-built_in">console</span>.log(objects);

objects.push({ <span class="hljs-attr">vehicle</span>: <span class="hljs-string">'car'</span>, <span class="hljs-attr">color</span>: <span class="hljs-string">'red'</span>, <span class="hljs-attr">make</span>: <span class="hljs-string">'Honda'</span>, <span class="hljs-attr">color</span>: <span class="hljs-string">'green'</span> });

objects.push({ ...default_object, <span class="hljs-attr">color</span>: <span class="hljs-string">'blue'</span> });

<span class="hljs-built_in">console</span>.log(objects);
</code></pre>
]]></content:encoded></item><item><title><![CDATA[Importance of using Getters in Vanilla JavaScript]]></title><description><![CDATA[Let's look at an example of why getters (and so are also setters) are so useful.
Let's say you have an AJAX call that you're using via fetch to retrieve the value of 1 USD in INR. Say we have a script that gets the content of https://open.er-api.com/...]]></description><link>https://javascript.co.in/importance-of-using-getters-in-vanilla-javascript</link><guid isPermaLink="true">https://javascript.co.in/importance-of-using-getters-in-vanilla-javascript</guid><category><![CDATA[getter and setter]]></category><category><![CDATA[getter]]></category><category><![CDATA[JavaScript]]></category><category><![CDATA[currency-converter]]></category><dc:creator><![CDATA[Anjanesh Lekshminarayanan]]></dc:creator><pubDate>Wed, 18 Oct 2023 01:24:07 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1697592190234/4258d9ca-5b81-4a56-b89d-f8a42672265d.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Let's look at an example of why getters (and so are also setters) are so useful.</p>
<p>Let's say you have an AJAX call that you're using via <code>fetch</code> to retrieve the value of 1 USD in INR. Say we have a script that gets the content of <a target="_blank" href="https://open.er-api.com/v6/latest/USD">https://open.er-api.com/v6/latest/USD</a> and parse the data to get the USD to INR value.</p>
<p>Now, the time taken to fetch from <a target="_blank" href="http://open.er-api.com">open.er-api.com</a> is not instant as its a network call to another location, so there <em>will</em> be some delay.</p>
<p>Ideally, the function to fetch the rates would be like this (thanks to <a target="_blank" href="http://open.er-api.com">open.er-api.com</a> for allowing cross-origin requests).</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> get_usd2inr = <span class="hljs-keyword">async</span> () =&gt;
{
    <span class="hljs-keyword">return</span> fetch(<span class="hljs-string">"https://open.er-api.com/v6/latest/USD"</span>)
    .then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span> response.json())
    .then(<span class="hljs-function"><span class="hljs-params">response</span> =&gt;</span>
    {
        <span class="hljs-built_in">console</span>.log(response[<span class="hljs-string">'rates'</span>][<span class="hljs-string">'INR'</span>]);
        <span class="hljs-keyword">return</span> response[<span class="hljs-string">'rates'</span>][<span class="hljs-string">'INR'</span>];
    });
}
</code></pre>
<p>Because it needs some time to execute, we need to use <code>await</code> in an <code>async</code> function.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> rate = <span class="hljs-literal">undefined</span>;

<span class="hljs-built_in">document</span>.addEventListener(<span class="hljs-string">"DOMContentLoaded"</span>, <span class="hljs-keyword">async</span> () =&gt;
{
    rate = <span class="hljs-keyword">await</span> get_usd2inr();
});
</code></pre>
<p>But if you want to assign it immediately to a variable, like inside that of an object :</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> obj = 
{
    <span class="hljs-attr">usd2inr</span>: rate
}
</code></pre>
<p>In 99% of cases, it'll be <code>undefined</code> as the <code>get_usd2inr</code> returns a <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">promise</a>, which hasn't yet finished executing and hence <code>obj.usd2inr</code> remains <code>undefined</code>.</p>
<p>To get the value of <code>rate</code> whenever you call for it, return <code>rate</code> in a getter method of the <code>obj</code> object. This way, the value of the AJAX called and processed <code>rate</code> is returned when you call for it later on as in <code>obj.usd2inr</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> obj = 
{
    <span class="hljs-keyword">get</span> <span class="hljs-title">usd2inr</span>()
    {
        <span class="hljs-keyword">return</span> rate;
    }
}
</code></pre>
<p>Here's the full code :</p>
<div class="gist-block embed-wrapper" data-gist-show-loading="false" data-id="11e0f061c040ba1656750d7ec9deb370"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a href="https://gist.github.com/anjanesh/11e0f061c040ba1656750d7ec9deb370" class="embed-card">https://gist.github.com/anjanesh/11e0f061c040ba1656750d7ec9deb370</a></div><p> </p>
<p>Clicking on the 1st button "click 1" would output undefined in the console where as clicking on the 2nd button "click 2" should output the USD value (83.272106 as of now) in the console.</p>
<p>Here's the demo online: <a target="_blank" href="https://anjanesh.s3.amazonaws.com/demo/getter-usd2inr.html">https://anjanesh.s3.amazonaws.com/demo/getter-usd2inr.html</a></p>
]]></content:encoded></item><item><title><![CDATA[Something totally new I learnt in JavaScript from Chat GPT]]></title><description><![CDATA[Today I learnt something totally brand new in JavaScript from ChatGPT !
let foo = () =>
{
    return { monthly: 3, onetime: 6 };
}

let obj = { x:0, monthly: 0, onetime: 0, y:0 };

How do I do the following?
{ obj.monthly, obj.onetime } = foo();

To ...]]></description><link>https://javascript.co.in/something-totally-new-i-learnt-in-javascript-from-chat-gpt</link><guid isPermaLink="true">https://javascript.co.in/something-totally-new-i-learnt-in-javascript-from-chat-gpt</guid><category><![CDATA[object]]></category><category><![CDATA[Destructuring]]></category><category><![CDATA[JavaScript]]></category><dc:creator><![CDATA[Anjanesh Lekshminarayanan]]></dc:creator><pubDate>Tue, 23 May 2023 09:18:36 GMT</pubDate><content:encoded><![CDATA[<p>Today I learnt something totally brand new in JavaScript from ChatGPT !</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> foo = <span class="hljs-function">() =&gt;</span>
{
    <span class="hljs-keyword">return</span> { <span class="hljs-attr">monthly</span>: <span class="hljs-number">3</span>, <span class="hljs-attr">onetime</span>: <span class="hljs-number">6</span> };
}

<span class="hljs-keyword">let</span> obj = { <span class="hljs-attr">x</span>:<span class="hljs-number">0</span>, <span class="hljs-attr">monthly</span>: <span class="hljs-number">0</span>, <span class="hljs-attr">onetime</span>: <span class="hljs-number">0</span>, <span class="hljs-attr">y</span>:<span class="hljs-number">0</span> };
</code></pre>
<p>How do I do the following?</p>
<pre><code class="lang-javascript">{ obj.monthly, obj.onetime } = foo();
</code></pre>
<p>To assign the values returned by the foo() function to the <strong>obj.monthly</strong> and <strong>obj.onetime</strong> properties, you can use object destructuring. Here's the updated code:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> foo = <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-keyword">return</span> { <span class="hljs-attr">monthly</span>: <span class="hljs-number">3</span>, <span class="hljs-attr">onetime</span>: <span class="hljs-number">6</span> };
};

<span class="hljs-keyword">let</span> obj = { <span class="hljs-attr">x</span>: <span class="hljs-number">0</span>, <span class="hljs-attr">monthly</span>: <span class="hljs-number">0</span>, <span class="hljs-attr">onetime</span>: <span class="hljs-number">0</span>, <span class="hljs-attr">y</span>: <span class="hljs-number">0</span> };

({ <span class="hljs-attr">monthly</span>: obj.monthly, <span class="hljs-attr">onetime</span>: obj.onetime } = foo());
</code></pre>
<p>In this code, object destructuring is used to extract the <code>monthly</code> and <code>onetime</code> properties from the object returned by the <code>foo()</code> function. The destructured properties are then assigned to the corresponding properties of the <code>obj</code> object using the syntax <code>property: target</code>.</p>
<p>After executing this code, <code>obj.monthly</code> will have the value <code>3</code> and <code>obj.onetime</code> will have the value <code>6</code>, matching the values returned by the <code>foo()</code> function.</p>
<p>My Q : Why is there a parenthesis surrounding <code>{ monthly: obj.monthly, onetime: obj.onetime } = foo()</code> ?</p>
<p>The parentheses surrounding <code>{ monthly: obj.monthly, onetime: obj.onetime }</code> in <code>({ monthly: obj.monthly, onetime: obj.onetime } = foo())</code> are necessary for syntactic reasons.</p>
<p>In JavaScript, when you have a statement that starts with a curly brace <code>{</code>, it is interpreted as a block statement rather than an object literal. Wrapping the entire assignment statement in parentheses helps clarify that you are performing an object destructuring assignment.</p>
<p>Without the parentheses, the JavaScript interpreter would treat <code>{ monthly: obj.monthly, onetime: obj.onetime }</code> as a block statement rather than an object literal, resulting in a syntax error.</p>
<p>Therefore, the parentheses are used to explicitly indicate that the intention is to destructure the returned object from <code>foo()</code> and assign its properties to <code>obj.monthly</code> and <code>obj.onetime</code>.</p>
]]></content:encoded></item><item><title><![CDATA[Initializing an object property if assigning to it fails]]></title><description><![CDATA[If you initialize a variable like let applications = {} and assign a property of applications with an array, like as in applications['foo'].push(1) it'll throw an error because foo is not yet a property of applications.
In Chrome it throws the follow...]]></description><link>https://javascript.co.in/initializing-an-object-property-if-assigning-to-it-fails</link><guid isPermaLink="true">https://javascript.co.in/initializing-an-object-property-if-assigning-to-it-fails</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[errors]]></category><category><![CDATA[errors in javascript]]></category><category><![CDATA[Error messages]]></category><category><![CDATA[Objects]]></category><dc:creator><![CDATA[Anjanesh Lekshminarayanan]]></dc:creator><pubDate>Sat, 22 Apr 2023 05:16:36 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1682140357271/7b6b9b8a-b518-4442-808f-2d2fe0912101.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>If you initialize a variable like <code>let applications = {}</code> and assign a property of <code>applications</code> with an array, like as in <code>applications['foo'].push(1)</code> it'll throw an error because <code>foo</code> is not <em>yet</em> a property of <code>applications</code>.</p>
<p>In Chrome it throws the following error :</p>
<blockquote>
<p>caught TypeError: Cannot read properties of undefined (reading 'push')</p>
</blockquote>
<p>In Firefox it throws :</p>
<blockquote>
<p>Uncaught TypeError: applications.foo is undefined</p>
</blockquote>
<p>In Safari it throws :</p>
<blockquote>
<p>undefined is not an object (evaluating 'applications[property].push'</p>
</blockquote>
<p>But at times we would want to push to an array of a property in <code>applications</code> like <code>applications['foo'].push(5)</code> where we don't know beforehand if <code>applications.foo</code> is defined or not.</p>
<p>In that case, we define it as <code>applications.foo = []</code>.</p>
<p>But, if we don't have a list of properties beforehand to mass assign to <code>applications</code>, if the data is coming from an AJAX request, then we can initialize the property using a try-catch block.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">try</span>
{
    applications[property].push(response[i][<span class="hljs-string">'version'</span>]);
}
<span class="hljs-keyword">catch</span>(e)
{
    <span class="hljs-keyword">if</span> (
        <span class="hljs-comment">// Chrome</span>
        e.message.includes(<span class="hljs-string">"Cannot read properties of undefined"</span>) ||
        <span class="hljs-comment">// FireFox</span>
        e.message.includes(<span class="hljs-string">"applications[property] is undefined"</span>) ||
        <span class="hljs-comment">// Safari</span>
        e.message.includes(<span class="hljs-string">"undefined is not an object (evaluating 'applications[property].push'"</span>)
        )
    {
        applications[property] = [response[i][<span class="hljs-string">'version'</span>]];
    }
    <span class="hljs-keyword">else</span>
    {
        <span class="hljs-built_in">console</span>.error(<span class="hljs-string">"error = "</span>, e.message);
    }
}
</code></pre>
<p>The catch here is to check for two error messages - one for Chrome and one for Firefox.</p>
<p><strong>UPDATE:</strong> A guy who works on the Chromium code-base for his company, The Browser Company (Arc.net) mentioned about using the optional chaining operator (<code>?.</code>)which was introduced in ES2020 - so now the entire try-catch block can be replaced with just this :</p>
<pre><code class="lang-javascript">applications[property]?.push(response[i][<span class="hljs-string">'version'</span>]);
</code></pre>
<p>Thanks <a class="user-mention" href="https://hashnode.com/@vivekgalatage">Vivek Galatage</a>.</p>
<p>Here is the full example source: <a target="_blank" href="https://gist.github.com/anjanesh/fda4de82fe22f82ba0db5caf08308968">https://gist.github.com/anjanesh/fda4de82fe22f82ba0db5caf08308968</a></p>
<div class="gist-block embed-wrapper" data-gist-show-loading="false" data-id="fda4de82fe22f82ba0db5caf08308968"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a href="https://gist.github.com/anjanesh/fda4de82fe22f82ba0db5caf08308968" class="embed-card">https://gist.github.com/anjanesh/fda4de82fe22f82ba0db5caf08308968</a></div>]]></content:encoded></item><item><title><![CDATA[Client-side AJAX using JSON]]></title><description><![CDATA[Very often, many developers, including myself in the past, normally all along we were using jQuery's $.ajax and sending in JSON with dataType: 'json' without really sending the content-type as a JSON string which is supposed to be application/json - ...]]></description><link>https://javascript.co.in/client-side-ajax-using-json</link><guid isPermaLink="true">https://javascript.co.in/client-side-ajax-using-json</guid><category><![CDATA[Ajax]]></category><category><![CDATA[json]]></category><category><![CDATA[fetch]]></category><category><![CDATA[formdata]]></category><dc:creator><![CDATA[Anjanesh Lekshminarayanan]]></dc:creator><pubDate>Wed, 01 Mar 2023 04:59:28 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1677646683747/c4cfedce-e156-4622-87e6-7bb46872ad04.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Very often, many developers, including <em>myself</em> in the past, normally all along we were using jQuery's <code>$.ajax</code> and sending in JSON with <code>dataType: 'json'</code> without really sending the <code>content-type</code> as a JSON string which is supposed to be <code>application/json</code> - instead we were actually sending in a regular POST (<code>application/x-www-urlencoded</code>) and decoding it from the PHP side as <code>$_POST</code>.</p>
<p>So, if you have this script, <strong>post.php</strong>, in a folder :</p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>
$post_body = $_POST;
<span class="hljs-keyword">echo</span> json_encode($post_body);
<span class="hljs-meta">?&gt;</span>
</code></pre>
<p>and in <strong>jqurey-ajax.html</strong> :</p>
<pre><code class="lang-xml"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span> 
<span class="hljs-tag">&lt;<span class="hljs-name">html</span> <span class="hljs-attr">lang</span>=<span class="hljs-string">"en"</span>&gt;</span> 
<span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span> 
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"UTF-8"</span>&gt;</span> 
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">http-equiv</span>=<span class="hljs-string">"X-UA-Compatible"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"IE=edge"</span>&gt;</span> 
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"viewport"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"width=device-width, initial-scale=1.0"</span>&gt;</span> 
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>jQuery AJAX<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>     
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span> 
<span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span> 
<span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span> 

<span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
<span class="hljs-keyword">let</span> url = <span class="hljs-string">"http://localhost:8989/post.php"</span>;

<span class="hljs-keyword">const</span> formData = <span class="hljs-keyword">new</span> FormData();
formData.append(<span class="hljs-string">"username"</span>, <span class="hljs-string">"john"</span>);
formData.append(<span class="hljs-string">"password"</span>, <span class="hljs-string">"a5y6e7Chk65kmFWeK5F5"</span>);

<span class="hljs-keyword">const</span> run = <span class="hljs-keyword">async</span>() =&gt;
{   
    $.ajax({
        <span class="hljs-attr">type</span>: <span class="hljs-string">'ajax'</span>,
        <span class="hljs-attr">method</span>: <span class="hljs-string">'post'</span>,
        <span class="hljs-attr">url</span>: url,
        <span class="hljs-attr">data</span>: {<span class="hljs-attr">username</span>: <span class="hljs-string">"john"</span>, <span class="hljs-attr">password</span>: <span class="hljs-string">"a5y6e7Chk65kmFWeK5F5"</span>},
        <span class="hljs-attr">async</span>: <span class="hljs-literal">false</span>,
        <span class="hljs-attr">dataType</span>: <span class="hljs-string">'json'</span>,
        <span class="hljs-attr">success</span>: <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">result</span>) </span>{ <span class="hljs-built_in">console</span>.log(result); },
        <span class="hljs-attr">error</span>: <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{ <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"error"</span>); }
    });
}

run();

</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p>we get :</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1677646306335/cc06362a-78b9-41cc-981b-5afac656c1bc.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-the-real-json">The Real JSON</h2>
<h3 id="heading-for-sending-in-non-json-requests">For sending in non-JSON requests</h3>
<p>Have this script, run.php, in the same folder :</p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>
$post_body = file_get_contents(<span class="hljs-string">'php://input'</span>);
parse_str($post_body, $queryArray);
print_r($queryArray);
<span class="hljs-meta">?&gt;</span>
</code></pre>
<p>If you have this HTML file in the same folder as client.html</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> url = <span class="hljs-string">"http://localhost:8989/run.php"</span>;

<span class="hljs-keyword">const</span> formData = <span class="hljs-keyword">new</span> FormData();
formData.append(<span class="hljs-string">"username"</span>, <span class="hljs-string">"john"</span>);
formData.append(<span class="hljs-string">"password"</span>, <span class="hljs-string">"a5y6e7Chk65kmFWeK5F5"</span>);

<span class="hljs-keyword">const</span> run = <span class="hljs-keyword">async</span>() =&gt;
{   
    <span class="hljs-keyword">let</span> response = <span class="hljs-keyword">await</span> fetch(url,
        {
            <span class="hljs-attr">method</span>: <span class="hljs-string">"POST"</span>,
            <span class="hljs-attr">headers</span>:
            {
                <span class="hljs-string">"Content-Type"</span>: <span class="hljs-string">"application/x-www-urlencoded"</span>,                
            },
            <span class="hljs-attr">body</span>: <span class="hljs-keyword">new</span> URLSearchParams(formData),            
        });
}

run();
</code></pre>
<p>If you run `php.exe -S <a target="_blank" href="http://localhost:8989">localhost:8989</a>`, you should get this in the response of the URL request you'll see in console :</p>
<pre><code class="lang-plaintext">Array
(
    [username] =&gt; john
    [password] =&gt; a5y6e7Chk65kmFWeK5F5
)
</code></pre>
<h3 id="heading-for-sending-in-json-requests">For sending in JSON requests</h3>
<p>run.php :</p>
<pre><code class="lang-php"><span class="hljs-meta">&lt;?php</span>
$post_body = file_get_contents(<span class="hljs-string">'php://input'</span>);
print_r($post_body);
<span class="hljs-meta">?&gt;</span>
</code></pre>
<p>client.html :</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> url = <span class="hljs-string">"http://localhost:8989/run.php"</span>;

<span class="hljs-keyword">const</span> formData = <span class="hljs-keyword">new</span> FormData();
formData.append(<span class="hljs-string">"username"</span>, <span class="hljs-string">"john"</span>);
formData.append(<span class="hljs-string">"password"</span>, <span class="hljs-string">"a5y6e7Chk65kmFWeK5F5"</span>);

<span class="hljs-keyword">const</span> run = <span class="hljs-keyword">async</span>() =&gt;
{   
    <span class="hljs-keyword">var</span> object = {};
    formData.forEach(<span class="hljs-function">(<span class="hljs-params">value, key</span>) =&gt;</span> object[key] = value);

    <span class="hljs-keyword">let</span> response = <span class="hljs-keyword">await</span> fetch(url,
        {
            <span class="hljs-attr">method</span>: <span class="hljs-string">"POST"</span>,
            <span class="hljs-attr">headers</span>:
            {                
                <span class="hljs-string">"Content-Type"</span>:<span class="hljs-string">"application/json"</span>,
            },            
            <span class="hljs-attr">body</span>: <span class="hljs-built_in">JSON</span>.stringify(object)
        });
}

run();
</code></pre>
<p>We get :</p>
<pre><code class="lang-plaintext">username    "john"
password    "a5y6e7Chk65kmFWeK5F5"
</code></pre>
<p>I haven't <em>echo</em>ed a JSON string to the output in the above 2 examples because I just wanted show how it's communicated - I'll leave it up to you to print a JSON string on the server-side for the client to fetch as response.</p>
]]></content:encoded></item><item><title><![CDATA[Using Optional Chaining for checking for existence of nested Object key]]></title><description><![CDATA[In PHP we can do use isset() for checking the existence of a deeply nested array's key since the beginning of time :
<?php
$p1 = "a9bedbd81019b877";
$p2 = "47bd5f64f7be5578";

$obj =
[
    'people' =>
    [
        $p1 =>
        [
            'first...]]></description><link>https://javascript.co.in/using-optional-chaining-for-checking-for-existence-of-nested-object-key</link><guid isPermaLink="true">https://javascript.co.in/using-optional-chaining-for-checking-for-existence-of-nested-object-key</guid><category><![CDATA[object]]></category><category><![CDATA[Optional chaining]]></category><dc:creator><![CDATA[Anjanesh Lekshminarayanan]]></dc:creator><pubDate>Wed, 07 Sep 2022 05:58:50 GMT</pubDate><content:encoded><![CDATA[<p>In PHP we can do use <code>isset()</code> for checking the existence of a deeply nested array's key since the beginning of time :</p>
<pre><code><span class="hljs-meta">&lt;?php</span>
$p1 = <span class="hljs-string">"a9bedbd81019b877"</span>;
$p2 = <span class="hljs-string">"47bd5f64f7be5578"</span>;

$obj =
[
    <span class="hljs-string">'people'</span> =&gt;
    [
        $p1 =&gt;
        [
            <span class="hljs-string">'first_name'</span> =&gt; <span class="hljs-string">'John'</span>,
            <span class="hljs-string">'last_name'</span> =&gt; <span class="hljs-string">'Smith'</span>,
            <span class="hljs-string">'suffix'</span> =&gt; <span class="hljs-string">'Sr'</span>,
            <span class="hljs-string">'results'</span> =&gt; [ <span class="hljs-string">'math'</span> =&gt; <span class="hljs-number">82</span>, <span class="hljs-string">'english'</span> =&gt; <span class="hljs-number">79</span>, <span class="hljs-string">'science'</span> =&gt; <span class="hljs-number">50</span> ]
        ],

        $p2 =&gt;
        [
            <span class="hljs-string">'first_name'</span> =&gt; <span class="hljs-string">'Timothy'</span>,
            <span class="hljs-string">'middle_name'</span> =&gt; <span class="hljs-string">'Bob'</span>,
            <span class="hljs-string">'last_name'</span> =&gt; <span class="hljs-string">'Jones'</span>
        ]
    ]
];

<span class="hljs-keyword">if</span> (<span class="hljs-keyword">isset</span>($obj[<span class="hljs-string">'people'</span>][$p1][<span class="hljs-string">'results'</span>][<span class="hljs-string">'science'</span>]))
{
    <span class="hljs-keyword">echo</span> $obj[<span class="hljs-string">'people'</span>][$p1][<span class="hljs-string">'results'</span>][<span class="hljs-string">'science'</span>];
}
<span class="hljs-keyword">echo</span> <span class="hljs-string">"\n"</span>;
<span class="hljs-keyword">if</span> (!<span class="hljs-keyword">isset</span>($obj[<span class="hljs-string">'people'</span>][$p2][<span class="hljs-string">'results'</span>][<span class="hljs-string">'science'</span>]))
{
    <span class="hljs-keyword">echo</span> <span class="hljs-string">'Not Found'</span>;
}
<span class="hljs-keyword">echo</span> <span class="hljs-string">"\n"</span>;
<span class="hljs-meta">?&gt;</span>
</code></pre><p>There are many solutions to this in JavaScript like the answers given here in <a target="_blank" href="https://stackoverflow.com/questions/2631001/test-for-existence-of-nested-javascript-object-key">StackOverflow</a>.</p>
<p>But I think the best solution lies in ECMA 262 (ES2020) which now all browsers support.</p>
<pre><code>let p1 <span class="hljs-operator">=</span> <span class="hljs-string">"a9bedbd81019b877"</span>;
let p2 <span class="hljs-operator">=</span> <span class="hljs-string">"47bd5f64f7be5578"</span>;

let obj <span class="hljs-operator">=</span>
{
    <span class="hljs-string">'people'</span> :
    {
        [p1] :
        {
            <span class="hljs-string">'first_name'</span>: <span class="hljs-string">'John'</span>,
            <span class="hljs-string">'last_name'</span>: <span class="hljs-string">'Smith'</span>,
            <span class="hljs-string">'suffix'</span>: <span class="hljs-string">'Sr'</span>,
            <span class="hljs-string">'results'</span>: { <span class="hljs-string">'math'</span>: <span class="hljs-number">82</span>, <span class="hljs-string">'english'</span>: <span class="hljs-number">79</span>, <span class="hljs-string">'science'</span>: <span class="hljs-number">50</span> }
        },

        [p2] :
        {
            <span class="hljs-string">'first_name'</span>: <span class="hljs-string">'Timothy'</span>,
            <span class="hljs-string">'middle_name'</span>: <span class="hljs-string">'Bob'</span>,
            <span class="hljs-string">'last_name'</span>: <span class="hljs-string">'Jones'</span>,
        }
    }
}

<span class="hljs-keyword">if</span> (obj?.people?.[p1]?.results?.science)
{
    console.log(<span class="hljs-string">'science = '</span>, obj?.people?.[p1]?.results?.science);
}

console.log(obj?.people?.[p2]?.results?.science);
</code></pre><p>Output :</p>
<pre><code>science =  50
undefined
</code></pre>]]></content:encoded></item><item><title><![CDATA[reduce function]]></title><description><![CDATA[I hope this code on how to understand the reduce function in JavaScript is is self-explanatory.
var desks = [
  { type: 'sitting' },
  { type: 'standing' },
  { type: 'sitting' },
  { type: 'sitting' },
  { type: 'standing' }
];

var deskTypes = desk...]]></description><link>https://javascript.co.in/reduce-function</link><guid isPermaLink="true">https://javascript.co.in/reduce-function</guid><category><![CDATA[Reduce]]></category><dc:creator><![CDATA[Anjanesh Lekshminarayanan]]></dc:creator><pubDate>Mon, 04 Jul 2022 04:36:59 GMT</pubDate><content:encoded><![CDATA[<p>I hope this code on how to understand the <code>reduce</code> function in JavaScript is is self-explanatory.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> desks = [
  { <span class="hljs-attr">type</span>: <span class="hljs-string">'sitting'</span> },
  { <span class="hljs-attr">type</span>: <span class="hljs-string">'standing'</span> },
  { <span class="hljs-attr">type</span>: <span class="hljs-string">'sitting'</span> },
  { <span class="hljs-attr">type</span>: <span class="hljs-string">'sitting'</span> },
  { <span class="hljs-attr">type</span>: <span class="hljs-string">'standing'</span> }
];

<span class="hljs-keyword">var</span> deskTypes = desks.reduce(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">d, desk</span>)
</span>{   
    d[desk.type]++;    
    <span class="hljs-keyword">return</span> d;
}, { <span class="hljs-attr">sitting</span>: <span class="hljs-number">0</span>, <span class="hljs-attr">standing</span>: <span class="hljs-number">0</span> });

<span class="hljs-built_in">console</span>.log(deskTypes);
</code></pre>
<p>We are initializing <strong>deskTypes</strong> to <code>{ sitting: 0, standing: 0 }</code> just before going through the reduce function.</p>
<p><code>d</code> gets returned in the function which gets updated to <code>deskTypes</code> while <code>desk</code> is each value of <code>desks</code> in the loop.</p>
<pre><code class="lang-javascript"> node trips.js 
{ <span class="hljs-attr">sitting</span>: <span class="hljs-number">3</span>, <span class="hljs-attr">standing</span>: <span class="hljs-number">2</span> }
</code></pre>
<p>This works in IE9-IE11 too.</p>
<p>UPDATE : Another common use-case for <code>reduce</code> :</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> shoes = [
    { <span class="hljs-attr">id</span>:<span class="hljs-number">205</span>, <span class="hljs-attr">name</span>:<span class="hljs-string">'reebok'</span>, <span class="hljs-attr">price</span>:<span class="hljs-number">50</span> },
    { <span class="hljs-attr">id</span>:<span class="hljs-number">206</span>, <span class="hljs-attr">name</span>:<span class="hljs-string">'adidas'</span>, <span class="hljs-attr">price</span>:<span class="hljs-number">45</span> },
    { <span class="hljs-attr">id</span>:<span class="hljs-number">207</span>, <span class="hljs-attr">name</span>:<span class="hljs-string">'nike'</span>, <span class="hljs-attr">price</span>:<span class="hljs-number">150</span> },
    { <span class="hljs-attr">id</span>:<span class="hljs-number">208</span>, <span class="hljs-attr">name</span>:<span class="hljs-string">'clarks'</span>, <span class="hljs-attr">price</span>:<span class="hljs-number">95</span> },
    { <span class="hljs-attr">id</span>:<span class="hljs-number">209</span>, <span class="hljs-attr">name</span>:<span class="hljs-string">'bata'</span>, <span class="hljs-attr">price</span>:<span class="hljs-number">30</span> },
];

<span class="hljs-built_in">console</span>.log(shoes.reduce(<span class="hljs-function">(<span class="hljs-params">n, {price}</span>) =&gt;</span> n + price, <span class="hljs-number">0</span>));
</code></pre>
<p>Will output 370 because 50+45+150+95+30=370</p>
]]></content:encoded></item><item><title><![CDATA[Converting a traditional function to an arrow function]]></title><description><![CDATA[If you're old like me (in my 40s) and got into JavaScript way before ES6 (2015) but didn't use the new syntax that came out post 2015 like arrow functions, then here's a preview of how to convert traditional functions to arrow functions - as an argum...]]></description><link>https://javascript.co.in/converting-a-traditional-function-to-an-arrow-function</link><guid isPermaLink="true">https://javascript.co.in/converting-a-traditional-function-to-an-arrow-function</guid><category><![CDATA[#arrowfunction]]></category><category><![CDATA[ES6]]></category><dc:creator><![CDATA[Anjanesh Lekshminarayanan]]></dc:creator><pubDate>Fri, 01 Jul 2022 08:04:09 GMT</pubDate><content:encoded><![CDATA[<p>If you're old like me (in my 40s) and got into JavaScript way before ES6 (2015) but didn't use the new syntax that came out post 2015 like arrow functions, then here's a preview of how to convert traditional functions to arrow functions - as an argument to a ES6 functions like <code>find</code>, <code>map</code>, <code>filter</code> and <code>reduce</code>.</p>
<pre><code>const arr <span class="hljs-operator">=</span> [<span class="hljs-number">3</span>, <span class="hljs-number">5</span>, <span class="hljs-number">6</span>, <span class="hljs-number">8</span>, <span class="hljs-number">7</span>];

console.log(<span class="hljs-string">"=== Array ==="</span>);
console.log(arr);
console.log(<span class="hljs-string">""</span>);


<span class="hljs-comment">// Find - will return 6</span>

let es6_find_1 <span class="hljs-operator">=</span> arr.find(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">n</span>)
</span>{
    <span class="hljs-keyword">if</span> (n <span class="hljs-operator">%</span> <span class="hljs-number">2</span> <span class="hljs-operator">=</span><span class="hljs-operator">=</span><span class="hljs-operator">=</span> <span class="hljs-number">0</span>)
    {        
        <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
    }

    <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;
});

let es6_find_2 <span class="hljs-operator">=</span> arr.find(n <span class="hljs-operator">=</span><span class="hljs-operator">&gt;</span> n <span class="hljs-operator">%</span> <span class="hljs-number">2</span> <span class="hljs-operator">=</span><span class="hljs-operator">=</span><span class="hljs-operator">=</span> <span class="hljs-number">0</span>);

console.log(<span class="hljs-string">"=== Find ==="</span>);
console.log(es6_find_1);
console.log(es6_find_2);
console.log(<span class="hljs-string">""</span>);

<span class="hljs-comment">// Map - will return [ 6, 10, 12, 16, 14 ]</span>

let es6_map_1 <span class="hljs-operator">=</span> arr.map(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">n</span>)
</span>{
    <span class="hljs-keyword">return</span> n <span class="hljs-operator">*</span> <span class="hljs-number">2</span>;
});

let es6_map_2 <span class="hljs-operator">=</span> arr.map(n <span class="hljs-operator">=</span><span class="hljs-operator">&gt;</span> n <span class="hljs-operator">*</span> <span class="hljs-number">2</span>);

console.log(<span class="hljs-string">"=== Map ==="</span>);
console.log(es6_map_1);
console.log(es6_map_2);
console.log(<span class="hljs-string">""</span>);

<span class="hljs-comment">// Filter - will return [ 6, 8 ]</span>

let es6_filter_1 <span class="hljs-operator">=</span> arr.filter(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">n</span>)
</span>{
    <span class="hljs-keyword">if</span> (n <span class="hljs-operator">%</span> <span class="hljs-number">2</span> <span class="hljs-operator">=</span><span class="hljs-operator">=</span><span class="hljs-operator">=</span> <span class="hljs-number">0</span>)
    {
        <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
    }

    <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;
});

let es6_filter_2 <span class="hljs-operator">=</span> arr.filter(n <span class="hljs-operator">=</span><span class="hljs-operator">&gt;</span> n <span class="hljs-operator">%</span> <span class="hljs-number">2</span> <span class="hljs-operator">=</span><span class="hljs-operator">=</span><span class="hljs-operator">=</span> <span class="hljs-number">0</span>);

console.log(<span class="hljs-string">"=== Filter ==="</span>);
console.log(es6_filter_1);
console.log(es6_filter_2);
console.log(<span class="hljs-string">""</span>);

<span class="hljs-comment">// Reduce - will return 29</span>

let es6_reduce_1 <span class="hljs-operator">=</span> arr.reduce(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">acc, cur</span>)
</span>{
    <span class="hljs-keyword">return</span> acc <span class="hljs-operator">+</span> cur;    
});

let es6_reduce_2 <span class="hljs-operator">=</span> arr.reduce((acc, cur) <span class="hljs-operator">=</span><span class="hljs-operator">&gt;</span> acc <span class="hljs-operator">+</span> cur);

console.log(<span class="hljs-string">"=== Reduce ==="</span>);
console.log(es6_reduce_1);
console.log(es6_reduce_2);
console.log(<span class="hljs-string">""</span>);
</code></pre><p>Read : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions</p>
]]></content:encoded></item></channel></rss>