<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/">
    <channel>
        <title>QuantArcane</title>
        <link>https://paragraph.com/@quantarcane</link>
        <description>I "code" about bots &amp; algos. Write about: Web3 Dev, DeFI, on/off-chain footprints, AI, NFTs &amp; any novel edge I find...</description>
        <lastBuildDate>Mon, 06 Apr 2026 09:10:14 GMT</lastBuildDate>
        <docs>https://validator.w3.org/feed/docs/rss2.html</docs>
        <generator>https://github.com/jpmonette/feed</generator>
        <language>en</language>
        <image>
            <title>QuantArcane</title>
            <url>https://storage.googleapis.com/papyrus_images/dd0917388dde1c0abb3e7b4889fb90ca75eff6c7b4c99adb6615824ae0abe8b3.png</url>
            <link>https://paragraph.com/@quantarcane</link>
        </image>
        <copyright>All rights reserved</copyright>
        <item>
            <title><![CDATA[III. Asynchronous JavaScript - A Fast Track Guide for C#/Java/... devs]]></title>
            <link>https://paragraph.com/@quantarcane/iii-asynchronous-javascript-a-fast-track-guide-for-c-java-devs</link>
            <guid>KP3ik5LRdrOlc7ij9JFe</guid>
            <pubDate>Sat, 15 Jul 2023 06:30:26 GMT</pubDate>
            <description><![CDATA[In this third part of our three-part series, we will delve into the evolution of the JavaScript language in the context of asynchronous programming. If you wish to:Start from the beginning navigate to: Part IGo to Part II, navigate to: Part IILet&apos;s begin with the following scenario: Suppose we have a method called "getCapitals" that utilizes an external API to fetch world capitals. How can we return the results from the "getCapitals" method without halting our entire system while waiting...]]></description>
            <content:encoded><![CDATA[<p>In this third part of our three-part series, we will delve into the evolution of the JavaScript language in the context of asynchronous programming. If you wish to:</p><ul><li><p>Start from the beginning navigate to: <a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://mirror.xyz/quantarcane.eth/3XMZRHJIMX7tEwYt2ZOyN9iOuyzji97HZMeVXNCXeoQ">Part I</a></p></li><li><p>Go to Part II, navigate to: <a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://mirror.xyz/quantarcane.eth/sw3wZxsZH-JXExMDCxcJFvd2sN9iS1X2YxNFnAZRPpI">Part II</a></p></li></ul><p>Let&apos;s begin with the following scenario: Suppose we have a method called &quot;getCapitals&quot; that utilizes an external API to fetch world capitals. How can we return the results from the &quot;getCapitals&quot; method without halting our entire system while waiting for the capitals to be fetched?</p><p>In a synchronous approach, we would simply wait for the capitals to be fetched, effectively blocking our program, and then use the &quot;return&quot; statement with the fetched data.</p><p>In an asynchronous approach, the first method we will explore is using the callback pattern.</p><figure float="none" data-type="figure" class="img-center" style="max-width: null;"><img src="https://storage.googleapis.com/papyrus_images/9ca1253ba08f3d507e8abd6d0e98d073fa52a6147224df62a673de33a0ff6cbb.png" alt="Callback Pattern" blurdataurl="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACwAAAAAAQABAAACAkQBADs=" nextheight="600" nextwidth="800" class="image-node embed"><figcaption HTMLAttributes="[object Object]" class="">Callback Pattern</figcaption></figure><pre data-type="codeBlock" text="const callbackFunction = function (result) {
    console.log(result);
}

const fakeCapitals = getCapitalsFake(callbackFunction);

console.log(&quot;Continue doing some other work that does not depend on the capitals&quot;);
"><code>const callbackFunction <span class="hljs-operator">=</span> <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">result</span>) </span>{
    console.log(result);
}

const fakeCapitals <span class="hljs-operator">=</span> getCapitalsFake(callbackFunction);

console.log(<span class="hljs-string">"Continue doing some other work that does not depend on the capitals"</span>);
</code></pre><p>On the left (in “app.js” file)</p><ul><li><p>I define a callback function that, when called, prints the capitals to the console.</p></li><li><p>then I just call the “requests.js“ getCapitals function passing in the callback function to be called with the fetched data.</p></li></ul><pre data-type="codeBlock" text="const getCapitalsFake = (callbackFunction) =&gt; {
    setTimeout(() =&gt; {
        const data = &quot;waiting 3 seconds for data to arrive...&quot;;
        callbackFunction(data);
    }, 3000)
}
"><code>const <span class="hljs-attr">getCapitalsFake</span> = (callbackFunction) => {
    setTimeout(() => {
        const <span class="hljs-attr">data</span> = <span class="hljs-string">"waiting 3 seconds for data to arrive..."</span><span class="hljs-comment">;</span>
        callbackFunction(data)<span class="hljs-comment">;</span>
    }, 3000)
}
</code></pre><p>On the right (in “requests.js” file) the GetCapitals function:</p><ul><li><p>receives the callback function passed in as a parameter.</p></li><li><p>it makes a http request to the API in order to fetch the data</p></li><li><p>defines an inner event listener that listens when the data is ready</p></li><li><p>the method finishes its execution and gives back control to app.js to execute other code.</p></li><li><p>Only once the data arrives, the event listener triggers and from within the listener we call the callback function from “app.js” received as param, passing it the result data.</p></li></ul><p>Above I excluded all the boilerplate code of making the http request and listening for the result for brevity. Here is the actual code:</p><pre data-type="codeBlock" text="const getCapitals = (callback) =&gt; {

    const request = new XMLHttpRequest()
    request.addEventListener(&apos;readystatechange&apos;, (e) =&gt; {
        if (e.target.readyState === 4 &amp;&amp; e.target.status === 200) {
            const data = JSON.parse(e.target.responseText);
            console.log(data)
            callback(undefined, data.map(d =&gt; d.capital).flat());
        } else if (e.target.readyState === 4) {
            callback(&apos;An error has taken place&apos;, undefined);
        }
    });
    request.open(&apos;GET&apos;, &apos;https://restcountries.com/v3.1/all?fields=capital&apos;);
    request.send();
}
"><code>const getCapitals <span class="hljs-operator">=</span> (callback) <span class="hljs-operator">=</span><span class="hljs-operator">></span> {

    const request <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> XMLHttpRequest()
    request.addEventListener(<span class="hljs-string">'readystatechange'</span>, (e) <span class="hljs-operator">=</span><span class="hljs-operator">></span> {
        <span class="hljs-keyword">if</span> (e.target.readyState <span class="hljs-operator">=</span><span class="hljs-operator">=</span><span class="hljs-operator">=</span> <span class="hljs-number">4</span> <span class="hljs-operator">&#x26;</span><span class="hljs-operator">&#x26;</span> e.target.status <span class="hljs-operator">=</span><span class="hljs-operator">=</span><span class="hljs-operator">=</span> <span class="hljs-number">200</span>) {
            const data <span class="hljs-operator">=</span> JSON.parse(e.target.responseText);
            console.log(data)
            callback(undefined, data.map(d <span class="hljs-operator">=</span><span class="hljs-operator">></span> d.capital).flat());
        } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (e.target.readyState <span class="hljs-operator">=</span><span class="hljs-operator">=</span><span class="hljs-operator">=</span> <span class="hljs-number">4</span>) {
            callback(<span class="hljs-string">'An error has taken place'</span>, undefined);
        }
    });
    request.open(<span class="hljs-string">'GET'</span>, <span class="hljs-string">'https://restcountries.com/v3.1/all?fields=capital'</span>);
    request.<span class="hljs-built_in">send</span>();
}
</code></pre><p>And here is the code that calls the getCapitals method. Please note I used an anonymous arrow function as parameter instead of declaring the callback separately:</p><pre data-type="codeBlock" text="getCapitals((error, capitals) =&gt; {
    if (error) {
    console.log(`Error: ${error}`)
    } else {
    console.log(capitals)
    }
});
"><code>getCapitals((<span class="hljs-function"><span class="hljs-keyword">error</span>, <span class="hljs-title">capitals</span>) => </span>{
    <span class="hljs-keyword">if</span> (<span class="hljs-function"><span class="hljs-keyword">error</span>) </span>{
    console.log(`<span class="hljs-built_in">Error</span>: ${<span class="hljs-function"><span class="hljs-keyword">error</span>}`)
    } <span class="hljs-title"><span class="hljs-keyword">else</span></span> </span>{
    console.log(capitals)
    }
});
</code></pre><h2 id="h-promises" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">Promises</h2><p>Promises in JS are like Tasks in C#. To create a new promise we use its constructor that expects two callback functions as parameters. One that should be called on success and one on failure:</p><pre data-type="codeBlock" text="const myPromise = new Promise((resolve, reject) =&gt; {
    setTimeout(() =&gt; {
        const currentSeconds = new Date().getSeconds();
        if (currentSeconds % 2 === 0) {
            resolve(&quot;I am the data from the API endpoint&quot;);
        }
        else {
            reject(&quot;I am an error, the API endpoint was down&quot;);
        }

    }, 2000)
});
"><code>const myPromise <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> Promise((resolve, reject) <span class="hljs-operator">=</span><span class="hljs-operator">></span> {
    setTimeout(() <span class="hljs-operator">=</span><span class="hljs-operator">></span> {
        const currentSeconds <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> Date().getSeconds();
        <span class="hljs-keyword">if</span> (currentSeconds <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>) {
            resolve(<span class="hljs-string">"I am the data from the API endpoint"</span>);
        }
        <span class="hljs-keyword">else</span> {
            reject(<span class="hljs-string">"I am an error, the API endpoint was down"</span>);
        }

    }, <span class="hljs-number">2000</span>)
});
</code></pre><p>In order to get the result back from a promise we use “then”. then is a method on the Promise object and it requires two functions as parameters:</p><ul><li><p>a function that will be called when the Promise will be <strong>resolved</strong> with the data</p></li><li><p>a function that will be called when the Promise will be <strong>rejected</strong> with the error</p></li></ul><pre data-type="codeBlock" text="myPromise.then((data) =&gt; {
    console.log(data);
}, (err) =&gt; {
    console.log(err);
})
"><code>myPromise.then((data) <span class="hljs-operator">=</span><span class="hljs-operator">></span> {
    console.log(data);
}, (err) <span class="hljs-operator">=</span><span class="hljs-operator">></span> {
    console.log(err);
})
</code></pre><p>in order to allow the promise access some data we can wrap a function around it that returns the promise like so:</p><pre data-type="codeBlock" text="const getPromiseFunction = (seedNumber) =&gt; {
    return new Promise((resolve, reject) =&gt; {
        //code excluded for brevity
    });
"><code><span class="hljs-keyword">const</span> <span class="hljs-title function_">getPromiseFunction</span> = (<span class="hljs-params">seedNumber</span>) => {
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">Promise</span>(<span class="hljs-function">(<span class="hljs-params">resolve, reject</span>) =></span> {
        <span class="hljs-comment">//code excluded for brevity</span>
    });
</code></pre><p>Or better, simplify the syntax further by removing the “{} and return” since “getPromiseFunction” is a function that receives a number as param and returns a promise.</p><pre data-type="codeBlock" text="const getPromiseFunction = (seedNumber) =&gt; new Promise((resolve, reject) =&gt; {
    setTimeout(() =&gt; {
        const currentSeconds = new Date().getSeconds() + seedNumber;
        if (currentSeconds % 2 === 0) {
            resolve(&quot;I am the data from the API endpoint&quot;);
        }
        else {
            reject(&quot;I am an error, the API endpoint was down&quot;);
        }
    }, 2000)
});

