<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Dimosthenis Botsaris on Medium]]></title>
        <description><![CDATA[Stories by Dimosthenis Botsaris on Medium]]></description>
        <link>https://medium.com/@el_dimious?source=rss-4ac6abed8195------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*_GaA-XyPjbhjrRdYyWhtuA.jpeg</url>
            <title>Stories by Dimosthenis Botsaris on Medium</title>
            <link>https://medium.com/@el_dimious?source=rss-4ac6abed8195------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 18:28:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@el_dimious/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[#003 JavaScript with Dimos: Scope Explained]]></title>
            <link>https://medium.com/arconsis/003-javascript-with-dimos-scope-explained-1cdd9c5e52be?source=rss-4ac6abed8195------2</link>
            <guid isPermaLink="false">https://medium.com/p/1cdd9c5e52be</guid>
            <category><![CDATA[global-scope]]></category>
            <category><![CDATA[variables]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[local-scope]]></category>
            <category><![CDATA[scopes]]></category>
            <dc:creator><![CDATA[Dimosthenis Botsaris]]></dc:creator>
            <pubDate>Thu, 19 May 2022 13:29:55 GMT</pubDate>
            <atom:updated>2022-05-19T13:29:55.825Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Hey there 👋 I am </em><a href="https://www.eldimious.com/"><em>Dimos</em></a><em>, a senior software engineer and software architect at </em><a href="https://www.arconsis.com/"><em>arconsis</em></a><em>. From time to time, I publish articles into the series “JavaScript with Dimos”, where I am trying to analyze a JavaScript topic and to focus on the core concepts of JavaScript.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*_HK5qZGiZnvlFz4j2cZIBw.jpeg" /></figure><p>Scope defines <strong>variable’s accessibility</strong> (visibility). If we would like to code in JavaScript, then understanding the variable’s scope is mandatory. JavaScript has the 2 following scope types:</p><ul><li><strong>Global</strong> scope</li><li><strong>Local</strong> scope:<br>a) Function scope<br>b) Lexical scope<br>c) Block scope<br>d) Module scope</li></ul><h3>Global Scope</h3><p>The outmost scope is referred to as global scope. Any variable declared outside of a function is a <strong>global</strong> <strong>variable</strong>, which can be <strong>accessed</strong> from any other scope. <br>For example window and document are global variables supplied by the browser.</p><pre>const animal = &quot;cat&quot;;</pre><pre>function myFunction() {<br>   console.log(animal);<br>}<br><br>myFunction(); // output: cat</pre><p>In the above code block, the variable animal is declared at the top of the program, therefore, is a <strong>global</strong> variable. This means that it can be <strong>used anywhere</strong> in the program. Hence, animal can be accessed inside any function, e.g. in myFunction(). <br>When we assign a value to a variable that has <strong>not</strong> been declared (we forgot to add var / const / let keyword), it will automatically become a <strong>global variable</strong>.</p><pre>function myFunction() {<br>   vehicle = &quot;car&quot;; // vehicle is considered as global variable<br>}</pre><pre>myFunction();<br>console.log(vehicle); // output: car</pre><blockquote><strong>Note</strong>: It is preferable to avoid creating, using global variables (considered as anti-pattern), because the value of a global variable can change in different parts in the program and can lead to unexpected results. We should always have strict mode enabled (in ES5, the Strict Mode is optional but in ES6, it’s needed for many ES6 features).</blockquote><pre>&#39;use strict&#39;;<br>function myFunction() {<br>   vehicle = &quot;car&quot;; // vehicle is considered as global variable<br>}</pre><pre>myFunction();<br>console.log(vehicle); // Uncaught ReferenceError: assignment to undeclared variable vehicle</pre><p>In the above program, we used ‘use strict’ which will execute code block in ‘<strong>strict mode</strong>’. Hence, when we try to use a variable animal (which is not declared), we get a ReferenceError, as in strict mode, we cannot use the variable without declaring them.</p><h3>Function scope</h3><p>Each function creates its own new scope. Variables defined inside a function <strong>can’t</strong> be accessed from anywhere <strong>outside</strong> the function, since the variable is defined only in the scope of the function. A function, on the other hand, can access all variables and functions defined within the scope in which it was defined.<br>When declared inside a function, variables declared with var, let and const are quite similar, as they are <strong>function-scoped</strong></p><pre>function myFunction() {<br>   const animal = &quot;cat&quot;;<br>   console.log(animal);<br>}</pre><pre>myFunction(); // output: cat<br>console.log(animal); // Uncaught ReferenceError: animal is not defined</pre><p>In the above program, the variable animal can be accessed only inside the function myFunction(), as is <strong>function-scoped</strong>. Therefore, when we try to access variable animal outside of the function, an error occurs.</p><h3>Lexical scope</h3><p>The ability for a function scope to access variables from the parent scope is known as <strong>lexical scope</strong> (or static scope). As a result, variable accessibility is determined statically by the position of variables within nested function scopes. Therefore, a nested inner function (closure) can access the scope of an outer function.</p><pre>function outerFunc() {<br>   // the outer scope<br>   const animal = &quot;cat&quot;;<br>   function innerFunc() {<strong><br>      </strong>// the inner scope<br>      console.log(animal); // output: cat<br>   }<strong><br>   </strong>return innerFunc;<br>}</pre><pre>outerFunc()();</pre><p>In the above program, we have 2 functions the outerFunc() and a nested one called innerFunc(). As we can see the innerFunc() (because of lexical scoping) can access animal animal variable which is function-scoped to outerFunc(). Hence, in the above example, the lexical scope of innerFunc() consists of the scope of outerFunc().</p><h3>Block scope</h3><p>The ES6 introduced two new JavaScript keywords: let and const , which provide <strong>Block Scope</strong>. As a result, a variable declared using let or const can only be accessed within the block in which it was declared. A variable declared using var, on the other hand, stays <strong>function-scoped</strong>.<br>The code block of if, for, while statements also create a block scope. Hence a variable declared inside {…} can not be accessed outside the block.</p><pre>for (const animal of [&#39;cat&#39;, &#39;dog&#39;, &#39;wolf&#39;]) {<br>   // &quot;for&quot; block scope<br>   const message = &#39;Hi&#39;;<br>   console.log(animal);   // output: &#39;cat&#39;, &#39;dog&#39;, &#39;wolf&#39;<br>   console.log(message); // output: &#39;Hi&#39;, &#39;Hi&#39;, &#39;Hi&#39;<br>}</pre><pre>console.log(animal);  // Uncaught ReferenceError: color is not defined<br>console.log(message);  // Uncaught ReferenceError: message is not defined</pre><p>Another one example:</p><pre>function myFunction() {<br>   const animal = &quot;cat&quot;;<br>   if (true) {<br>      var car1 = &quot;porsche&quot;;<br>      const car2 = &quot;opel&quot;;<br>      let car3 = &quot;volvo&quot;;<br>      console.log(car1); // output: porsche<br>      console.log(car2); // output: opel<br>      console.log(car3); // output: volvo<br>   }<br>   console.log(animal); // output: cat<br>   console.log(car1); // output: porsche<br>   console.log(car2); // Uncaught ReferenceError: car2 is not defined<br>   console.log(car3); // Uncaught ReferenceError: car3 is not defined<br>}<br><br>myFunction();</pre><p>In the above program, variable</p><ul><li>animal is a local variable (function-scoped) and can be accessed only inside the function myFunction().</li><li>car1 is declared as var for this reason is considered as function-scoped variable and can be accessed only inside the function myFunction()</li><li>car2 and car3 variables are declared using const and let, hence are considered as block-scoped and can be accessed only inside the if statement block.</li></ul><h3>Module scope</h3><p>The ES6 module also creates a scope for variables, functions, classes. Before ES6 modules, every variable declared outside any function was a global variable. Now, if we declare a variable inside an ES6 module is <strong>hidden</strong> and <strong>not available</strong> to other modules unless it is <strong>explicitly exported</strong>. <br>Let’s try to create a module called animal which has a declared variable.</p><pre>// &quot;animal&quot; module scope in animal.js file<br>const cat = &quot;cat&quot;;<br>console.log(cat); // output: cat<br>// Usage of cat</pre><p>Let’s try to import above module:</p><pre>import &#39;./animal&#39;;<br>console.log(cat); // Uncaught ReferenceError: cat is not defined</pre><p>The variable cat is not accessible outside of animal module (unless explicitly exported using export). The module scope makes the module encapsulated and every variable (that’s <strong>not exported</strong>) remains as “<strong>private</strong>”.</p><p>Let’s now try to explicitly export cat from animal module.</p><pre>// &quot;animal&quot; module scope in animal.js file<br>const cat = &quot;cat&quot;;<br>console.log(cat); // output: cat</pre><pre>// export cat variable explicitly<br>export { cat };</pre><p>and now import it to another JS file:</p><pre>import { cat } from &#39;./animal.js&#39;;</pre><pre>console.log(cat); // output: cat</pre><p>Those are all the scopes available in JavaScript. Meanwhile, please feel free to post any questions, comments, or feedback in the comment section below.</p><p>Follow on Twitter <a href="https://twitter.com/el_dimious/">here</a>!<br>Follow on Github <a href="https://github.com/eldimious">here</a>!</p><h4>Further Reading</h4><ol><li><a href="https://www.tutorialsteacher.com/javascript/scope-in-javascript">https://www.tutorialsteacher.com/javascript/scope-in-javascript</a></li><li><a href="https://dmitripavlutin.com/javascript-scope/">https://dmitripavlutin.com/javascript-scope/</a></li><li><a href="https://www.w3schools.com/JS//js_scope.asp">https://www.w3schools.com/JS//js_scope.asp</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions#function_scope">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions#function_scope</a></li><li><a href="https://www.programiz.com/javascript/variable-scope">https://www.programiz.com/javascript/variable-scope</a></li><li><a href="https://www.educative.io/edpresso/lexical-scope-in-javascript">https://www.educative.io/edpresso/lexical-scope-in-javascript</a></li><li><a href="https://www.freecodecamp.org/news/an-introduction-to-scope-in-javascript-cbd957022652/">https://www.freecodecamp.org/news/an-introduction-to-scope-in-javascript-cbd957022652/</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1cdd9c5e52be" width="1" height="1" alt=""><hr><p><a href="https://medium.com/arconsis/003-javascript-with-dimos-scope-explained-1cdd9c5e52be">#003 JavaScript with Dimos: Scope Explained</a> was originally published in <a href="https://medium.com/arconsis">arconsis</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[#002 JavaScript with Dimos: Data Types]]></title>
            <link>https://medium.com/arconsis/002-javascript-with-dimos-data-types-5ad3efc79cba?source=rss-4ac6abed8195------2</link>
            <guid isPermaLink="false">https://medium.com/p/5ad3efc79cba</guid>
            <category><![CDATA[data-type]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[javascript-development]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[variables]]></category>
            <dc:creator><![CDATA[Dimosthenis Botsaris]]></dc:creator>
            <pubDate>Thu, 12 May 2022 08:13:55 GMT</pubDate>
            <atom:updated>2022-05-12T08:16:34.797Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Hey there 👋 I am </em><a href="https://www.eldimious.com/"><em>Dimos</em></a><em>, a senior software engineer and software architect at </em><a href="https://www.arconsis.com/"><em>arconsis</em></a><em>. From time to time, I publish articles into the series “JavaScript with Dimos”, where I am trying to analyze a JavaScript topic and to focus on the core concepts of JavaScript.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*_HK5qZGiZnvlFz4j2cZIBw.jpeg" /></figure><p>In the chapter “JavaScript’s Grammar” we will take a look at JavaScript’s basic grammar, variable declarations and data types.</p><h4>Chapter’s Posts Roadmap</h4><ul><li><a href="https://medium.com/arconsis/001-javascript-with-dimos-variables-and-constants-555599d765df">Variables and Constants</a></li><li>Data Types (This article)</li></ul><p>This is the second article of this chapter which focuses on<strong> built-in</strong> data structures available in JavaScript.</p><h3><strong><em>What is a data type?</em></strong></h3><p><strong>Data structures</strong> are built-in in all programming languages, but often these differ from one language to another.</p><blockquote>The<strong> data type</strong> is a classification that specifies which type of value a variable has in our code.</blockquote><h3>Dynamic typing</h3><p>JavaScript is a <strong><em>loosely typed</em></strong> and <strong><em>dynamic</em> language</strong>. Variables in JavaScript are not directly associated with any specific value type, and each variable can be assigned (and re-assigned) values of all types. For example:</p><pre>let foo = 42;    // foo is now a &quot;number&quot;<br>foo     = &#39;bar&#39;; // foo is now a &quot;string&quot;<br>foo     = true;  // foo is now a &quot;boolean&quot;</pre><h3>JavaScript types</h3><p>There are two types of data types in JavaScript.</p><ol><li><strong>Primitive</strong> data type (<em>immutable</em> values)<br>- <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#boolean_type">Boolean type</a><br>- <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#number_type">Number type</a><br>- <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#string_type">String type</a><br>- <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#undefined_type">Undefined type</a><br>- <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#null_type">Null type</a><br>- <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#bigint_type">BigInt type</a><br>- <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#symbol_type">Symbol type</a> (added in ES6)</li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#objects"><strong>Objects</strong></a> (<em>reference</em>) data type</li></ol><p><strong>Primitive</strong> data types are <em>immutable, </em>which means that values can not be changed and are always copied “<em>as whole value</em>”. On the other hand, <strong>objects</strong> used as <em>key-value pairs</em> of collection which are stored and copied “<em>by reference</em>”.</p><h3>typeof Operator</h3><p>The typeof operator <strong>inspects</strong> the data type of its given operand, and always returns one of the following values as string:</p><ul><li>“boolean”</li><li>“number”</li><li>“bigint”</li><li>“string”</li><li>“undefined”</li><li>“symbol”</li><li>“object”</li><li>“function”</li></ul><p>As we can see, typeof operator returns all built-in JavaScript’s data types apart from null. We will take a closer look below which value is returned when we apply typeof operator on a null. Also, we can notice that it returns &quot;function&quot; as another new value, as “function” is a top-level built-in type in JavaScript.</p><h3>Boolean Type</h3><p>It represents <em>logical</em> entities which can have one of these two values: true or false. If we use typeof to inspect<strong> </strong>variables of that type, it will return &quot;boolean&quot; as string value. For example:</p><pre>const isOrderValid = true;<br>typeof isOrderValid; // &quot;boolean&quot;</pre><pre>const isOrderCreated = false;<br>typeof isOrderCreated; // &quot;boolean&quot;</pre><h4>Boolean primitives and Boolean objects</h4><p>We can use <strong>Boolean constructor</strong> to create a new Boolean object, which is just an object wrapper for a boolean value. To call the constructor, we must provide a value as an argument that will be converted to a boolean value.<br>The Boolean object has <strong>false </strong>as initial value, if the value is absented or +0, -0, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/null">null</a>, false, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NaN">NaN</a>, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined">undefined</a>, or the empty string (&quot;&quot;) (these values are considered as “falsy”). While, the rest values, including any object, an empty array ([]), or the string &quot;false&quot;, have as initial value <strong>true</strong>.<br>We can use constructor via the two following ways:</p><pre>new Boolean(true) // constructor function<br>Boolean(true) // non-constructor function</pre><pre>typeof new Boolean(true); // object<br>typeof Boolean(true); // boolean</pre><blockquote>JavaScript distinguishes between Boolean objects and primitive boolean values.</blockquote><blockquote>Boolean literals (true / false) and values created by the non-constructor Boolean function (<strong>without</strong> using the new keyword) are <a href="https://developer.mozilla.org/en-US/docs/Glossary/Primitive">primitive</a> strings as type coercion (implicit conversion) is performed when called as a function. Although, the values created using constructor Number function (via <strong>new</strong> keyword) are <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#objects">objects</a>. That’s why we <strong>rarely</strong> want to use the <strong>Boolean constructor</strong> at all.<br>Be careful, we should not confuse the <a href="https://developer.mozilla.org/en-US/docs/Glossary/Primitive">primitive</a> Boolean values true and false with the true and false values of the Boolean object. Any boolean object is evaluated to <strong>true</strong> when passed to a <strong>conditional statement.</strong></blockquote><pre>const x = new Boolean(false); // constructor function<br>const y = Boolean(false); // non-constructor function</pre><pre>if (x) {<br>   // code block is executed<br>   console.log(&quot;enters if statement, using function constructor&quot;);<br>}<br>if (y) {<br>   // code block is not executed<br>   console.log(&quot;enters if statement using function&quot;);<br>}<br>if (false) {<br>   // code block is not executed<br>   console.log(&quot;enters if statement using literal&quot;);<br>}</pre><p>As we can above, any Boolean object is evaluated to true when passed to a conditional statement, as the problem is that we’ve created an object wrapper around the false value, but objects themselves are &quot;truthy&quot;.</p><blockquote>If we want to use a Boolean object, then we should use it in a <strong>non</strong>-constructor function (without using the new keyword).</blockquote><blockquote>Hence, we should avoid using a Boolean object to convert a non-boolean value to a boolean value. To perform this task, instead, we should use Boolean as a function (without using the new keyword), or a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_NOT">double NOT operator</a>:</blockquote><pre>var x = Boolean(expression);     // use this...<br>var x = !!(expression);          // ...or this<br>var x = new Boolean(expression); // don&#39;t use this!</pre><h3>Number Type</h3><p>It represents represents <em>integer</em> and <em>floating</em> numbers. The JavaScript Number type is a double-precision 64-bit binary format IEEE 754 value. Values outside of the range from <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MIN_VALUE">Number.MIN_VALUE</a> to <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_VALUE">Number.MAX_VALUE</a> are automatically converted to either +Infinity or -Infinity<br>If we use typeof to inspect<strong> </strong>variables of that type, it will return &quot;number&quot;. For example:</p><pre>const num1 = 9; // literal<br>typeof num1; // &quot;number&quot;</pre><pre>const num2 = 9.633; // literal<br>typeof num2; // &quot;number&quot;</pre><pre>const num3 = 9e6; // literal<br>typeof num3; // &quot;number&quot;</pre><h4>Number primitives and Number objects</h4><p>We can use <strong>Number constructor</strong> to create a new Number object, which is just an <em>object wrapper</em> for a number value. We can use constructor via the following two ways:</p><pre>const x = new Number(3); // constructor function<br>const y = Number(3); // non-constructor function</pre><pre>typeof new Number(3); // object<br>typeof Number(3); // number<br>typeof 3; // number</pre><pre>new Number(3) === 3; // false<br>Number(3) === 3; // true<br>3 === 3; // true</pre><blockquote>JavaScript distinguishes between Number objects and primitive number values.</blockquote><blockquote>Number literals and values created by the non-constructor Number function (without using the new keyword) are <a href="https://developer.mozilla.org/en-US/docs/Glossary/Primitive">primitive</a> strings as type coercion (implicit conversion) is performed when called as a function. Although, the values created using constructor Number function (via new keyword) are <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#objects">objects</a>. That’s why we <strong>rarely</strong> want to use the <strong>Number constructor</strong> at all.</blockquote><h3>String Type</h3><p>It represents some <em>text data. </em>We can create strings using <strong>single</strong> or <strong>double</strong> <strong>quotes</strong> surrounding one or more characters. If we use typeof to inspect<strong> </strong>variables of that type, it will return &quot;string&quot;. For example:</p><pre>const str1 = &#39;foo&#39;;<br>typeof str1; // &quot;string&quot;</pre><pre>const str2 = &quot;bar&quot;;<br>typeof str2; // &quot;string&quot;</pre><pre>const str3 = `The string values are ${str1} and ${str2}`;<br>typeof str3; // &quot;string&quot;</pre><h4>String primitives and String objects</h4><p>We can use <strong>String constructor</strong> to create a new String object, which is just an object wrapper for a string value. We can use constructor via the following two ways:</p><pre>new String(str); // constructor function<br>String(str); // non-constructor function</pre><pre>typeof String(&#39;foo&#39;); // string<br>typeof new String(&#39;foo&#39;); // object</pre><blockquote>JavaScript distinguishes between String objects and primitive string values.</blockquote><blockquote>String literals (create by double or single quotes) and strings returned from String using the non-constructor function (without using the new keyword) are primitive strings as type coercion (implicit conversion) is performed when called as a function. Although, the values created using constructor function (via new keyword) are <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#objects">objects</a>. That’s why we <strong>rarely</strong> want to use the <strong>String constructor</strong> at all.</blockquote><h3>Undefined Type</h3><p>It represents a variable which has been declared but has <strong>not</strong> been <em>assigned</em> with any value. If we use typeof to inspect<strong> </strong>variables of that type, it will return &quot;undefined&quot;. For example:</p><pre>let str;<br>console.log(str); // undefined<br>typeof str; // &quot;undefined&quot;</pre><h3>Null Type</h3><p>It is a special value that represents <em>empty</em> or <em>unknown</em> value. <strong>Be careful</strong>, null is “<strong>buggy</strong>” when used with the typeof operator, as if we use typeof to inspect variables of that type will return &quot;<strong>object</strong>&quot;. For example:</p><pre>let str = null;<br>console.log(str); // null<br>typeof str; // &quot;object&quot;</pre><h3>BigInt Type</h3><p>If we need <em>bigger number</em> then, we should use BigInt as data type (was introduced in the newer version of JavaScript). If we use typeof to inspect<strong> </strong>variables of that type, it will return &quot;bigint&quot;. For example:</p><pre>const bigNum1 = BigInt(Number.MAX_SAFE_INTEGER);<br>// 9007199254740991n<br>typeof bigNum1; // &quot;bigint&quot;</pre><h3>Symbol Type</h3><p>It has been introduced in JavaScript ES6 version and is an immutable primitive value that is unique, and can be used to create unique identifiers for objects. Symbols are always <strong>unique</strong>. As a result, even if we create many symbols with the same description, the values will be different.<br>If we use typeof to inspect<strong> </strong>variables of that type, it will return &quot;symbol&quot;. For example:</p><pre>let symbol1 = Symbol(&quot;Test&quot;)<br>let symbol2 = Symbol(&quot;Test&quot;)<br><br>console.log(symbol1 === symbol2) // returns &quot;false&quot;<br>typeof symbol1; // &quot;symbol&quot;<br>typeof symbol2; // &quot;symbol&quot;</pre><h3>Object Type</h3><p>It is a is a <strong>non-primitive</strong> data-type which is key-value and allows us to store <strong>collections</strong> of data. If we use typeof to inspect<strong> </strong>variables of that type, it will return &quot;object&quot;. For example:</p><pre>const user = {<br>    firstName: &#39;Dimos&#39;,<br>    lastName: &#39;Botsaris&#39;,<br>    age: 33<br>};<br>typeof user; //&quot;object&quot;</pre><p>We will take a deep dive into JavaScript Objects in next tutorials.</p><h3>Data Type Conversions</h3><p>Type conversion means casting from one data type to another. In JavaScript we can use 2 kinds of type conversion:</p><ul><li><strong>Implicit Conversion</strong> — automatic conversion via compiler (coercion)</li><li><strong>Explicit Conversion</strong> — manual conversion</li></ul><h4>Implicit Conversion (coercion)</h4><p>It is the automatic values casting from one data type to another (such as strings to numbers)</p><pre>const num = 1;<br>const str = &#39;3&#39;;<br>const bool = true;</pre><pre>const result1 = num + str; <br>console.log(result1) // output: &quot;31&quot;<br><br>const result2 = str + bool; <br>console.log(result2); // output: &quot;3true&quot;<br><br>const result3 = str - &#39;2&#39;; <br>console.log(result3); // output: 1</pre><p>In the above example, JavaScript has implicitly casted the 1 from a number into a string, resulting in a string of &quot;31&quot;. If we want to have a sum as number (4) as result we should to explicitly cast str to number via Number constructor. For example:</p><pre>const num = 1;<br>const str = &#39;3&#39;;</pre><pre>const result = num + Number(str);<br>console.log(result); // output: 4</pre><h4>Explicit Conversion</h4><p>In JavaScript, we can also convert one data type to another manually via explicit conversion using constructors like String, Number.</p><ul><li><strong>Convert to String Explicitly</strong></li></ul><pre>let result = String(123);<br>console.log(result);  // output: &quot;123&quot;</pre><pre>result = String(1 + 2);<br>console.log(result); // output: &quot;3&quot;</pre><pre>result = String(false);<br>console.log(result); // &quot;false&quot;</pre><pre>result = String(undefined);<br>console.log(result); // &quot;undefined&quot;</pre><pre>result = String(null);<br>console.log(result); // &quot;null&quot;</pre><ul><li><strong>Convert to Number Explicitly</strong></li></ul><pre>let result = Number(&quot;12&quot;);<br>console.log(result);  // output: 12</pre><pre>result = Number(&quot;12&quot;) + 1;<br>console.log(result); // output: 13</pre><pre>result = Number(true);<br>console.log(result); // output: 1<br><br>result = Number(false);<br>console.log(result); // output: 0</pre><pre>result = Number(null);<br>console.log(result);  // output: 0<br><br>result = Number(&#39; &#39;)<br>console.log(result);  // output: 0</pre><pre>result = Number(&#39;hello world&#39;);<br>console.log(result); // output: NaN<br><br>result = Number(undefined);<br>console.log(result); // output: NaN<br><br>result = Number(NaN);<br>console.log(result); // output: NaN</pre><ul><li><strong>Convert to Boolean Explicitly</strong></li></ul><pre>let result = Boolean(0);<br>console.log(result); // output: false<br><br>result = Boolean(undefined);<br>console.log(result); // output: false<br><br>result = Boolean(&#39;&#39;);<br>console.log(result); // output: false<br><br>result = Boolean(null);<br>console.log(result); // output: false<br><br>result = Boolean(NaN);<br>console.log(result); // output: false</pre><pre>result = Boolean(1);<br>console.log(result); // output: true</pre><pre>result = Boolean(&quot;true&quot;);<br>console.log(result); // output: true</pre><pre>result = Boolean(&quot;0&quot;);<br>console.log(result); // output: true</pre><pre>result = Boolean(&quot;false&quot;);<br>console.log(result); // output: true</pre><pre>result = Boolean(&quot;hello&quot;);<br>console.log(result); // output: true</pre><pre>result = Boolean({});<br>console.log(result); // output: true</pre><pre>result = Boolean([]);<br>console.log(result); // output: true</pre><p>These are all we need to know about data types and type casting in JavaScript. Meanwhile, please feel free to post any questions, comments, or feedback in the comment section below.</p><p>Follow on Twitter <a href="https://twitter.com/el_dimious/">here</a>!<br>Follow on Github <a href="https://github.com/eldimious">here</a>!</p><h4>See you until next time!</h4><h4>References</h4><ol><li><a href="https://www.programiz.com/javascript/data-types">https://www.programiz.com/javascript/data-types</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures</a></li><li><a href="https://github.com/getify/You-Dont-Know-JS">https://github.com/getify/You-Dont-Know-JS</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5ad3efc79cba" width="1" height="1" alt=""><hr><p><a href="https://medium.com/arconsis/002-javascript-with-dimos-data-types-5ad3efc79cba">#002 JavaScript with Dimos: Data Types</a> was originally published in <a href="https://medium.com/arconsis">arconsis</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[#001 JavaScript with Dimos: Variables and Constants]]></title>
            <link>https://medium.com/arconsis/001-javascript-with-dimos-variables-and-constants-555599d765df?source=rss-4ac6abed8195------2</link>
            <guid isPermaLink="false">https://medium.com/p/555599d765df</guid>
            <category><![CDATA[grammar]]></category>
            <category><![CDATA[scopes]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[declaration]]></category>
            <category><![CDATA[variables]]></category>
            <dc:creator><![CDATA[Dimosthenis Botsaris]]></dc:creator>
            <pubDate>Thu, 12 May 2022 08:13:18 GMT</pubDate>
            <atom:updated>2022-05-12T08:16:13.010Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Hey there 👋 I am </em><a href="https://www.eldimious.com/"><em>Dimos</em></a><em>, a senior software engineer and software architect at </em><a href="https://www.arconsis.com/"><em>arconsis</em></a><em>. From time to time, I publish articles into the series “JavaScript with Dimos”, where I am trying to analyze a JavaScript topic and to focus on the core concepts of JavaScript.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*_HK5qZGiZnvlFz4j2cZIBw.jpeg" /></figure><p>In the chapter “JavaScript’s Grammar” we will take a look at JavaScript’s basic grammar, variable declarations and data types.</p><h4>Chapter’s Posts Roadmap</h4><ul><li>Variables and Constants (This article)</li><li><a href="https://medium.com/arconsis/002-javascript-with-dimos-data-types-5ad3efc79cba">Data Types</a></li></ul><p>Today, in the first article of this chapter, we will explore JavaScript variables and constants, how to initialize and use them and their differences.</p><h3>JavaScript Variables</h3><p>A variable is just a container to <strong>store</strong> data and <strong>hold</strong> its value. For example we can use a variable to store a number, or a string:</p><pre>var str = &#39;Hello!&#39;;</pre><p>In above example, str is a variable we use to store a text.</p><h3>Variable’s Declaration</h3><p>It is essential to know how to declare variables in every programming language. The var, let, and const keywords are used to <strong>declare</strong> variables in JavaScript. There are some significant differences among them which we will analyze later in this tutorial.</p><pre>var x = 1;<br>let y = 2;<br>const z = 3;</pre><h3>Variable’s Initialization</h3><p>We can use the <strong>assignment</strong> operator = in order to initialize a variable and assign it a value. For example:</p><pre>var num = 3;<br>let str = &#39;Hello!&#39;;<br>const isValid = true;<br>let str2;<br>str2 = &#39;Hey!&#39;;</pre><p>In the above example, num was initialized with 3 as the initial value. As we can see, we can declare and initialize a variable at the same time (let str = &#39;Hello!&#39;; ) or we can first declare it (let str2; ) and then initialize it str2 = &#39;Hey!&#39;;.</p><p>JavaScript supports <strong>multiple</strong> variable declaration in a single sentence just like below:</p><pre>let x = 1, y = 2, z = 3;</pre><h3>Variable’s Value Re-assignment</h3><p>In JavaScript, it is possible to <strong>mutate</strong> the variable’s value, like below:</p><pre>let x = 1;<br>console.log(x); // output 1<br>x = 2;<br>console.log(x); // output: 2</pre><pre>var y = &#39;Hello!&#39;;<br>console.log(y); // output: Hello!<br>y = &#39;Hey!&#39;;<br>console.log(y); // output: Hey!</pre><h3>JavaScript <strong>Constants</strong></h3><p>Similar to variables, we can declare <strong>constants</strong> in JavaScript. We can use const statement (was introduced in the ES6 version) to create constants. For example:</p><pre>const x = 1;</pre><p>Constants are similar to variables, apart from:</p><ul><li>declaration and initialization must take place at <strong>same time</strong>.</li><li><strong>cannot</strong> be re-assigned after initialization.</li></ul><p>For example:</p><pre>const x;  // Uncaught SyntaxError: missing = in const declaration<br>x = 1;<br>console.log(x);</pre><pre>const x = 1;<br>x = 3;  // Uncaught TypeError: invalid assignment to const &#39;x&#39;<br>console.log(x);</pre><blockquote>Be careful: Although we <strong>cannot</strong> mutate a constant (applies only to <strong>primitive</strong> values) we can still <strong>mutate</strong> (update, add, or remove) properties of an <strong>object</strong> declared by const. This is possible because the object declared by const is still pointing to the same object, even though its content has been changed.</blockquote><pre>const vehicle = { type : &#39;car&#39;};<br>console.log(vehicle.type);  // output: &quot;car&quot;</pre><pre>vehicle.type = &#39;bike&#39;;<br>console.log(vehicle.type);  // output: &quot;bike&quot;</pre><h3>var statement</h3><p>The var statement defines a <strong>function-scoped</strong> or <strong>globally-scoped</strong> variable (scopes will be discussed in next article). We can assign a value optionally, on variable declared by var. It does <strong>not</strong> support block-level scope, which means that a variable declared inside {…} (for example inside for or if statement) <strong>cannot</strong> be accessed outside the block, which potentially can lead to bugs.</p><pre>var num = 1;</pre><pre>if (num === 1) {<br>    var num = 2;<br>    console.log(x); // output: 2<br>}</pre><pre>console.log(num); // output: 2</pre><p><strong>a) var is function-scoped</strong></p><p><em>Function scope</em> means that variables defined inside a function <strong>cannot</strong> be accessed from anywhere <strong>outside</strong> the function. For example:</p><pre>function foo() {<br>    var x = 1;<br>    function baz() {<br>        var y = 2;<br>        console.log(x); // output: 1 (baz() can see outer scope)<br>        console.log(y); // output: 2<br>    }<br>    baz();<br>    console.log(x); // output: 1 (as x is in same function scope)<br>    console.log(y); // Uncaught ReferenceError: y is not defined<br>}</pre><pre>foo();</pre><p>Another example:</p><pre>var animal = &#39;dog&#39;;</pre><pre>function foo() {<br>    animal = &#39;cat&#39;;<br>    console.log(animal); // output: &quot;cat&quot;<br>}</pre><pre>console.log(animal); // output: &quot;dog&quot;<br>foo();<br>console.log(animal); // output:&quot;cat&quot;</pre><pre>// output: &quot;dog&quot;, &quot;cat&quot;, &quot;cat&quot;</pre><p><strong>b)</strong> <strong>var gets hoisted</strong></p><p>The variables declared by var are processed before any code is executed in a process known as “<a href="https://developer.mozilla.org/en-US/docs/Glossary/Hoisting"><strong>hoisting</strong></a><strong>”</strong> with undefined as initial value. If we declare a variable anywhere in the code using var, is the same as declaring it at the top. Hence a var can appear to be used <strong>before</strong> it’s declared, which is called “<a href="https://developer.mozilla.org/en-US/docs/Glossary/Hoisting"><strong>hoisting</strong></a>”<strong>. </strong>In other words,<strong> </strong>the term “<a href="https://developer.mozilla.org/en-US/docs/Glossary/Hoisting"><strong>hoisting</strong></a>” means that all var and function declarations are “pulled” to the top of the code when the code is run.</p><pre>animal = &#39;dog&#39;;<br>var animal;<br><br>// ...is equivalent (hoisting):<br><br>var animal;<br>animal = &#39;dog&#39;;</pre><pre>console.log(foo); // output: undefined<br>var foo = 1;<br>console.log(foo); // output: 1<br></pre><p>Or another example:</p><pre>function foo() {<br>  console.log(baz); // output: undefined<br>  var baz = 3;<br>  console.log(baz); // output: 3<br>}</pre><pre>// ...is equivalent (hoisting):<br><br>function foo() {<br>  var baz;<br>  console.log(baz); // output: undefined<br>  bar = 3;<br>  console.log(baz); // output: 3<br>}</pre><blockquote><strong>Recommendation</strong>: It’s best to declare variables always at the top of their scope, to be clear which is their scope.</blockquote><p><strong>c)</strong> <strong>var can be re-declared</strong></p><p>Variables declared with var can be <em>re-declared</em> with a new value. For example:</p><pre>var x = 1;<br>console.log(x); // output: 1<br>var x = 3;<br>console.log(x); // output: 3</pre><p><strong>d)</strong> <strong>var can be re-assigned</strong></p><p>Variables declared by var can be <em>re-assigned</em> to a new value. For example:</p><pre>var x = 1;<br>console.log(x); // output: 1<br>x = 3;<br>console.log(x); // output: 3</pre><h3>let statement</h3><p>The let statement was introduced in the ES6 version. The let and the var statements have some similarities but their main difference is that let declares a <strong>block-scoped</strong> variable and although it can be reassigned it <strong>cannot</strong> be <strong>re-declared</strong>. Also compared to var statements, a variable declared using let will <strong>not</strong> be <strong>hoisted</strong>.</p><p><strong>a) let is block-scoped</strong></p><p>Unlike the var keyword, which defines a global or function-scoped variable, the let keyword allows us to define variables that are <strong>block-scoped</strong>. This means that variables are <strong>limited</strong> to the scope of the <strong>block</strong> statement or <strong>expression</strong> on which it is used, as well as in any nested <strong>sub-blocks</strong>.</p><pre>let x = 3;</pre><pre>if (x === 3) {<br>    let x = 6;<br>    console.log(x); // output: 6<br>}</pre><pre>console.log(x); // output: 3</pre><p>Another example:</p><pre>function foo() {<br>    let x = 3;<br>    function baz() {<br>        let x = 6;  // different variable<br>        console.log(x);  // output: 6<br>    }<br>    baz();<br>    console.log(x);  // output: 3<br>}</pre><pre>foo();<br>console.log(x); // output: ReferenceError: x is not defined (defined in function scope, cannot be accessed outer)</pre><p><strong>b)</strong> <strong>let cannot be</strong> <strong>hoisted</strong></p><p>The variables declared by let statement, <strong>cannot</strong> be hoisted and a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ReferenceError">ReferenceError</a> is expected to be thrown, compared to variables declared by var. For example:</p><pre>console.log(x); // Uncaught ReferenceError: can&#39;t access lexical declaration &#39;x&#39; before initialization</pre><pre>let x = 1;</pre><p><strong>c)</strong> <strong>let cannot be re-declared</strong></p><p>If we try to re-declare the same variable by let within the same function or same block, then a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SyntaxError">SyntaxError</a> is expected to be thrown.For example:</p><pre>if (true) {<br>    let x = 1;<br>    let x = 3; // Uncaught SyntaxError: redeclaration of let x<br>}</pre><p>Or another example:</p><pre>function foo() {<br>    let x = 3;<br>    let x = 6; // Uncaught SyntaxError: redeclaration of let x<br>}<br>foo();</pre><p>Also if we combine var and let statements, then it is possible to get a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SyntaxError">SyntaxError</a>, because var is hoisted to the top of the block. As we can see below, the variable declared by var , will introduce re-declaration of x , as is not block-scoped and will be “pulled” on top of the code because of the “hoisting”.</p><pre>let x = 3;<br>{<br>    var x = 5; // Uncaught SyntaxError: redeclaration of let x, Previously declared<br>}</pre><p><strong>d)</strong> <strong>let can be re-assigned</strong></p><p>Variables declared by let keyword can be re-assigned with a new value. For example:</p><pre>let x = 1;<br>console.log(x); // output: 1<br>x = 3;<br>console.log(x); // output: 3</pre><h3>const statement</h3><p>The const keyword and let keyword have a lot of similarities, as both are <strong>blocked</strong> scoped, <strong>cannot</strong> be hoisted and <strong>cannot</strong> be <strong>re-declared</strong>. The only difference is that variables declared by const <strong>cannot</strong> be <strong>reassigned</strong>. Hence, every const variable must be initialized with a value at the time of declaration.</p><p><strong>a) const is block-scoped</strong></p><p>The const statement allows us to define variables that are block-scoped. This means that variables are <strong>limited</strong> to the scope of the <strong>block</strong> statement or <strong>expression</strong> on which it is used, as well as in any contained <strong>sub-blocks</strong>.</p><pre>const x = 3;<br>if (x === 3) {<br>    const x = 6;<br>    console.log(x); // output: 6<br>}<br>console.log(x); // output: 3</pre><p>Or another example:</p><pre>function foo() {<br>    const x = 3;<br>    function baz() {<br>        const x = 6;  // different variable<br>        console.log(x);  // output: 6<br>    }<br>    baz();<br>    console.log(x);  // output: 3<br>}</pre><pre>foo();<br>console.log(x); // output: ReferenceError: x is not defined (defined in function scope, cannot be accessed outer)</pre><p><strong>b)</strong> <strong>const cannot be</strong> <strong>hoisted</strong></p><p>The variables declared by const statement, <strong>cannot</strong> be hoisted and a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ReferenceError">ReferenceError</a> is expected to be thrown, compared to variables declared by var. For example:</p><pre>console.log(x); // Uncaught ReferenceError: can&#39;t access lexical declaration &#39;x&#39; before initialization</pre><pre>const x = 1;</pre><p><strong>c)</strong> <strong>const cannot be re-declared</strong></p><p>If we try to re-declare the same variable by const within the same function or same block , then a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SyntaxError">SyntaxError</a> is expected to be thrown. For example:</p><pre>if (true) {<br>    const x = 1;<br>    const x = 3; // Uncaught SyntaxError: redeclaration of let x<br>}</pre><p>Or another example:</p><pre>function foo() {<br>    const x = 3;<br>    const x = 6; // Uncaught SyntaxError: redeclaration of let x<br>}<br>foo();</pre><p>Also if we combine var and const statements, then it is possible to get a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SyntaxError">SyntaxError</a>, because var is hoisted to the top of the block. As we can see below, the variable declared by var , will introduce re-declaration of x , as is not block-scoped and will be “pulled” on top of the code because of the “hoisting”.</p><pre>const x = 3;<br>{<br>    var x = 5; // Uncaught SyntaxError: redeclaration of let x, Previously declared<br>}</pre><p><strong>d)</strong> <strong>const cannot be re-assigned</strong></p><p>Variables declared by const keyword<strong> cannot</strong> be re-assigned with a new value and a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypeError">TypeError</a> is expected to be thrown. For example:</p><pre>const x = 1;<br>console.log(x); // output: 1<br>x = 3;<br>console.log(x); // output: TypeError: invalid assignment to const &#39;x&#39;</pre><blockquote>Note: If we know that the variable’s value will not change, it’s preferable to use const instead of var or let.</blockquote><p>Those are all we need to know about <strong>variables</strong> and <strong>constants</strong> declaration in JavaScript and their differences. Meanwhile, please feel free to post any questions, comments, or feedback in the comment section below.</p><p>Follow on Twitter <a href="https://twitter.com/el_dimious/">here</a>!<br>Follow on Github <a href="https://github.com/eldimious">here</a>!</p><h4>See you until next time!</h4><h4>References</h4><ol><li><a href="https://www.programiz.com/javascript/variables-constants">https://www.programiz.com/javascript/variables-constants</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_Types">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_Types</a></li><li><a href="https://github.com/getify/You-Dont-Know-JS">https://github.com/getify/You-Dont-Know-JS</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=555599d765df" width="1" height="1" alt=""><hr><p><a href="https://medium.com/arconsis/001-javascript-with-dimos-variables-and-constants-555599d765df">#001 JavaScript with Dimos: Variables and Constants</a> was originally published in <a href="https://medium.com/arconsis">arconsis</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript with Dimos: Intro to Async Functions]]></title>
            <link>https://medium.com/arconsis/javascript-with-dimos-intro-to-async-functions-44697974ae73?source=rss-4ac6abed8195------2</link>
            <guid isPermaLink="false">https://medium.com/p/44697974ae73</guid>
            <category><![CDATA[async]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[async-functions]]></category>
            <category><![CDATA[asyncawait]]></category>
            <category><![CDATA[promises]]></category>
            <dc:creator><![CDATA[Dimosthenis Botsaris]]></dc:creator>
            <pubDate>Mon, 02 May 2022 14:24:44 GMT</pubDate>
            <atom:updated>2022-05-02T14:24:44.933Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Hey there 👋 I am </em><a href="https://www.eldimious.com/"><em>Dimos</em></a><em>, a senior software engineer and software architect at </em><a href="https://www.arconsis.com/"><em>arconsis</em></a><em>. From time to time, I publish articles into the series “JavaScript with Dimos”, where I am trying to analyze a JavaScript topic and to focus on the core concepts of JavaScript.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*TmquvzbkoxMGjS_tkY-fyA.jpeg" /></figure><p><strong>JavaScript</strong> is a <strong>single threaded </strong>language and executes code blocks by order from top to bottom, therefore, it is <strong>synchronous</strong> in nature. Sometimes we may need to use an asynchronous function for example to fetch data from an API. An operation like this takes time to complete, and a blocking approach would negatively impact user experience. <br>Thanks to <strong>JavaScript event loop</strong>, we are able to do <strong>non-blocking</strong> processes by using a callback function and/or a promise function. Using a non-blocking approach we can reduce the JavaScript main thread load and improve our code performance.<br>JavaScript introduced <strong>async</strong> and <strong>await</strong> keywords as an addition to EcmaScript 2015. In this article, we are going to talk about async functions, and how they work.</p><h3>Intro to JavaScript Promises</h3><blockquote>A Promise is a proxy for a value not necessarily known when the promise is created. It allows us to associate handlers with an asynchronous action’s eventual success value or failure reason.</blockquote><p>Therefore, a promise is a special JavaScript <strong>object</strong> which represents a <strong>future result</strong> of an asynchronous action.</p><p><strong>A promise has three states:</strong></p><ol><li><strong>pending</strong> — Initial state which indicates that the request is pending, and is neither fulfilled nor rejected.</li><li><strong>fulfilled</strong> — Indicates that the operation was completed successfully.</li><li><strong>rejected</strong> —Indicates that the operation failed.</li></ol><h3>Intro to async functions</h3><p>The async function is a function that is declared using the async keyword and returns a AsyncFunction object. When we call an async function, it always returns a promise. Hence, async functions allow us to write <strong>promise-based code </strong>(async/await is built on top of promises) <strong>as if it were synchronous</strong>, but <strong>without blocking the main thread</strong>. Below we can find some ways to <strong>declare</strong> async functions:</p><pre>async function functionName(params) {<br>    # code block<br>}</pre><pre>const functionName = async function functionName(params) {<br>    # code block<br>}</pre><pre>const functionName = async (params) =&gt; {<br>    # code block<br>};</pre><p>As we can see, we can declare async functions as every other function. The only difference is the <strong>usage</strong> of the async keyword.</p><p>Below we can find out how we can <strong>call</strong> an async function:</p><pre>try {<br>    const result = await functionName(params)<br>} catch (error) {<br>    console.error(`Async function threw an error: ${error}`)<br>}</pre><p>As we can see above, the execution of an async function is equivalent to execution of a regular synchronous JavaScript function and the only difference is the <strong>usage</strong> of await keyword.</p><h3>How async functions work</h3><p>The await keyword tells JavaScript to “<strong>wait</strong>” until the promise is settled before executing the rest of the code block. So they are simply <em>syntactic sugar</em> for creating functions that return and wait for Promises.<br>The async/await syntax improves readability by letting us write code as synchronously.</p><ul><li>Async function is declared by using the word <strong>async</strong> in their declaration.</li><li>await keyword is permitted within async functions and can only be used <strong>inside</strong> an async function, otherwise we will get Error.</li><li>Always<strong> returns Promises</strong>.</li><li>Code can be “<strong>paused</strong>” waiting using await keyword.</li><li>await returns whatever the async function returns when it is done. It will return<strong> result</strong> if the Promise is fulfilled or will throw an <strong>error</strong> if the Promise is rejected.</li><li>If an async function throws an exception, the exception will bubble up to the parent functions just like in normal JavaScript, and can be caught with try/catch or using .catch() method directly in await asyncFunc.catch(error =&gt; { }) just like in Promises.</li></ul><h4><strong>Fulfilling</strong> the Promise of an async function:</h4><pre>async function asyncFunc() {<br>    return &#39;result&#39;;<br>}</pre><p>which is <em>equivalent to</em>:</p><pre>function asyncFunc() {<br>    return Promise.resolve(&#39;result&#39;);<br>}</pre><p>which is same to:</p><pre>function asyncFunc() {<br>    return new Promise((resolve, reject) =&gt; {<br>        return resolve(&#39;result&#39;);<br>    });<br>}</pre><h4><strong>Rejecting</strong> the Promise of an async function:</h4><pre>async function asyncFunc() {<br>    return Promise.reject(new Error(&#39;We have error!&#39;));<br>}</pre><p>which is equivalent to:</p><pre>async function asyncFunc() {<br>    return Promise.reject(new Error(&#39;We have error!&#39;));<br>}</pre><p>which is same to:</p><pre>async function asyncFunc() {<br>    return new Promise((resolve, reject) =&gt; {<br>        return reject(new Error(&#39;We have error!&#39;));<br>    });<br>}</pre><p>The await keyword is used to handle Promises inside the async function. Therefore, handling <strong>results and errors</strong> of asynchronous computations takes place via await. The operator await “<strong>waits”</strong> for the Promise to be settled. It “pauses” the function until <em>asyncFunc</em> is done (fulfilled or rejected), and returns the result (resolved result or error):</p><ul><li>If the Promise is <strong>fulfilled</strong>, the result of await is the <em>fulfillment value</em>.</li></ul><pre>async function asyncFunc() {<br>    const result = await otherAsyncFunc();<br>    console.log(result);<br>}</pre><pre>// which is equivalent to:<br>function asyncFunc() {<br>    return otherAsyncFunc()<br>    .then(result =&gt; {<br>        console.log(result);<br>    });<br>}</pre><ul><li>If the Promise is <strong>rejected</strong>, await throws the <em>rejection value</em>.</li></ul><pre>async function asyncFunc() {<br>    try {<br>        await otherAsyncFunc();<br>    } catch (err) {<br>        console.error(err);<br>    }<br>}</pre><pre>// which is equivalent to:<br>function asyncFunc() {<br>    return otherAsyncFunc()<br>        .catch(err =&gt; {<br>            console.error(err);<br>        });<br>}</pre><h3>Error Handling</h3><p>An async function has two possible return values: <em>resolved</em> value, and <em>rejected</em> value. We can use <strong>.then()</strong> for normal cases and <strong>.catch()</strong> for exceptional cases. Let’s explore how we handle errors in async functions:</p><h4>1) try…catch statement</h4><p>The most standard way is to use try...catch statement. When await a call, any rejected value will be thrown as an exception. Here is an example:</p><pre>async function asyncFunc() {<br>    try {<br>        await otherAsyncFunc();<br>    } catch (err) {<br>        console.error(err);<br>    }<br>}</pre><p>The error is exactly the rejected value. After we caught the exception, we have <strong>several ways to deal</strong> in catch(err) {…}block with it:</p><ul><li>Handle the exception, and return a <strong>normal value</strong> (not an error). Not using any return statement in the catch block is equivalent to using return undefined; and is a normal value as well. catch(err) { return &#39;fail&#39; }</li><li><strong>Throw error</strong>, if you want the caller to handle the exception. catch (err) { throw err }</li><li><strong>Reject it</strong>, like return Promise.reject(error). This is equivalent to throwing an error. catch (err) { return Promise.reject(err) }</li></ul><h4>2) Using .catch</h4><p>As we declared before, the functionality of await is to “wait” for a promise to be fulfilled or rejected. That’s why we can handle the await otherAsyncFunc as a Promise using then or catch method (as an async function <strong>always returns a Promise</strong>). Therefore we can write error handling like this:</p><pre>function asyncFunc() {<br>    const result = await otherAsyncFunc()<br>        .catch((error) =&gt; { console.log(error); });<br>}</pre><h3>Serial execution of asynchronous functions</h3><p>The below code block runs two asynchronous functions, asyncFunc1() and asyncFunc2( in sequence. The code execution will wait until asyncFunc1() returns (resolved / rejected), via await asyncFunc1() before starting asyncFunc2() execution. Notice that asyncFunc2() does not depend on the result of asyncFunc1() as using of await runs these two functions <strong>sequentially</strong>.</p><pre>async function asyncFunc1() {<br>   return 1;<br>}</pre><pre>async function asyncFunc2() {<br>   return 2;<br>}</pre><pre>(async() =&gt; {<br>    const result1 = await asyncFunc1();<br>    const result2 = await asyncFunc2();<br>})();</pre><p>Below we can see how we can iterate over async iterable arrays sequentially. As we can see there are 2 ways:</p><ul><li>Using <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for-await...of">for await…of</a> statement, which creates a loop <em>iterating</em> over async iterable objects as well as on sync iterables.</li><li>Using <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce">Array.prototype.reduce()</a> method, which executes a <em>reducer</em> function for array elements and returns a single value.</li></ul><pre>const arr = [1, 2, 3, 4, 5];<br><br>async function asyncFunc(item) {<br>    return item;<br>}</pre><pre>(async() =&gt; {<br>    const results = await arr.reduce(async (promise, item) =&gt; {<br>      const accumulator = await promise;<br>      const result = await asyncFunc(item)<br>      return [...accumulator, result]<br>    }, Promise.resolve([]));    <br>    console.log(&#39;results&#39;, results); // Output: [1, 2, 3, 4, 5]<br>})();</pre><pre>// which is equivalent to:<br>(async() =&gt; {<br>    const results = []<br>    for await (const item of arr) {<br>      results.push(await asyncFunc(item));<br>    }<br>    console.log(&#39;results&#39;, results); // Output: [1, 2, 3, 4, 5]<br>})();</pre><h3>Concurrent execution of asynchronous functions</h3><p>As we can see below, using <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all">Promise.all()</a> method we can execute these async functions (asyncFunc1(), asyncFunc2()) <strong>concurrently</strong>. This method combines all the promises and returns a <em>single promise</em>, resolved to an array of the results of the input promises. If one promise throws an error, then Promise.all() will be <strong>rejected</strong> <strong>immediately</strong> with the first rejection message / error.</p><pre>async function asyncFunc1() {<br>   return 1;<br>}</pre><pre>async function asyncFunc2() {<br>   return 2;<br>}</pre><pre>(async() =&gt; {<br>    const results = await Promise.all([asyncFunc1(), asyncFunc2()]);<br>    console.log(results); // Output: [1, 2]<br>})();</pre><p>Below we can see how we can iterate over <em>async iterable arrays</em> <strong>concurrently</strong>. We can combine <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map">Array.prototype.map()</a> built-in array’s method which uses a callback to apply the function over each array’s and returns an array of values, with <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all">Promise.all()</a> method. The <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map">Array.prototype.map()</a> method is a synchronous operation, but combined with async/await leads to an array of promises. The final resolved value is an array of the results of the input promises, and because of using Promise.all() the execution will be rejected immediately, if a promise throws an error.</p><pre>const arr = [1, 2, 3, 4, 5];<br><br>async function asyncFunc(item) {<br>    return item;<br>}<br><br>(async() =&gt; {<br>    const results = await Promise.all(arr.map(async (item) =&gt; {<br>      const res = await asyncFunc(item);<br>      return res;<br>    }));<br>    console.log(&#39;results&#39;, results); // Output: [1, 2, 3, 4, 5]<br>})();</pre><h3>Advantages of async/await</h3><ul><li><strong>Readability: </strong>As we can see from above examples, async/await makes the code cleaner and more readable compared to promises style.</li><li><strong>Error handling: </strong>We can handle both asynchronous and synchronous errors using try/catch.</li></ul><h3>Avoiding common pitfalls</h3><ul><li>Avoid abuse await, when we can execute async calls in <strong>parallel</strong> unless they need to be done synchronously.</li><li>Avoid combining await and return statements together, e.g. await return Promise.resolve(“result”) . Instead we can just return a promise via:return Promise.resolve(“result”) and “await” the promise on execution.</li></ul><h3>Conclusions</h3><ul><li>An<strong> async function always returns Promises</strong>, whether you <strong>use </strong>await<strong> or not</strong>. They are simply <em>syntactic sugar</em> for creating functions that return and wait for Promises.</li><li>If <strong>no </strong>await is present the execution is <strong>not “paused”</strong> and the result of it settling is never handled, as the promise starts its execution when we invoke it. Therefore it synchronously returns a pending promise as didn’t tell JavaScript to “<strong>wait</strong>”.</li><li>The async keyword just declares that the async function returns a value which is guaranteed <strong>to be a promise</strong>, so that callers can call asyncFunc().then(…) or await asyncFunc() safely. Therefore when we use async keyword we create an <strong>asynchronous functions that always return a Promise</strong>.</li><li>We can handle an async function when we call it, exactly <strong>like Promise</strong>.</li><li>await operator &quot;<strong>pauses</strong>&quot; an async function.</li><li>await returns whatever the async function returns when it is done. It will return result if Promise is <strong>fulfilled</strong> or will throw an error if Promise is <strong>rejected.</strong></li><li>Best approach to <strong>handle errors</strong> of an async function is using try...catch statement, but of course we can use .catch() method directly in async function when we call it.</li></ul><p>Those are all we need to know to start using an async function in JavaScript. Meanwhile, please feel free to post any questions, comments, or feedback in the comment section below.</p><p>Follow on Twitter <a href="https://twitter.com/el_dimious/">here</a>!<br>Follow on Github <a href="https://github.com/eldimious">here</a>!</p><h4>Further Reading</h4><ol><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise</a></li><li><a href="https://javascript.info/async">https://javascript.info/async</a></li><li><a href="https://exploringjs.com/impatient-js/ch_async-functions.html">https://exploringjs.com/impatient-js/ch_async-functions.html</a></li><li><a href="https://www.tabnine.com/academy/javascript/how-to-use-asynchronous-functions/">https://www.tabnine.com/academy/javascript/how-to-use-asynchronous-functions/</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=44697974ae73" width="1" height="1" alt=""><hr><p><a href="https://medium.com/arconsis/javascript-with-dimos-intro-to-async-functions-44697974ae73">JavaScript with Dimos: Intro to Async Functions</a> was originally published in <a href="https://medium.com/arconsis">arconsis</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>