const myPromise2 = getPromiseFunction(3)
    .then((data) =&gt; {
        console.log(data);
    }, (err) =&gt; {
        console.log(err);
    })
"><code>const getPromiseFunction <span class="hljs-operator">=</span> (seedNumber) <span class="hljs-operator">=</span><span class="hljs-operator">></span> <span class="hljs-keyword">new</span> Promise((resolve, reject) <span class="hljs-operator">=</span><span class="hljs-operator">></span> {
    setTimeout(() <span class="hljs-operator">=</span><span class="hljs-operator">></span> {
        const currentSeconds <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> Date().getSeconds() <span class="hljs-operator">+</span> seedNumber;
        <span class="hljs-keyword">if</span> (currentSeconds <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>) {
            resolve(<span class="hljs-string">"I am the data from the API endpoint"</span>);
        }
        <span class="hljs-keyword">else</span> {
            reject(<span class="hljs-string">"I am an error, the API endpoint was down"</span>);
        }
    }, <span class="hljs-number">2000</span>)
});

const myPromise2 <span class="hljs-operator">=</span> getPromiseFunction(<span class="hljs-number">3</span>)
    .then((data) <span class="hljs-operator">=</span><span class="hljs-operator">></span> {
        console.log(data);
    }, (err) <span class="hljs-operator">=</span><span class="hljs-operator">></span> {
        console.log(err);
    })
</code></pre><h3 id="h-using-promise-to-fetch-some-data-from-an-api" class="text-2xl font-header !mt-6 !mb-4 first:!mt-0 first:!mb-0">Using Promise to fetch some data from an API</h3><p>Now that we know what a promise is, we can use fetch API (which returns a promise) for making requests, instead of the low level &quot;XMLHttpRequest”.</p><p>In our requests.js I will add the following method:</p><pre data-type="codeBlock" text="const getCountryByCode = (code) =&gt; {
    const url = `https://restcountries.com/v3.1/alpha/${code}`;

    return fetch(url).then((response) =&gt; {
        if (response.status === 200) {
            return response.json();    // RETURNS ANOTHER PROMISE 
        } else {
            throw new Error(&quot;Unable to fetch country&quot;);
        }
    });
}
"><code>const getCountryByCode <span class="hljs-operator">=</span> (code) <span class="hljs-operator">=</span><span class="hljs-operator">></span> {
    const url <span class="hljs-operator">=</span> `https:<span class="hljs-comment">//restcountries.com/v3.1/alpha/${code}`;</span>

    <span class="hljs-keyword">return</span> fetch(url).then((response) <span class="hljs-operator">=</span><span class="hljs-operator">></span> {
        <span class="hljs-keyword">if</span> (response.status <span class="hljs-operator">=</span><span class="hljs-operator">=</span><span class="hljs-operator">=</span> <span class="hljs-number">200</span>) {
            <span class="hljs-keyword">return</span> response.json();    <span class="hljs-comment">// RETURNS ANOTHER PROMISE </span>
        } <span class="hljs-keyword">else</span> {
            <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">"Unable to fetch country"</span>);
        }
    });
}
</code></pre><p>And in our “app.js“ I can get the result by calling the method as such:</p><pre data-type="codeBlock" text="getCountryByCode(&quot;US&quot;).then((data) =&gt; {
    console.log(data);
}).catch((err) =&gt; {
    console.log(`Error: ${err}`);
})
"><code>getCountryByCode(<span class="hljs-string">"US"</span>).then((data) <span class="hljs-operator">=</span><span class="hljs-operator">></span> {
    console.log(data);
}).catch((err) <span class="hljs-operator">=</span><span class="hljs-operator">></span> {
    console.log(`<span class="hljs-built_in">Error</span>: ${err}`);
})
</code></pre><p>Now let’s break down the code.</p><p>Fetch returns a promise, so instead of doing “const getCountryByCode = (code) =&gt; new Promise()“ I can do directly “const getCountryByCode = (code) =&gt; fetch()“.</p><p>Going further, you can see that I already called “then” once on fetch. So instead of the promise returned by fetch I’m actually returning the promise returned by “response.json()”. This returns a promise with the response data. If something goes wrong I throw the error to be caught down the line.</p><figure float="none" data-type="figure" class="img-center" style="max-width: null;"><img src="https://storage.googleapis.com/papyrus_images/21123dd4201646a064cfbcc0a2eda17d1bffd1f11b59ed35a5359aed2a223c6e.png" alt="promise returned from &quot;response.json()&quot;" blurdataurl="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACwAAAAAAQABAAACAkQBADs=" nextheight="600" nextwidth="800" class="image-node embed"><figcaption HTMLAttributes="[object Object]" class="">promise returned from &quot;response.json()&quot;</figcaption></figure><p>Further, on the calling side I am calling “then” again on the response data promise in order to get the actual data from the response.</p><p>If any error occurs on any of the two “then“ (the one on “fetch” and the one on “getCountryByCode“) the attached “catch” will catch and log the error.</p><p>This is called chaining and is one of the biggest advantages that promises offer. Let’s further explore it.</p><h3 id="h-promise-chaining" class="text-2xl font-header !mt-6 !mb-4 first:!mt-0 first:!mb-0">Promise Chaining</h3><p>Going back to our first API call example where we used the callback pattern, imagine you have a scenario where you need to fetch a country code by its name, then from the result you use the country code to fetch it’s capital, and then you would use the capital to fetch it’s population. Using the callback pattern would result in a hard to read, hard to maintain and error prone multi-nested code that’s often referred to as “callback hell”. By returning a promise instead of nesting a callback function you achieve promise chaining and avoid this callback hell.</p><p>We will first look at an example of a square function returning a promise. The function squares a number and takes 1 second to execute (imagine it’s part of a different API and data has to be fetched). We will square the result three times:</p><pre data-type="codeBlock" text="const squareNumber = (num) =&gt; new Promise((resolve, reject) =&gt; {
    setTimeout(()=&gt;{
        typeof num === &quot;number&quot; ? resolve(num * num) : reject(&quot;Number not provided&quot;);
    }, 1000)
})
"><code>const squareNumber <span class="hljs-operator">=</span> (num) <span class="hljs-operator">=</span><span class="hljs-operator">></span> <span class="hljs-keyword">new</span> Promise((resolve, reject) <span class="hljs-operator">=</span><span class="hljs-operator">></span> {
    setTimeout(()<span class="hljs-operator">=</span><span class="hljs-operator">></span>{
        typeof num <span class="hljs-operator">=</span><span class="hljs-operator">=</span><span class="hljs-operator">=</span> <span class="hljs-string">"number"</span> ? resolve(num <span class="hljs-operator">*</span> num) : reject(<span class="hljs-string">"Number not provided"</span>);
    }, <span class="hljs-number">1000</span>)
})
</code></pre><p>This approach is close to the callback hell that you would be forced to do with callback pattern:</p><pre data-type="codeBlock" text="squareNumber(10).then((data) =&gt; {
    squareNumber(data).then((data) =&gt; {
        squareNumber(data).then((data) =&gt; {
            console.log(data);
        }, (err) =&gt; {
            console.log(err);
        })
    }, (err) =&gt; {
        console.log(err);
    })     
}, (err) =&gt; {
    console.log(err);
})
"><code>squareNumber(<span class="hljs-number">10</span>).then((data) <span class="hljs-operator">=</span><span class="hljs-operator">></span> {
    squareNumber(data).then((data) <span class="hljs-operator">=</span><span class="hljs-operator">></span> {
        squareNumber(data).then((data) <span class="hljs-operator">=</span><span class="hljs-operator">></span> {
            console.log(data);
        }, (err) <span class="hljs-operator">=</span><span class="hljs-operator">></span> {
            console.log(err);
        })
    }, (err) <span class="hljs-operator">=</span><span class="hljs-operator">></span> {
        console.log(err);
    })     
}, (err) <span class="hljs-operator">=</span><span class="hljs-operator">></span> {
    console.log(err);
})
</code></pre><p>But with promises instead of resolving on the spot with “then” we can choose to simply call the function and let it return the promise:</p><pre data-type="codeBlock" text="squareNumber(10).then((data) =&gt; {
    return squareNumber(data)
}).then((data) =&gt; {
    return squareNumber(data)
}).then((data) =&gt; {
    console.log(data);
}).catch((err) =&gt; {
    console.log(err)
})
"><code>squareNumber(<span class="hljs-number">10</span>).then((data) <span class="hljs-operator">=</span><span class="hljs-operator">></span> {
    <span class="hljs-keyword">return</span> squareNumber(data)
}).then((data) <span class="hljs-operator">=</span><span class="hljs-operator">></span> {
    <span class="hljs-keyword">return</span> squareNumber(data)
}).then((data) <span class="hljs-operator">=</span><span class="hljs-operator">></span> {
    console.log(data);
}).catch((err) <span class="hljs-operator">=</span><span class="hljs-operator">></span> {
    console.log(err)
})
</code></pre><figure float="none" data-type="figure" class="img-center" style="max-width: null;"><img src="https://storage.googleapis.com/papyrus_images/30864970a693f2cafcc1ec4e1a444706663a0da59b186aad861d215c0c65acea.png" alt="Promise Chaining (returning a promise from another promise)" blurdataurl="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACwAAAAAAQABAAACAkQBADs=" nextheight="600" nextwidth="800" class="image-node embed"><figcaption HTMLAttributes="[object Object]" class="">Promise Chaining (returning a promise from another promise)</figcaption></figure><p>Returning a promise from another promise it&apos;s called chaining.</p><p>Now let’s use a real world example. I will use the getCountryByCode defined earlier and also add a new request getCountriesByLanguage:</p><pre data-type="codeBlock" text="const getCountriesByLanguage = (language) =&gt; fetch(`https://restcountries.com/v3.1/lang/${language}`).then((response) =&gt; {
    if (response.status === 200) {
        return response.json();
    } else {
        throw new Error(&quot;Unable to fetch countries&quot;);
    }
})
"><code>const getCountriesByLanguage <span class="hljs-operator">=</span> (language) <span class="hljs-operator">=</span><span class="hljs-operator">></span> fetch(`https:<span class="hljs-comment">//restcountries.com/v3.1/lang/${language}`).then((response) => {</span>
    <span class="hljs-keyword">if</span> (response.status <span class="hljs-operator">=</span><span class="hljs-operator">=</span><span class="hljs-operator">=</span> <span class="hljs-number">200</span>) {
        <span class="hljs-keyword">return</span> response.json();
    } <span class="hljs-keyword">else</span> {
        <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">"Unable to fetch countries"</span>);
    }
})
</code></pre><p>Now I will chain the two calls together:</p><ul><li><p>first get a country by code, then search into the object and get the country’s first language</p></li><li><p>then use the language to get all countries that use the language fetched earlier as their first language.</p></li></ul><pre data-type="codeBlock" text="getCountryByCode(&quot;US&quot;).then((country) =&gt; {
    const language = Object.values(country[0].languages)[0];
    return getCountriesByLanguage(language);
}).then((countries) =&gt; {
    console.log(countries.map(i =&gt; i.name).map(i =&gt; i.official));
}).catch((err) =&gt; {
    console.log(`Error: ${err}`);
})
"><code>getCountryByCode(<span class="hljs-string">"US"</span>).then((country) <span class="hljs-operator">=</span><span class="hljs-operator">></span> {
    const language <span class="hljs-operator">=</span> Object.values(country[<span class="hljs-number">0</span>].languages)[<span class="hljs-number">0</span>];
    <span class="hljs-keyword">return</span> getCountriesByLanguage(language);
}).then((countries) <span class="hljs-operator">=</span><span class="hljs-operator">></span> {
    console.log(countries.map(i <span class="hljs-operator">=</span><span class="hljs-operator">></span> i.<span class="hljs-built_in">name</span>).map(i <span class="hljs-operator">=</span><span class="hljs-operator">></span> i.official));
}).catch((err) <span class="hljs-operator">=</span><span class="hljs-operator">></span> {
    console.log(`<span class="hljs-built_in">Error</span>: ${err}`);
})
</code></pre><h2 id="h-async-await" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">Async / Await</h2><p>.Net devs rejoice! Yet another feature borrowed from C#, which makes my life a lot easier in working with JavaScript!</p><p>Microsoft first introduced <code>async/await</code> pattern in C# 5.0 back in 2011-2012, and was adopted by several programming languages. And rightfully so because this was one of the greatest contributions to asynchronous programming.</p><p>Let’s explore how <code>async/await</code> builds on promises (Tasks in C#) and makes our code a whole lot easier to work with.</p><p>Below is a regular function that returns a string:</p><pre data-type="codeBlock" text="const someFunction = () =&gt; {
    return &quot;some text&quot;;
}

console.log(someFunction()); // prints: some text
"><code>const someFunction <span class="hljs-operator">=</span> () <span class="hljs-operator">=</span><span class="hljs-operator">></span> {
    <span class="hljs-keyword">return</span> <span class="hljs-string">"some text"</span>;
}

console.log(someFunction()); <span class="hljs-comment">// prints: some text</span>
</code></pre><p>and this is what happens when I make the function async:</p><pre data-type="codeBlock" text="const someFunctionAsync = async () =&gt; {
    return &quot;some other text&quot;;
}

console.log(someFunctionAsync()); // prints: Promise { &apos;some other text&apos; }
"><code>const someFunctionAsync <span class="hljs-operator">=</span> async () <span class="hljs-operator">=</span><span class="hljs-operator">></span> {
    <span class="hljs-keyword">return</span> <span class="hljs-string">"some other text"</span>;
}

console.log(someFunctionAsync()); <span class="hljs-comment">// prints: Promise { 'some other text' }</span>
</code></pre><p>It will make the function return a promise instead of the string itself</p><figure float="none" data-type="figure" class="img-center" style="max-width: null;"><img src="https://storage.googleapis.com/papyrus_images/6576dbec2a2df14f2c1f9fe416d0ad45b319955f231e44cdfce897f29f8e97f0.png" alt="async return" blurdataurl="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACwAAAAAAQABAAACAkQBADs=" nextheight="600" nextwidth="800" class="image-node embed"><figcaption HTMLAttributes="[object Object]" class="">async return</figcaption></figure><p>We can get the string by resolving the promise like we always do:</p><pre data-type="codeBlock" text="someFunctionAsync().then((data) =&gt;
    console.log(data)
).catch((err) =&gt; 
    console.log(err)
);
"><code>someFunctionAsync().then((data) <span class="hljs-operator">=</span><span class="hljs-operator">></span>
    console.log(data)
).catch((err) <span class="hljs-operator">=</span><span class="hljs-operator">></span> 
    console.log(err)
);
</code></pre><p>Now in order to demonstrate await, do you remember our squareNumber function that returned a promise? We will call that in our function again three times passing in the result and see how async/await compares to promise chaining:</p><pre data-type="codeBlock" text="const someOtherFunctionAsync = async () =&gt; {
    const firstSqare = await squareNumber(10);// no then no callback
    const secondSqare = await squareNumber(firstSqare);  
    const thirdSqare = await squareNumber(secondSqare);  

    return thirdSqare; // return the final promise
}

someOtherFunctionAsync().then((data) =&gt;
    console.log(data)
).catch((err) =&gt; 
    console.log(err)
);
"><code>const someOtherFunctionAsync <span class="hljs-operator">=</span> async () <span class="hljs-operator">=</span><span class="hljs-operator">></span> {
    const firstSqare <span class="hljs-operator">=</span> await squareNumber(<span class="hljs-number">10</span>);<span class="hljs-comment">// no then no callback</span>
    const secondSqare <span class="hljs-operator">=</span> await squareNumber(firstSqare);  
    const thirdSqare <span class="hljs-operator">=</span> await squareNumber(secondSqare);  

    <span class="hljs-keyword">return</span> thirdSqare; <span class="hljs-comment">// return the final promise</span>
}

someOtherFunctionAsync().then((data) <span class="hljs-operator">=</span><span class="hljs-operator">></span>
    console.log(data)
).catch((err) <span class="hljs-operator">=</span><span class="hljs-operator">></span> 
    console.log(err)
);
</code></pre><p>Remember the promise chaining we had to do before? Now, <code>async/await</code> makes our code look like regular synchronous code!</p><p>The second await will not run until the first await either resolves or rejects, the third await will not run until the second await either resolves or rejects and return will not run until all previous awaits either resolve or reject.</p><p>If any of the promise rejects, for example if we pass in a string instead of the number 10 in our squareNumber function, the promise is going to reject with: <code>reject(&quot;Number not provided&quot;);</code>that we coded in squareNumber.</p><p>Now in someOtherFunctionAsync, <strong>away will automatically throw that error further for us</strong>, so no need to manually throw the error by typing <code>throw new Error(&quot;error&quot;)</code></p><p>Converting our getCountryByCode function to async would look something along those lines:</p><pre data-type="codeBlock" text="const getCountryByCode = (code) =&gt; {
    return fetch(`https://restcountries.com/v3.1/alpha/${code}`).then((response) =&gt; {
        if (response.status === 200) {
            return response.json();    // RETURNS ANOTHER PROMISE
        } else {
            throw new Error(&quot;Unable to fetch country&quot;);
        }
    });
}

const getCountryByCodeAsync = async (code) =&gt; {
    const response = await fetch(`https://restcountries.com/v3.1/alpha/${code}`); // await
    
    if (response.status === 200) {
        return response.json();    // await here if you want to return something inside the response
    } else {
        throw new Error(&quot;Unable to fetch country&quot;);
    }
}
"><code>const getCountryByCode <span class="hljs-operator">=</span> (code) <span class="hljs-operator">=</span><span class="hljs-operator">></span> {
    <span class="hljs-keyword">return</span> fetch(`https:<span class="hljs-comment">//restcountries.com/v3.1/alpha/${code}`).then((response) => {</span>
        <span class="hljs-keyword">if</span> (response.status <span class="hljs-operator">=</span><span class="hljs-operator">=</span><span class="hljs-operator">=</span> <span class="hljs-number">200</span>) {
            <span class="hljs-keyword">return</span> response.json();    <span class="hljs-comment">// RETURNS ANOTHER PROMISE</span>
        } <span class="hljs-keyword">else</span> {
            <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">"Unable to fetch country"</span>);
        }
    });
}

const getCountryByCodeAsync <span class="hljs-operator">=</span> async (code) <span class="hljs-operator">=</span><span class="hljs-operator">></span> {
    const response <span class="hljs-operator">=</span> await fetch(`https:<span class="hljs-comment">//restcountries.com/v3.1/alpha/${code}`); // await</span>
    
    <span class="hljs-keyword">if</span> (response.status <span class="hljs-operator">=</span><span class="hljs-operator">=</span><span class="hljs-operator">=</span> <span class="hljs-number">200</span>) {
        <span class="hljs-keyword">return</span> response.json();    <span class="hljs-comment">// await here if you want to return something inside the response</span>
    } <span class="hljs-keyword">else</span> {
        <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">"Unable to fetch country"</span>);
    }
}
</code></pre><p>I also converted the getCountriesByLanguage to async, now if I want to make a function that will chain the two calls together like we did above using the promise version, it would look something like this:</p><pre data-type="codeBlock" text="const getCountriesByLanguageUsingCountryCodeAsync = async (code) =&gt; {
    const country = await getCountryByCodeAsync(code);
    const countryLanguage = Object.values(country[0].languages)[0];
    const allCountriesUsingLanguage = await getCountriesByLanguageAsync(countryLanguage);

    return allCountriesUsingLanguage.map(i =&gt; i.name).map(i =&gt; i.official);
}

getCountriesByLanguageUsingCountryCodeAsync(&quot;FR&quot;).then((data) =&gt; {
    console.log(data);
}).catch((err) =&gt; {
    console.log(`Error: ${err}`);
})
"><code>const getCountriesByLanguageUsingCountryCodeAsync <span class="hljs-operator">=</span> async (code) <span class="hljs-operator">=</span><span class="hljs-operator">></span> {
    const country <span class="hljs-operator">=</span> await getCountryByCodeAsync(code);
    const countryLanguage <span class="hljs-operator">=</span> Object.values(country[<span class="hljs-number">0</span>].languages)[<span class="hljs-number">0</span>];
    const allCountriesUsingLanguage <span class="hljs-operator">=</span> await getCountriesByLanguageAsync(countryLanguage);

    <span class="hljs-keyword">return</span> allCountriesUsingLanguage.map(i <span class="hljs-operator">=</span><span class="hljs-operator">></span> i.<span class="hljs-built_in">name</span>).map(i <span class="hljs-operator">=</span><span class="hljs-operator">></span> i.official);
}

getCountriesByLanguageUsingCountryCodeAsync(<span class="hljs-string">"FR"</span>).then((data) <span class="hljs-operator">=</span><span class="hljs-operator">></span> {
    console.log(data);
}).catch((err) <span class="hljs-operator">=</span><span class="hljs-operator">></span> {
    console.log(`<span class="hljs-built_in">Error</span>: ${err}`);
})
</code></pre><figure float="none" data-type="figure" class="img-center" style="max-width: null;"><img src="https://storage.googleapis.com/papyrus_images/5d3495d0588d3cf1b7d70d85792361d0df4b569cf5b113955941ab07e2eeb2cc.png" alt="FR code -&gt; French Language -&gt; All countries using French as their official language" blurdataurl="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACwAAAAAAQABAAACAkQBADs=" nextheight="600" nextwidth="800" class="image-node embed"><figcaption HTMLAttributes="[object Object]" class="">FR code -&gt; French Language -&gt; All countries using French as their official language</figcaption></figure><p>So there you have it. This part may have been a bit lengthy, but there are numerous nuances to consider, making it an important subject so I wanted to cover the basics. In the future it would be interesting to go more in depth and explore things like the differences between JavaScript&apos;s Promises and C#&apos;s Tasks, using side-by-side code examples in both languages.</p><h3 id="h-lets-connect" class="text-2xl font-header !mt-6 !mb-4 first:!mt-0 first:!mb-0">Let’s connect:</h3><p>You can find the full set of examples over at my <a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://github.com/razvanpiticas/js-primer">github</a> page.</p><p>Also if you liked the article, I&apos;m constantly tweeting about this stuff and more. Feel free to follow me on <a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://twitter.com/QuantArcane">Twitter</a> and drop a comment to say hi!</p>]]></content:encoded>
            <author>quantarcane@newsletter.paragraph.com (QuantArcane)</author>
            <enclosure url="https://storage.googleapis.com/papyrus_images/9e21277a06deeaa356cc1d8e3a9e382e4655706f5bd3dc4dac3ac364a706a455.png" length="0" type="image/png"/>
        </item>
        <item>
            <title><![CDATA[II. JavaScript Object Oriented Programming - A Fast Track Guide for C#/Java/... devs]]></title>
            <link>https://paragraph.com/@quantarcane/ii-javascript-object-oriented-programming-a-fast-track-guide-for-c-java-devs</link>
            <guid>dGeTjKdcoVqzL9rxPoe2</guid>
            <pubDate>Sat, 15 Jul 2023 05:49:31 GMT</pubDate>
            <description><![CDATA[This article is the second part of a three-part series exploring JavaScript from the perspective of a .NET developer. In this installment, I will delve into JavaScript&apos;s prototypal inheritance, the distinction between primitives and objects, and the syntactic evolution of object-oriented programming concepts. If you wish to start from the beginning, please navigate to Part I.Literal Object syntaxA weird json like syntax way of defining an object on the fly:const wallet = { address: "0x12...]]></description>
            <content:encoded><![CDATA[<p>This article is the second part of a three-part series exploring JavaScript from the perspective of a .NET developer. In this installment, I will delve into JavaScript&apos;s prototypal inheritance, the distinction between primitives and objects, and the syntactic evolution of object-oriented programming concepts.</p><p>If you wish to start from the beginning, please navigate to <a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://mirror.xyz/quantarcane.eth/3XMZRHJIMX7tEwYt2ZOyN9iOuyzji97HZMeVXNCXeoQ">Part I</a>.</p><h2 id="h-literal-object-syntax" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">Literal Object syntax</h2><p>A weird json like syntax way of defining an object on the fly:</p><pre data-type="codeBlock" text="const wallet = {
    address: &quot;0x123&quot;,
    balance: 10101010,
    getOwner() { return this.address; }
}

const owner = wallet.getOwner();
console.log(owner);                   // 0x123
"><code>const wallet <span class="hljs-operator">=</span> {
    <span class="hljs-keyword">address</span>: <span class="hljs-string">"0x123"</span>,
    balance: <span class="hljs-number">10101010</span>,
    getOwner() { <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.<span class="hljs-built_in">address</span>; }
}

const owner <span class="hljs-operator">=</span> wallet.getOwner();
console.log(owner);                   <span class="hljs-comment">// 0x123</span>
</code></pre><p>wallet is a reference like in C#. It has the same shallow copy behavior, same for passing it in functions as well.</p><p>Literal declaration is a fast way of bundling some data together, but what if you need a second wallet object?</p><h2 id="h-constructor-function-syntax" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">Constructor Function syntax</h2><p>A regular function can act as a constructor, without being declared inside a class. WHAT?</p><pre data-type="codeBlock" text="const Wallet = function(address, balance){
    this.address = address;
    this.balance = balance;
}
"><code>const Wallet <span class="hljs-operator">=</span> <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"><span class="hljs-keyword">address</span>, balance</span>)</span>{
    <span class="hljs-built_in">this</span>.<span class="hljs-built_in">address</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">address</span>;
    <span class="hljs-built_in">this</span>.<span class="hljs-built_in">balance</span> <span class="hljs-operator">=</span> balance;
}
</code></pre><p>“new“ serves the same scope as in C#: allocates memory, initializes the object and returns a reference to it.</p><pre data-type="codeBlock" text="const wallet1 = new Wallet(&quot;0x123&quot;, 101010);
console.log(wallet1);

const wallet2 = new Wallet(&quot;0x456&quot;, 100100);
console.log(wallet2);

wallet2.balance += 100;        // set prop
console.log(wallet2.balance);  // get prop
"><code>const wallet1 <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> Wallet(<span class="hljs-string">"0x123"</span>, <span class="hljs-number">101010</span>);
console.log(wallet1);

const wallet2 <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> Wallet(<span class="hljs-string">"0x456"</span>, <span class="hljs-number">100100</span>);
console.log(wallet2);

wallet2.<span class="hljs-built_in">balance</span> <span class="hljs-operator">+</span><span class="hljs-operator">=</span> <span class="hljs-number">100</span>;        <span class="hljs-comment">// set prop</span>
console.log(wallet2.<span class="hljs-built_in">balance</span>);  <span class="hljs-comment">// get prop</span>
</code></pre><p>Now what if I want to add a method to our object?</p><h3 id="h-prototypal-inheritance" class="text-2xl font-header !mt-6 !mb-4 first:!mt-0 first:!mb-0"><a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://javascript.info/prototype-inheritance">Prototypal</a> Inheritance</h3><p>Since we don&apos;t have a class to add methods to, we will use JavaScript&apos;s prototypal Inheritance.</p><pre data-type="codeBlock" text="Wallet.prototype.getOwner = function () {
    return this.address; 
}

Wallet.prototype.setBalance = function (balance) { 
    this.balance = balance;
}

console.log(wallet1.getOwner());    // 0x123
console.log(wallet2.getOwner());    // 0x456

wallet1.setBalance(200000);
console.log(wallet1.balance);        // 200000
}
"><code>Wallet.prototype.getOwner <span class="hljs-operator">=</span> <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.<span class="hljs-built_in">address</span>; 
}

Wallet.prototype.setBalance <span class="hljs-operator">=</span> <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">balance</span>) </span>{ 
    <span class="hljs-built_in">this</span>.<span class="hljs-built_in">balance</span> <span class="hljs-operator">=</span> balance;
}

console.log(wallet1.getOwner());    <span class="hljs-comment">// 0x123</span>
console.log(wallet2.getOwner());    <span class="hljs-comment">// 0x456</span>

wallet1.setBalance(<span class="hljs-number">200000</span>);
console.log(wallet1.<span class="hljs-built_in">balance</span>);        <span class="hljs-comment">// 200000</span>
}
</code></pre><p><em>It’s worth mentioning that you can’t use the arrow function here since arrow functions don&apos;t bind &quot;this&quot;, so you won’t have access to the object from within.</em></p><p>The <strong>prototype property</strong> is an object where we can add methods / properties on the fly (even after instances are created) that we want to be shared across all Wallet instances.</p><figure float="none" data-type="figure" class="img-center" style="max-width: null;"><img src="https://storage.googleapis.com/papyrus_images/fc3050513fa531b957029b4bf7dcc1fdab6caa8823bceb03a6f0849db78207ac.png" alt="Prototypal Inheritance" blurdataurl="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACwAAAAAAQABAAACAkQBADs=" nextheight="600" nextwidth="800" class="image-node embed"><figcaption HTMLAttributes="[object Object]" class="">Prototypal Inheritance</figcaption></figure><pre data-type="codeBlock" text="const wallet3 = new Wallet(&quot;0x789&quot;, 303030);
// wallet3.[[prototype]] = Wallet.prototype
"><code>const wallet3 = new Wallet(<span class="hljs-string">"0x789"</span>, <span class="hljs-number">303030</span>);
// wallet3.<span class="hljs-string">[[prototype]]</span> = Wallet.prototype
</code></pre><p>wallet3.[[prototype]] automatically gets a reference to Wallet.prototype.</p><p>When calling a property / method on an object JavaScript first checks if that property is part of the instance, If it can’t find it it will search for it up the inheritance chain using the [[prototype]] property.</p><pre data-type="codeBlock" text="console.log(wallet3.balance);
"><code>console.log(wallet3.<span class="hljs-built_in">balance</span>);
</code></pre><p>Here JS searches for balance property on wallet3. It finds it and gets it.</p><pre data-type="codeBlock" text="console.log(wallet3.getOwner());              
"><code>console.log(wallet3.getOwner());              
</code></pre><p>Again, here JS searches for getOwner method on wallet3. It cannot find it so it uses wallet3.[[prototype]] reference to go up the prototype chain and find the method at wallet3.[[prototype]].getOwner().</p><p>Another difference worth mentioning is that JS allows us to “on the fly“ override a property/method directly on an instance (shadowing):</p><pre data-type="codeBlock" text="wallet2.getOwner = function() {return &quot;The owner is secret&quot;; }
console.log(wallet1.getOwner());      // 0x123 
console.log(wallet2.getOwner());      // 0x456
console.log(wallet3.getOwner());      // 0x789 
"><code>wallet2.getOwner <span class="hljs-operator">=</span> <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{<span class="hljs-keyword">return</span> <span class="hljs-string">"The owner is secret"</span>; }
console.log(wallet1.getOwner());      <span class="hljs-comment">// 0x123 </span>
console.log(wallet2.getOwner());      <span class="hljs-comment">// 0x456</span>
console.log(wallet3.getOwner());      <span class="hljs-comment">// 0x789 </span>
</code></pre><h3 id="h-primitives-vs-objects-and-the-prototype-chain" class="text-2xl font-header !mt-6 !mb-4 first:!mt-0 first:!mb-0">Primitives vs Objects &amp; The Prototype Chain</h3><p>It&apos;s funny; the last time I checked JavaScript about 7 years ago, the prevailing notion was that everything in JavaScript is a function. However, now I&apos;m hearing that everything is an object.</p><p>JS has 5 primitive types (like in Java not .NET which does not have primitives, only value types). <strong>Those 5 primitives are:</strong> <strong>string, number, boolean, null and undefined</strong>. <strong>Everything else is an object.</strong></p><pre data-type="codeBlock" text="const flag = true;
console.log(flag); 

const age = 35;
console.log(age); 

const book = &quot;The Art of War&quot;;
console.log(book); 
"><code>const <span class="hljs-attr">flag</span> = <span class="hljs-literal">true</span><span class="hljs-comment">;</span>
console.log(flag)<span class="hljs-comment">; </span>

const <span class="hljs-attr">age</span> = <span class="hljs-number">35</span><span class="hljs-comment">;</span>
console.log(age)<span class="hljs-comment">; </span>

const <span class="hljs-attr">book</span> = <span class="hljs-string">"The Art of War"</span><span class="hljs-comment">;</span>
console.log(book)<span class="hljs-comment">; </span>
</code></pre><p>will print in the console:</p><figure float="none" data-type="figure" class="img-center" style="max-width: null;"><img src="https://storage.googleapis.com/papyrus_images/1a7c12e4aa3ec2c1cf2b1e7ac569784f13099b0d4759ad55d9e074a74cca77d9.png" alt="Primitives in the console" blurdataurl="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACwAAAAAAQABAAACAkQBADs=" nextheight="600" nextwidth="800" class="image-node embed"><figcaption HTMLAttributes="[object Object]" class="">Primitives in the console</figcaption></figure><p>From the first 5 primitives outlined above only null and undefined will ever be a primitive. The first three are initially primitives as seen in the console, but if needed JS will wrap an object around them. That’s why if I try to call methods on any of them (string, boolean, number) I can.</p><pre data-type="codeBlock" text="console.log(book.split(&apos;&apos;));
"><code>console.log(book.split(<span class="hljs-string">''</span>));
</code></pre><p>will print in the console:</p><figure float="none" data-type="figure" class="img-center" style="max-width: null;"><img src="https://storage.googleapis.com/papyrus_images/1c52f4e68cfef018bbb0f46846fc5198baedfe3cc7b022c7d1bfb70c842da793.png" alt="Objects in the console" blurdataurl="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACwAAAAAAQABAAACAkQBADs=" nextheight="600" nextwidth="800" class="image-node embed"><figcaption HTMLAttributes="[object Object]" class="">Objects in the console</figcaption></figure><p>As we can see JS turned our primitive string into an object that inherits from an array of characters prototype, that further inherits from the Object prototype.</p><p>As all value types and reference types inherit from Object in C#, <strong>In JavaScript all objects inherit from Object prototype.</strong></p><p>Here is the prototypal inheritance chain for different types in JS:</p><ul><li><p>Object: myObject &gt; Object.prototype &gt; null</p></li><li><p>Number: myNumber &gt; Number.prototype &gt; Object.prototype &gt; null</p></li><li><p>Boolean: myBool &gt; Boolean.prototype &gt; Object.prototype &gt; null</p></li><li><p>String: myString &gt; String.prototype &gt; Object.prototype &gt; null</p></li><li><p>Array: myArray &gt; Array.prototype &gt; Object.prototype &gt; null</p></li><li><p>Function: myFunction &gt; Function.prototype &gt; Object.prototype &gt; null</p></li></ul><p>You can further explore the inheritance chain and all the properties by creating an object of some type and just dumping it to the console.</p><h2 id="h-class-syntax" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">Class syntax</h2><p>And finally a familiar syntax. Using classes:</p><pre data-type="codeBlock" text="class Wallet {

    // clean differentiation from regular functions via constructor keyword &lt;3
    constructor(address, balance){
        this.address = address;
        this._balance = balance;
    }

    // methods defined within the class, not all over the place &lt;3
    // using that useless &quot;function&quot; keyword in here would actually crash the program. &lt;3
    getOwner() { 
        return this.address; 
    }

    addToBalance(value) { 
        this._balance += value;
    }

    // encapsulation through getters and setters &lt;3. (although we could do w/o the parenthesis)
    get balance(){
        return this._balance;
    }

    set balance(value){
        if(value &gt;= 0){
            this._balance = value;
        }
    }
}

const wallet1 = new Wallet(&quot;0x123&quot;, 101010);
console.log(wallet1);
"><code>class Wallet {

    <span class="hljs-comment">// clean differentiation from regular functions via constructor keyword &#x3C;3</span>
    <span class="hljs-function"><span class="hljs-keyword">constructor</span>(<span class="hljs-params"><span class="hljs-keyword">address</span>, balance</span>)</span>{
        <span class="hljs-built_in">this</span>.<span class="hljs-built_in">address</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">address</span>;
        <span class="hljs-built_in">this</span>._balance <span class="hljs-operator">=</span> balance;
    }

    <span class="hljs-comment">// methods defined within the class, not all over the place &#x3C;3</span>
    <span class="hljs-comment">// using that useless "function" keyword in here would actually crash the program. &#x3C;3</span>
    getOwner() { 
        <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>.<span class="hljs-built_in">address</span>; 
    }

    addToBalance(value) { 
        <span class="hljs-built_in">this</span>._balance <span class="hljs-operator">+</span><span class="hljs-operator">=</span> value;
    }

    <span class="hljs-comment">// encapsulation through getters and setters &#x3C;3. (although we could do w/o the parenthesis)</span>
    get balance(){
        <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>._balance;
    }

    set balance(value){
        <span class="hljs-keyword">if</span>(value <span class="hljs-operator">></span><span class="hljs-operator">=</span> <span class="hljs-number">0</span>){
            <span class="hljs-built_in">this</span>._balance <span class="hljs-operator">=</span> value;
        }
    }
}

const wallet1 <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> Wallet(<span class="hljs-string">"0x123"</span>, <span class="hljs-number">101010</span>);
console.log(wallet1);
</code></pre><h3 id="h-inheritance-and-polymorphism" class="text-2xl font-header !mt-6 !mb-4 first:!mt-0 first:!mb-0">Inheritance &amp; Polymorphism</h3><pre data-type="codeBlock" text="class MultiSigWallet extends Wallet { // extends like in java
    constructor(address, secondAddress, balance){
        super(address, balance);      // super like in java

        this.secondAddress = secondAddress;
    }

    // method override in subclass just like in C#/Java
    getOwner(){ return `first address: ${this.address} &amp; second address: ${this.secondAddress}`; }

}

const w = new Wallet(&quot;0x123&quot;, 101010);
console.log(w);
w.addToBalance = 5000;          // method from Wallet
console.log(w.getOwner());      // method from Wallet

const msw = new MultiSigWallet(&quot;0x456&quot;, &quot;0x789&quot;, 9999999);
console.log(msw);
w.addToBalance = 6000;          // method from Wallet (no override on MultiSigWallet)
console.log(msw.getOwner());    // method from MultiSigWallet
"><code>class MultiSigWallet extends Wallet { <span class="hljs-comment">// extends like in java</span>
    <span class="hljs-function"><span class="hljs-keyword">constructor</span>(<span class="hljs-params"><span class="hljs-keyword">address</span>, secondAddress, balance</span>)</span>{
        <span class="hljs-built_in">super</span>(<span class="hljs-keyword">address</span>, balance);      <span class="hljs-comment">// super like in java</span>

        <span class="hljs-built_in">this</span>.secondAddress <span class="hljs-operator">=</span> secondAddress;
    }

    <span class="hljs-comment">// method override in subclass just like in C#/Java</span>
    getOwner(){ <span class="hljs-keyword">return</span> `first <span class="hljs-keyword">address</span>: ${<span class="hljs-built_in">this</span>.<span class="hljs-built_in">address</span>} <span class="hljs-operator">&#x26;</span> second <span class="hljs-keyword">address</span>: ${<span class="hljs-built_in">this</span>.secondAddress}`; }

}

const w <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> Wallet(<span class="hljs-string">"0x123"</span>, <span class="hljs-number">101010</span>);
console.log(w);
w.addToBalance <span class="hljs-operator">=</span> <span class="hljs-number">5000</span>;          <span class="hljs-comment">// method from Wallet</span>
console.log(w.getOwner());      <span class="hljs-comment">// method from Wallet</span>

const msw <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> MultiSigWallet(<span class="hljs-string">"0x456"</span>, <span class="hljs-string">"0x789"</span>, <span class="hljs-number">9999999</span>);
console.log(msw);
w.addToBalance <span class="hljs-operator">=</span> <span class="hljs-number">6000</span>;          <span class="hljs-comment">// method from Wallet (no override on MultiSigWallet)</span>
console.log(msw.getOwner());    <span class="hljs-comment">// method from MultiSigWallet</span>
</code></pre><p>So there you have it.</p><p>In conclusion I am amazed by how strongly JavaScript has developed a syntactic resemblance to C# and Java. It almost feels as though the evolution of JS was influenced by Microsoft developers.</p><p>However, it&apos;s important to remember that this resemblance is primarily syntactic sugar, as the underlying functionality remains the same.JS still allows you to mess with the properties and methods of an object even after it has been created through the [[Prototype]] object.</p><p>Navigate to part three of this three part series where we explore Asynchronous Programming in JavaScript: <a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://mirror.xyz/quantarcane.eth/fyMW6ZXkJ1AA3FN42TU522_YR5gh_QyyvMZev84Tshg">Part III</a></p><h3 id="h-lets-connect" class="text-2xl font-header !mt-6 !mb-4 first:!mt-0 first:!mb-0">Let’s connect:</h3><p>You can find the full set of examples over at my <a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://github.com/razvanpiticas/js-primer">github</a> page.</p><p>Also if you liked the article, I&apos;m constantly tweeting about this stuff and more. Feel free to follow me on <a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://twitter.com/QuantArcane">Twitter</a> and drop a comment to say hi!</p>]]></content:encoded>
            <author>quantarcane@newsletter.paragraph.com (QuantArcane)</author>
            <enclosure url="https://storage.googleapis.com/papyrus_images/636f04b557ac3df7eef6bcc5a7d03d3b554c901857e3770a49be6bc225dcb5ba.png" length="0" type="image/png"/>
        </item>
        <item>
            <title><![CDATA[I. JavaScript General Syntax - A Fast Track Guide for C#/Java/... devs]]></title>
            <link>https://paragraph.com/@quantarcane/i-javascript-general-syntax-a-fast-track-guide-for-c-java-devs</link>
            <guid>L6cUKQTmJyBIv1H5YYUo</guid>
            <pubDate>Thu, 13 Jul 2023 13:50:32 GMT</pubDate>
            <description><![CDATA[Hello coders. I’m a long time .NET developer who recently started playing with Solidity at Alchemy’s Web3 Dev Bootcamp. About halfway into the bootcamp I had an epiphany about what my final project should be. Since React is the de facto front-end library/framework in the blockchain industry I decided to use it for my app. Also throughout my (mostly backed) career I did work on a couple of Angular-Typescript projects but never got a chance to work with React. So, in order to not feel like a fr...]]></description>
            <content:encoded><![CDATA[<p>Hello coders. I’m a long time .NET developer who recently started playing with Solidity at <a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://university.alchemy.com/">Alchemy’s Web3 Dev Bootcamp</a>. About halfway into the bootcamp I had an epiphany about what my final project should be.</p><p>Since React is the de facto front-end library/framework in the blockchain industry I decided to use it for my app. Also throughout my (mostly backed) career I did work on a couple of Angular-Typescript projects but never got a chance to work with React.</p><p>So, in order to not feel like a fraud for jumping straight into React without properly going through JavaScript first, I took yet another step back and did a quick 30-hour tutorial: <a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://www.udemy.com/course/modern-javascript/">The Modern JavaScript Bootcamp</a> by Andrew Mean. By the way, I want to give a big shout-out to Andrew for the great content!</p><p>Since I did something similar about 7 years ago before working with TypeScript and Angular, this time I decided I will create a small set of cheat sheet articles that can be reviewed in 20-30 minutes at most.</p><p>This way I will have a reference point to come back to in the future and hopefully save some time for other object-oriented programmers out there.</p><p>I plan to split this in three articles: The first one is going to be about general JS syntactic concepts, The second one about OOP in JS, and the third about Asynchronous JS.</p><p>In the future I might expand the set with more in-depth articles on subjects like Webpack or delve into Web Assembly, but at this point I feel I’m getting too derailed from my goal of obtaining the Alchemy NFT Certification.</p><p>Enough context let’s get started.</p><h2 id="h-variables-and-scopinglexicalstatic" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">Variables &amp; Scoping(Lexical/Static)</h2><pre data-type="codeBlock" text="const { keccak256 } = require(&quot;ethereum-cryptography/keccak&quot;);
const { utf8ToBytes } = require(&quot;ethereum-cryptography/utils&quot;);

const message = &quot;JS uses lexical scoping&quot;;

const hashMessage = function(msg){

    if(msg.length &lt; 30)
    {
        const message = &quot; shadowing: defining a variable with the same name but in a different scope&quot;;
        msg += message;
    }

    const bytes = utf8ToBytes(msg);
    const hash = keccak256(bytes);

    return hash;
}

console.log(hashMessage(message));

// Global Scope (message, hashMessage)
    // Local Scope (msg, bytes, hash)
        // Local Scope (message)
        
"><code>const { <span class="hljs-built_in">keccak256</span> } <span class="hljs-operator">=</span> <span class="hljs-built_in">require</span>(<span class="hljs-string">"ethereum-cryptography/keccak"</span>);
const { utf8ToBytes } <span class="hljs-operator">=</span> <span class="hljs-built_in">require</span>(<span class="hljs-string">"ethereum-cryptography/utils"</span>);

const message <span class="hljs-operator">=</span> <span class="hljs-string">"JS uses lexical scoping"</span>;

const hashMessage <span class="hljs-operator">=</span> <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"><span class="hljs-built_in">msg</span></span>)</span>{

    <span class="hljs-keyword">if</span>(<span class="hljs-built_in">msg</span>.length <span class="hljs-operator">&#x3C;</span> <span class="hljs-number">30</span>)
    {
        const message <span class="hljs-operator">=</span> <span class="hljs-string">" shadowing: defining a variable with the same name but in a different scope"</span>;
        <span class="hljs-built_in">msg</span> <span class="hljs-operator">+</span><span class="hljs-operator">=</span> message;
    }

    const <span class="hljs-keyword">bytes</span> <span class="hljs-operator">=</span> utf8ToBytes(<span class="hljs-built_in">msg</span>);
    const hash <span class="hljs-operator">=</span> <span class="hljs-built_in">keccak256</span>(<span class="hljs-keyword">bytes</span>);

    <span class="hljs-keyword">return</span> hash;
}

console.log(hashMessage(message));

<span class="hljs-comment">// Global Scope (message, hashMessage)</span>
    <span class="hljs-comment">// Local Scope (msg, bytes, hash)</span>
        <span class="hljs-comment">// Local Scope (message)</span>
        
</code></pre><p>The nested scope from the if block (where the second “message” variable is defined) has access to all the above scopes. So it can access the local scope variables: msg, bytes, hash, as well as the global scope vars “message “ and “hashMessage”.</p><h3 id="h-leaked-globals-and-use-strict" class="text-2xl font-header !mt-6 !mb-4 first:!mt-0 first:!mb-0">Leaked Globals &amp; &apos;use strict&apos;</h3><p>If JS can&apos;t find the variable in its scope it will keep going up until global. If it reaches global and the variable is NOT defined, it will auto define it! Because why not... :|</p><p>To fix this mayhem causing &quot;feature&quot; Js has something called &quot;strict mode&quot;. (Add &quot;use strict&quot; on top of your script files) More on this here <a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode</a></p><h3 id="h-shadowing" class="text-2xl font-header !mt-6 !mb-4 first:!mt-0 first:!mb-0">Shadowing</h3><p>It&apos;s ok to define a second variable with the same name, e.g. the &quot;message&quot; variable inside the if block, if it’s not in the same scope as the first “message” variable (from global scope), and it will shadow if.</p><h3 id="h-undefined-vs-null" class="text-2xl font-header !mt-6 !mb-4 first:!mt-0 first:!mb-0">Undefined vs Null</h3><ul><li><p>Undefined comes from uninitialized, declared variables.</p></li><li><p>Or from assigning a void function result to a variable</p></li><li><p>Or by not passing a parameter into a function</p></li></ul><p>I can check against it:</p><pre data-type="codeBlock" text="if (x === undefined)  
"><code><span class="hljs-keyword">if</span> (x <span class="hljs-operator">=</span><span class="hljs-operator">=</span><span class="hljs-operator">=</span> undefined)  
</code></pre><p>And I can manually assign undefined to clear a value, but for that &quot;null&quot; should be used!</p><h3 id="h-let-and-const-vs-obsoletevar" class="text-2xl font-header !mt-6 !mb-4 first:!mt-0 first:!mb-0">let &amp; const vs (obsolete)var</h3><ul><li><p>&quot;let&quot; is block scoped</p></li><li><p>&quot;const&quot; is like in C# (on a ref type you can&apos;t change the address but you can change the object&apos;s content)</p></li><li><p>&quot;var&quot; has several issues:</p><ul><li><p>is function scoped (a var declared in an &quot;if&quot; block is accessible outside the &quot;if&quot; block provided is in the same function.</p></li><li><p>you can redeclare the same variable multiple times :|</p></li><li><p>var declaration (not assignment) gets hoisted above. So if using a var variable before declaration you get undefined instead of the natural reference error. Plus all sorts of weird stuff can happen due to the vars hoisting.</p></li></ul></li></ul><p><em>I’ll be addressing </em><strong><em>value types vs reference types</em></strong><em> in my next guide about OOP in JS.</em></p><h2 id="h-string-interpolation" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">String Interpolation</h2><pre data-type="codeBlock" text="const str = ´Lorem Ipsum ${varLoremHere} Ipsum´;  
"><code>const <span class="hljs-attr">str</span> = ´Lorem Ipsum <span class="hljs-variable">${varLoremHere}</span> Ipsum´<span class="hljs-comment">;  </span>
</code></pre><p>Great, now I have to make room for the backtick key on my Dygma keyboard and mess my perfect setup. Arghhh!</p><h2 id="h-type-coercion-truthy-and-falsy-aaand-no-im-not-being-funny-those-are-actually-technical-words" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">Type Coercion - Truthy &amp; Falsy (aaand no I&apos;m not being funny, those are actually technical words)</h2><p>So apparently if you do:</p><pre data-type="codeBlock" text="if(&quot;some string&quot;)  // true 
"><code><span class="hljs-built_in">if</span>("some string")  <span class="hljs-comment">// true </span>
</code></pre><p>Js is going to default the string to the &quot;true&quot; boolean value. Resembling ChatGPT, if you don&apos;t know just make something up!</p><p>Js will resolve: <strong>(false, 0, empty string, null, undefined, NaN)</strong> to <strong>falsy. Everything else</strong> will be resolved to <strong>truthy</strong> (arrays, objects, a monkey with a chainsaw)!</p><h3 id="h-type-coercion-resolve-to-a-string-number-or-bool" class="text-2xl font-header !mt-6 !mb-4 first:!mt-0 first:!mb-0">Type Coercion (resolve to a string, number or bool)</h3><pre data-type="codeBlock" text="console.log(&apos;5&apos; + 5);         // 55
console.log(&apos;5&apos; - 5);         // 0
console.log(&apos;5&apos; === 5);       // false (the third equal is for comparing the types)
console.log(&apos;5&apos; == 5);        // true (can&apos;t think of a scenario where == should be used...)
console.log(true + 12);       // 13

const type = typeof 123       // check the type using typeof
console.log(type)             // number
"><code>console.log(<span class="hljs-string">'5'</span> <span class="hljs-operator">+</span> <span class="hljs-number">5</span>);         <span class="hljs-comment">// 55</span>
console.log(<span class="hljs-string">'5'</span> <span class="hljs-operator">-</span> <span class="hljs-number">5</span>);         <span class="hljs-comment">// 0</span>
console.log(<span class="hljs-string">'5'</span> <span class="hljs-operator">=</span><span class="hljs-operator">=</span><span class="hljs-operator">=</span> <span class="hljs-number">5</span>);       <span class="hljs-comment">// false (the third equal is for comparing the types)</span>
console.log(<span class="hljs-string">'5'</span> <span class="hljs-operator">=</span><span class="hljs-operator">=</span> <span class="hljs-number">5</span>);        <span class="hljs-comment">// true (can't think of a scenario where == should be used...)</span>
console.log(<span class="hljs-literal">true</span> <span class="hljs-operator">+</span> <span class="hljs-number">12</span>);       <span class="hljs-comment">// 13</span>

const <span class="hljs-keyword">type</span> <span class="hljs-operator">=</span> typeof <span class="hljs-number">123</span>       <span class="hljs-comment">// check the type using typeof</span>
console.log(<span class="hljs-keyword">type</span>)             <span class="hljs-comment">// number</span>
</code></pre><p>More on type coercion here: <a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://github.com/getify/You-Dont-Know-JS/blob/2nd-ed/types-grammar/ch4.md">https://github.com/getify/You-Dont-Know-JS/blob/2nd-ed/types-grammar/ch4.md</a> (Funny I stumbled upon Kyle Simpson here, I followed a pluralsight course by him like 7-8 years ago.)</p><h2 id="h-ternary-operator" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">Ternary Operator</h2><pre data-type="codeBlock" text="const age = 35;
let message = age &gt;= 18 ? &quot;Can Vote!&quot; : &quot;Can&apos;t Vote!&quot;;  // same as C#! GG Js!
"><code>const <span class="hljs-attr">age</span> = <span class="hljs-number">35</span><span class="hljs-comment">;</span>
let <span class="hljs-attr">message</span> = age >= <span class="hljs-number">18</span> ? <span class="hljs-string">"Can Vote!"</span> : <span class="hljs-string">"Can't Vote!"</span><span class="hljs-comment">;  // same as C#! GG Js!</span>
</code></pre><h2 id="h-functions" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">Functions</h2><p>See below the syntax for creating functions in JS (regular functions, arrow functions and methods inside classes)</p><pre data-type="codeBlock" text="const function_name = function(){}

const square_MultiLineLambda = (num) =&gt; { return num * num; }

const square_SingleLineLambda = (num) =&gt; num * num
"><code>const function_name <span class="hljs-operator">=</span> <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{}

const square_MultiLineLambda <span class="hljs-operator">=</span> (num) <span class="hljs-operator">=</span><span class="hljs-operator">></span> { <span class="hljs-keyword">return</span> num <span class="hljs-operator">*</span> num; }

const square_SingleLineLambda <span class="hljs-operator">=</span> (num) <span class="hljs-operator">=</span><span class="hljs-operator">></span> num <span class="hljs-operator">*</span> num
</code></pre><p><em>It’s worth mentioning that lambda expressions don&apos;t have access to the context when declared inside a class, they can&apos;t access &quot;this&quot;!</em></p><p>Inside classes, define functions like in C# (minus return type, minus access modifier)</p><pre data-type="codeBlock" text="function_name(){} 
"><code><span class="hljs-built_in">function_name</span>(){} 
</code></pre><h2 id="h-encapsulation-via-closures" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">Encapsulation via Closures</h2><p>In JavaScript we can simulate the same effect as encapsulating a private variable with getters and setters in C#, by using closures:</p><pre data-type="codeBlock" text="const createBankAccount = () =&gt; {
    let balance = 100000;

    getBalance = () =&gt; balance;

    depozit = (amount) =&gt; balance += amount;

    withdraw = (amount) =&gt; {
        if(amount &lt;= 5000){
            balance -= amount;
        }
    }

    return {getBalance, depozit, withdraw};
}

const bankAccount = createBankAccount();

bankAccount.depozit(6000)
console.log(bankAccount.getBalance());   // prints 106000

bankAccount.withdraw(7000)
console.log(bankAccount.getBalance());   // prints 106000 (withdraw &gt; 5000)

bankAccount.withdraw(4000)
console.log(bankAccount.getBalance());   // prints 102000
"><code>const createBankAccount <span class="hljs-operator">=</span> () <span class="hljs-operator">=</span><span class="hljs-operator">></span> {
    let balance <span class="hljs-operator">=</span> <span class="hljs-number">100000</span>;

    getBalance <span class="hljs-operator">=</span> () <span class="hljs-operator">=</span><span class="hljs-operator">></span> balance;

    depozit <span class="hljs-operator">=</span> (amount) <span class="hljs-operator">=</span><span class="hljs-operator">></span> balance <span class="hljs-operator">+</span><span class="hljs-operator">=</span> amount;

    withdraw <span class="hljs-operator">=</span> (amount) <span class="hljs-operator">=</span><span class="hljs-operator">></span> {
        <span class="hljs-keyword">if</span>(amount <span class="hljs-operator">&#x3C;</span><span class="hljs-operator">=</span> <span class="hljs-number">5000</span>){
            balance <span class="hljs-operator">-</span><span class="hljs-operator">=</span> amount;
        }
    }

    <span class="hljs-keyword">return</span> {getBalance, depozit, withdraw};
}

const bankAccount <span class="hljs-operator">=</span> createBankAccount();

bankAccount.depozit(<span class="hljs-number">6000</span>)
console.log(bankAccount.getBalance());   <span class="hljs-comment">// prints 106000</span>

bankAccount.withdraw(<span class="hljs-number">7000</span>)
console.log(bankAccount.getBalance());   <span class="hljs-comment">// prints 106000 (withdraw > 5000)</span>

bankAccount.withdraw(<span class="hljs-number">4000</span>)
console.log(bankAccount.getBalance());   <span class="hljs-comment">// prints 102000</span>
</code></pre><p>Here we define a regular function “createBankAccount“, that has our “private“ variable “balance“. The variable is private in the sense that due to the lexical scoping it cannot be used from outside the function.</p><p>Now we don’t want anyone to be able to change this variable to their liking. For this, inside our “createBankAccount“ function we define three nested functions: one for getting the balance, one for crediting the balance, and one for debiting the balance. We can even protect our balance by adding a debit limit of 5000.</p><p>All three methods have access to the balance variable due to scoping.</p><p>Then we return an object containing a reference to each of the three nested functions. (delegates in C#)</p><p>On the line below we run the “createBankAccount“ function from top to bottom.</p><pre data-type="codeBlock" text="const bankAccount = createBankAccount();
"><code>const <span class="hljs-attr">bankAccount</span> = createBankAccount()<span class="hljs-comment">;</span>
</code></pre><p>We now have in the “bankAccount“ variable an object with three references to those nested functions that have access to “let balance”.</p><p>This is how we protect the balance and allow access only through the three nested methods defined inside the closure.</p><h2 id="h-arrays" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">Arrays</h2><pre data-type="codeBlock" text="const emptyArray = []                      // Empty array
const expenses = [100.10, 45, -20]         // Array of numbers
const data = [true, 11, &apos;Paul&apos;]            // Array of mixed types

console.log(expenses[0])                   // get first
console.log(expenses[expenses.length - 1]) // get last

expenses.push(12)                          // add items
expenses.unshift(3)                        // add items before
console.log(expenses)                      // Will print [ 3, 100.1, 45, -20, 12 ]

// Splice adds, removes, edits items anywhere
const nums = [99, 199, 299]
nums.splice(1, 0, 399)                      // Add item - p1: position, p2: items to delete, p3: item to add
console.log(nums)                           // Will print [99, 399, 199, 299]

nums.pop()                                  // remove from end
nums.shift()                                // remove from beginning
console.log(nums)                           // Will print [399, 199]

nums.splice(0, 1)                           // p1: index, p2: how many elements to delete
console.log(nums)                           // Will print [399]

const nums2 = [10, 20, 30, 40]
nums2[2] = 3000;
nums2.splice(1, 1, 2000);                   // p1: at index 1, p2: delete 1 item, p3: add item 2000
console.log(nums2);                         // [10, 2000, 3000, 40]
"><code>const emptyArray <span class="hljs-operator">=</span> []                      <span class="hljs-comment">// Empty array</span>
const expenses <span class="hljs-operator">=</span> [<span class="hljs-number">100.10</span>, <span class="hljs-number">45</span>, <span class="hljs-number">-20</span>]         <span class="hljs-comment">// Array of numbers</span>
const data <span class="hljs-operator">=</span> [<span class="hljs-literal">true</span>, <span class="hljs-number">11</span>, <span class="hljs-string">'Paul'</span>]            <span class="hljs-comment">// Array of mixed types</span>

console.log(expenses[<span class="hljs-number">0</span>])                   <span class="hljs-comment">// get first</span>
console.log(expenses[expenses.<span class="hljs-built_in">length</span> <span class="hljs-operator">-</span> <span class="hljs-number">1</span>]) <span class="hljs-comment">// get last</span>

expenses.<span class="hljs-built_in">push</span>(<span class="hljs-number">12</span>)                          <span class="hljs-comment">// add items</span>
expenses.unshift(<span class="hljs-number">3</span>)                        <span class="hljs-comment">// add items before</span>
console.log(expenses)                      <span class="hljs-comment">// Will print [ 3, 100.1, 45, -20, 12 ]</span>

<span class="hljs-comment">// Splice adds, removes, edits items anywhere</span>
const nums <span class="hljs-operator">=</span> [<span class="hljs-number">99</span>, <span class="hljs-number">199</span>, <span class="hljs-number">299</span>]
nums.splice(<span class="hljs-number">1</span>, <span class="hljs-number">0</span>, <span class="hljs-number">399</span>)                      <span class="hljs-comment">// Add item - p1: position, p2: items to delete, p3: item to add</span>
console.log(nums)                           <span class="hljs-comment">// Will print [99, 399, 199, 299]</span>

nums.<span class="hljs-built_in">pop</span>()                                  <span class="hljs-comment">// remove from end</span>
nums.shift()                                <span class="hljs-comment">// remove from beginning</span>
console.log(nums)                           <span class="hljs-comment">// Will print [399, 199]</span>

nums.splice(<span class="hljs-number">0</span>, <span class="hljs-number">1</span>)                           <span class="hljs-comment">// p1: index, p2: how many elements to delete</span>
console.log(nums)                           <span class="hljs-comment">// Will print [399]</span>

const nums2 <span class="hljs-operator">=</span> [<span class="hljs-number">10</span>, <span class="hljs-number">20</span>, <span class="hljs-number">30</span>, <span class="hljs-number">40</span>]
nums2[<span class="hljs-number">2</span>] <span class="hljs-operator">=</span> <span class="hljs-number">3000</span>;
nums2.splice(<span class="hljs-number">1</span>, <span class="hljs-number">1</span>, <span class="hljs-number">2000</span>);                   <span class="hljs-comment">// p1: at index 1, p2: delete 1 item, p3: add item 2000</span>
console.log(nums2);                         <span class="hljs-comment">// [10, 2000, 3000, 40]</span>
</code></pre><h3 id="h-for-and-foreach-loops" class="text-2xl font-header !mt-6 !mb-4 first:!mt-0 first:!mb-0">For &amp; forEach loops</h3><p>For loop is the same as C#/Java</p><p>forEach is similar with linq’s foreach</p><pre data-type="codeBlock" text="const todos = [&apos;Order cat food&apos;, &apos;Clean kitchen&apos;, &apos;Buy food&apos;, &apos;Do work&apos;, &apos;Exercise&apos;]
todos.forEach(function (todo, index) {      // forEach is similar to linq&apos;s, takes a delegate as a param
 const num = index + 1
 console.log(`${num}. ${todo}`)           
})
"><code>const todos <span class="hljs-operator">=</span> [<span class="hljs-string">'Order cat food'</span>, <span class="hljs-string">'Clean kitchen'</span>, <span class="hljs-string">'Buy food'</span>, <span class="hljs-string">'Do work'</span>, <span class="hljs-string">'Exercise'</span>]
todos.forEach(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">todo, index</span>) </span>{      <span class="hljs-comment">// forEach is similar to linq's, takes a delegate as a param</span>
 const num <span class="hljs-operator">=</span> index <span class="hljs-operator">+</span> <span class="hljs-number">1</span>
 console.log(`${num}. ${todo}`)           
})
</code></pre><h3 id="h-find-index-w-indexof" class="text-2xl font-header !mt-6 !mb-4 first:!mt-0 first:!mb-0">Find index w/ indexOf</h3><pre data-type="codeBlock" text="const index = todos.indexOf(&apos;Clean kitchen&apos;);    // indexOf gets the index searching by the content
console.log(index)                               // Will print 1

// but indexOf uses &quot;&quot;===&quot;&quot; to search for the index, which doesn&apos;t work on ref types&quot;: {} === {} does not return true (diff addresses)
// for getting the index in an array of objects we use findIndex to search into the objects properties
const notes = [{title: &apos;title 1&apos;, body: &apos;body 1&apos;}, {
    title: &apos;title 2&apos;,
    body: &apos;body 2&apos;
   }];
const objIndex = notes.findIndex(function (note, index) {
    return note.title === &apos;title 2&apos;
})
console.log(index)                              // Will print 1
"><code>const index <span class="hljs-operator">=</span> todos.indexOf(<span class="hljs-string">'Clean kitchen'</span>);    <span class="hljs-comment">// indexOf gets the index searching by the content</span>
console.log(index)                               <span class="hljs-comment">// Will print 1</span>

<span class="hljs-comment">// but indexOf uses ""==="" to search for the index, which doesn't work on ref types": {} === {} does not return true (diff addresses)</span>
<span class="hljs-comment">// for getting the index in an array of objects we use findIndex to search into the objects properties</span>
const notes <span class="hljs-operator">=</span> [{title: <span class="hljs-string">'title 1'</span>, body: <span class="hljs-string">'body 1'</span>}, {
    title: <span class="hljs-string">'title 2'</span>,
    body: <span class="hljs-string">'body 2'</span>
   }];
const objIndex <span class="hljs-operator">=</span> notes.findIndex(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">note, index</span>) </span>{
    <span class="hljs-keyword">return</span> note.title <span class="hljs-operator">=</span><span class="hljs-operator">=</span><span class="hljs-operator">=</span> <span class="hljs-string">'title 2'</span>
})
console.log(index)                              <span class="hljs-comment">// Will print 1</span>
</code></pre><h3 id="h-find-object-w-find" class="text-2xl font-header !mt-6 !mb-4 first:!mt-0 first:!mb-0">Find object w/ find</h3><pre data-type="codeBlock" text="// for getting the whole object, just use find instead of findIndex:
const obj = notes.find(function (note, index) {
    return note.title === &apos;title 2&apos;
})
console.log(obj)                                // Will print { title: &apos;title 2&apos;, body: &apos;body 2&apos; }

const todoItems = [{text: &apos;t1&apos;, completed: false}, {text: &apos;t2&apos;, completed: true}, {text: &apos;t3&apos;, completed: false}]
"><code><span class="hljs-comment">// for getting the whole object, just use find instead of findIndex:</span>
const obj <span class="hljs-operator">=</span> notes.find(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">note, index</span>) </span>{
    <span class="hljs-keyword">return</span> note.title <span class="hljs-operator">=</span><span class="hljs-operator">=</span><span class="hljs-operator">=</span> <span class="hljs-string">'title 2'</span>
})
console.log(obj)                                <span class="hljs-comment">// Will print { title: 'title 2', body: 'body 2' }</span>

const todoItems <span class="hljs-operator">=</span> [{text: <span class="hljs-string">'t1'</span>, completed: <span class="hljs-literal">false</span>}, {text: <span class="hljs-string">'t2'</span>, completed: <span class="hljs-literal">true</span>}, {text: <span class="hljs-string">'t3'</span>, completed: <span class="hljs-literal">false</span>}]
</code></pre><h3 id="h-filter" class="text-2xl font-header !mt-6 !mb-4 first:!mt-0 first:!mb-0">Filter</h3><pre data-type="codeBlock" text="/*
* Filter returns a NEW array with the filtered elements
* Takes as param a callback function 
*                         - which gets called for each element with the collection and the index
*                         - returns true for including an element
*                         - returns false for excluding an element
*/
const thingsToDo = todoItems.filter(function (todo) {
    return !todo.completed
});
   
console.log(thingsToDo)     // Wil print t1 &amp; t3 objects
"><code><span class="hljs-comment">/*
* Filter returns a NEW array with the filtered elements
* Takes as param a callback function 
*                         - which gets called for each element with the collection and the index
*                         - returns true for including an element
*                         - returns false for excluding an element
*/</span>
const thingsToDo <span class="hljs-operator">=</span> todoItems.filter(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">todo</span>) </span>{
    <span class="hljs-keyword">return</span> <span class="hljs-operator">!</span>todo.completed
});
   
console.log(thingsToDo)     <span class="hljs-comment">// Wil print t1 &#x26; t3 objects</span>
</code></pre><h3 id="h-sort" class="text-2xl font-header !mt-6 !mb-4 first:!mt-0 first:!mb-0">Sort</h3><pre data-type="codeBlock" text="/**
 * Sort takes a delegate with two items of the array &quot;a&quot; &amp; &quot;b&quot;
 * Implement the delegate&apos;s callback function so that it:
 *                         - returns -1 if &quot;a&quot; should come first
 *                         - returns 1 if &quot;b&quot; should come first
 *                         - returns 0 is &quot;a&quot; &amp; &quot;b&quot; are equal
 * * does NOT return a NEW collection!
 */
todoItems.sort(function (a, b) {
    if (!a.completed &amp;&amp; b.completed) {
        return -1
    } else if (!b.completed &amp;&amp; a.completed) {
        return 1
    } else {
        return 0
    }
})
console.log(todoItems)      // Wil print t1, t3, t2 objects (sorted by completed prop)
"><code><span class="hljs-comment">/**
 * Sort takes a delegate with two items of the array "a" &#x26; "b"
 * Implement the delegate's callback function so that it:
 *                         - returns -1 if "a" should come first
 *                         - returns 1 if "b" should come first
 *                         - returns 0 is "a" &#x26; "b" are equal
 * * does NOT return a NEW collection!
 */</span>
todoItems.sort(<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params">a, b</span>) </span>{
    <span class="hljs-keyword">if</span> (<span class="hljs-operator">!</span>a.completed <span class="hljs-operator">&#x26;</span><span class="hljs-operator">&#x26;</span> b.completed) {
        <span class="hljs-keyword">return</span> <span class="hljs-number">-1</span>
    } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (<span class="hljs-operator">!</span>b.completed <span class="hljs-operator">&#x26;</span><span class="hljs-operator">&#x26;</span> a.completed) {
        <span class="hljs-keyword">return</span> <span class="hljs-number">1</span>
    } <span class="hljs-keyword">else</span> {
        <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>
    }
})
console.log(todoItems)      <span class="hljs-comment">// Wil print t1, t3, t2 objects (sorted by completed prop)</span>
</code></pre><p>Find all methods in <a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf">mdn docs here</a>.</p><h2 id="h-the-rest-parameter-vs-the-spread-syntax" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">The Rest Parameter vs The Spread Syntax</h2><p>The rest parameter is very similar to C#’s params argument. You can use it as a parameter in a method signature when you have a variable number of parameters you want to pass in. The operator will receive those parameters as an array.</p><p>Suppose we have a function that sums two numbers:</p><pre data-type="codeBlock" text="const sum = (a, b) =&gt; {
    return a + b;
}

console.log(sum(1,2));
}
"><code>const sum <span class="hljs-operator">=</span> (a, b) <span class="hljs-operator">=</span><span class="hljs-operator">></span> {
    <span class="hljs-keyword">return</span> a <span class="hljs-operator">+</span> b;
}

console.log(sum(<span class="hljs-number">1</span>,<span class="hljs-number">2</span>));
}
</code></pre><p>Now suppose we want to change the function to accept being called with a variable amount of numbers to be summed? The code would look like this:</p><pre data-type="codeBlock" text="const sum2 = (...params) =&gt; {
    let sum = 0;
    params.forEach(i =&gt; sum += i);

    return sum;
}

console.log(sum2(1, 2, 3));
console.log(sum2(1, 2, 3, 4, 5));
"><code>const sum2 <span class="hljs-operator">=</span> (...params) <span class="hljs-operator">=</span><span class="hljs-operator">></span> {
    let sum <span class="hljs-operator">=</span> <span class="hljs-number">0</span>;
    params.forEach(i <span class="hljs-operator">=</span><span class="hljs-operator">></span> sum <span class="hljs-operator">+</span><span class="hljs-operator">=</span> i);

    <span class="hljs-keyword">return</span> sum;
}

console.log(sum2(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>));
console.log(sum2(<span class="hljs-number">1</span>, <span class="hljs-number">2</span>, <span class="hljs-number">3</span>, <span class="hljs-number">4</span>, <span class="hljs-number">5</span>));
</code></pre><p>In JS the rest parameter has three dots before “…rest“. Also same as C# if we have multiple parameters in the function, the rest param naturally comes last.</p><p>Now we can also use the rest parameter for something else that I find both awesome and useful, and that is to deep copy an array:</p><pre data-type="codeBlock" text="const arrayOne = [&quot;One&quot;, &quot;Two&quot;, &quot;Three&quot;];
const arrayTwo = [...arrayOne]; 
arrayTwo.push(&quot;Four&quot;);
console.log(arrayOne);   // prints [ &apos;One&apos;, &apos;Two&apos;, &apos;Three&apos; ]
console.log(arrayTwo);   // prints [ &apos;One&apos;, &apos;Two&apos;, &apos;Three&apos;, &apos;Four&apos; ]
"><code>const arrayOne <span class="hljs-operator">=</span> [<span class="hljs-string">"One"</span>, <span class="hljs-string">"Two"</span>, <span class="hljs-string">"Three"</span>];
const arrayTwo <span class="hljs-operator">=</span> [...arrayOne]; 
arrayTwo.<span class="hljs-built_in">push</span>(<span class="hljs-string">"Four"</span>);
console.log(arrayOne);   <span class="hljs-comment">// prints [ 'One', 'Two', 'Three' ]</span>
console.log(arrayTwo);   <span class="hljs-comment">// prints [ 'One', 'Two', 'Three', 'Four' ]</span>
</code></pre><p>The <code>const arrayTwo = [...arrayOne];</code> takes each element from arrayOne and copies it into arrayTwo. The result is a deep copy of arrayOne.</p><h3 id="h-the-spread-syntax-is-the-opposite-of-the-rest-parameter" class="text-2xl font-header !mt-6 !mb-4 first:!mt-0 first:!mb-0">The Spread Syntax is the opposite of the Rest Parameter.</h3><p>Let’s say I have the same add method that receives numbers as a rest param, and let’s say this method is part of a third party library and I cannot change it’s signature. Also imagine I have an array of numbers that I want to pass in <strong>as parameters</strong> so they can be received by the rest parameter:</p><pre data-type="codeBlock" text="const numbers = [10, 20, 30, 40, 50, 60];

// Sum should be called like this:
// sum2(10, 20, 30, 40, 50, 60); 
// but my numbers are in an array!

console.log(sum2(...numbers));  // spreads out all array items as parameters
"><code>const numbers <span class="hljs-operator">=</span> [<span class="hljs-number">10</span>, <span class="hljs-number">20</span>, <span class="hljs-number">30</span>, <span class="hljs-number">40</span>, <span class="hljs-number">50</span>, <span class="hljs-number">60</span>];

<span class="hljs-comment">// Sum should be called like this:</span>
<span class="hljs-comment">// sum2(10, 20, 30, 40, 50, 60); </span>
<span class="hljs-comment">// but my numbers are in an array!</span>

console.log(sum2(...numbers));  <span class="hljs-comment">// spreads out all array items as parameters</span>
</code></pre><p>The spread operator has the same syntax as the rest parameter but it’s used in a function call (to spread out the array items as parameters) as opposed being used in a function signature (to bundle function parameters into an array).</p><h2 id="h-try-catch" class="text-3xl font-header !mt-8 !mb-4 first:!mt-0 first:!mb-0">Try-Catch</h2><pre data-type="codeBlock" text="// same syntax as C#. I imagine throwing stuff often since js refuses to fail

const addLikeAPro = (a, b) =&gt; {
    if (typeof a !== &quot;number&quot; || typeof b !== &quot;number&quot;) {
        throw new Error(&quot;One of the params is not a number&quot;);
    }
    return a + b;
}

try {
    const sum = addLikeAPro(10, &quot;cow&quot;);
    console.log(sum);
}
catch (e) {
    console.log(e);
}
"><code><span class="hljs-comment">// same syntax as C#. I imagine throwing stuff often since js refuses to fail</span>

const addLikeAPro <span class="hljs-operator">=</span> (a, b) <span class="hljs-operator">=</span><span class="hljs-operator">></span> {
    <span class="hljs-keyword">if</span> (typeof a <span class="hljs-operator">!</span><span class="hljs-operator">=</span><span class="hljs-operator">=</span> <span class="hljs-string">"number"</span> <span class="hljs-operator">|</span><span class="hljs-operator">|</span> typeof b <span class="hljs-operator">!</span><span class="hljs-operator">=</span><span class="hljs-operator">=</span> <span class="hljs-string">"number"</span>) {
        <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">"One of the params is not a number"</span>);
    }
    <span class="hljs-keyword">return</span> a <span class="hljs-operator">+</span> b;
}

<span class="hljs-keyword">try</span> {
    const sum <span class="hljs-operator">=</span> addLikeAPro(<span class="hljs-number">10</span>, <span class="hljs-string">"cow"</span>);
    console.log(sum);
}
<span class="hljs-keyword">catch</span> (e) {
    console.log(e);
}
</code></pre><p>Since the last time I checked out JavaScript, it seems that the language has fixed many of its faults with the introduction of const/let and strict mode.</p><p>In part II of this three-part series I’ll explore JavaScript’s Object-Oriented Programming and its prototypical inheritance.</p><p><a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://mirror.xyz/quantarcane.eth/sw3wZxsZH-JXExMDCxcJFvd2sN9iS1X2YxNFnAZRPpI">https://mirror.xyz/quantarcane.eth/sw3wZxsZH-JXExMDCxcJFvd2sN9iS1X2YxNFnAZRPpI</a></p><p><a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://mirror.xyz/quantarcane.eth/fyMW6ZXkJ1AA3FN42TU522_YR5gh_QyyvMZev84Tshg">https://mirror.xyz/quantarcane.eth/fyMW6ZXkJ1AA3FN42TU522_YR5gh_QyyvMZev84Tshg</a></p><h3 id="h-lets-connect" class="text-2xl font-header !mt-6 !mb-4 first:!mt-0 first:!mb-0">Let’s connect:</h3><p>You can find the full set of examples over at my <a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://github.com/razvanpiticas/js-primer">github</a> page.</p><p>Also if you liked the article, I&apos;m constantly tweeting about this stuff and more. Feel free to follow me on <a target="_blank" rel="noopener noreferrer nofollow ugc" class="dont-break-out" href="https://twitter.com/QuantArcane">Twitter</a> and drop a comment to say hi!</p>]]></content:encoded>
            <author>quantarcane@newsletter.paragraph.com (QuantArcane)</author>
            <enclosure url="https://storage.googleapis.com/papyrus_images/cb53c96f7766cdb41b6657922d8838ca0bc4fa5926f58687fefc62b1b7ddf42e.png" length="0" type="image/png"/>
        </item>
    </channel>
</rss>