<?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 Sara on Medium]]></title>
        <description><![CDATA[Stories by Sara on Medium]]></description>
        <link>https://medium.com/@tibbz?source=rss-30e6de4cf970------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*iWWNR5VSvKcAu_MME8ppmw.jpeg</url>
            <title>Stories by Sara on Medium</title>
            <link>https://medium.com/@tibbz?source=rss-30e6de4cf970------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 19:03:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tibbz/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[How to host your own JSON API on GitHub Pages]]></title>
            <link>https://medium.com/@tibbz/how-to-host-your-own-json-api-on-github-pages-8fd8ebf21f5d?source=rss-30e6de4cf970------2</link>
            <guid isPermaLink="false">https://medium.com/p/8fd8ebf21f5d</guid>
            <category><![CDATA[github]]></category>
            <category><![CDATA[github-pages]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Sara]]></dc:creator>
            <pubDate>Thu, 28 Apr 2022 19:40:03 GMT</pubDate>
            <atom:updated>2022-04-28T19:40:03.078Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rJTgCXovFqX7zmTDUbrgEQ.jpeg" /></figure><h3>Hosting your own JSON API on Github, why?</h3><ul><li>It won’t limit your calls per day.</li><li>It will return all data.</li><li>It’s super easy.</li><li>It’s FREE!</li></ul><h4>Here are the steps:</h4><ol><li>First thing you’ll need to do is create a GitHub Pages repository so head on over to GitHub and create one called <em>username</em>.github.io, where <em>username</em> is your GitHub username. <br>Make sure that it matches your username or it won’t work!</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q9IJyNjhva5tXITcFMoLnQ.png" /></figure><p>2. Go to your terminal and clone that repository into a directory of your choosing:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Aoand7DfdOXOsXX1fEgaxA.png" /></figure><p>3. Once it’s been cloned to your computer, enter the project folder:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3diPs1U9T0CoAdHigA_Ylw.png" /></figure><p>4. Add an index.html with a standard “Hello World” message so that you can see it in your browser.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QadFW6me6Q70XbdYwQGqXg.png" /></figure><p>5. Add, commit, and push your changes!</p><p>6. After that, open up your browser and go to <em>username.github.io</em> to see the text from your index.html file!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*U8mJiLD0bPO9CKUMMTV70g.png" /></figure><p>7. Create a new folder within your project (I called mine Data) and put your JSON file in it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vfOevamf3oFlg7OqYuV8tw.png" /></figure><p>8. Head back on over to your browser and go to your URL with the file path to the data added to it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s2-ynGi3SnOapxeOsCyxHA.png" /></figure><blockquote>Extra tip:</blockquote><blockquote>To see your JSON better, this <a href="https://chrome.google.com/webstore/detail/jsonvue/chklaanhfefbnpoihckbnefhakgolnmc?hl=en">Chrome extension</a> will do the job :)</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KC6-auUF3PoML4jH9xkKuw.png" /></figure><p>Now you have a publicly hosted API!</p><p>To access this information in your back end all you need to do is make an API call like you normally would, parse that data, then iterate through it to seed your database.</p><p>Source: <a href="https://pages.github.com/">https://pages.github.com/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8fd8ebf21f5d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript ES6: A crash course on modern JS]]></title>
            <link>https://medium.com/@tibbz/javascript-es6-a-crash-course-on-modern-js-8f7f06ddb82f?source=rss-30e6de4cf970------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f7f06ddb82f</guid>
            <category><![CDATA[javascript-es6-map]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[javascript-development]]></category>
            <category><![CDATA[javascript-es6]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Sara]]></dc:creator>
            <pubDate>Sun, 24 Apr 2022 22:32:05 GMT</pubDate>
            <atom:updated>2022-04-24T22:32:05.155Z</atom:updated>
            <content:encoded><![CDATA[<p>Summary — updated April 2022</p><h3>Babel</h3><p>One of the biggest changes from ES5 is that <strong>ES7 JavaScript</strong> is <strong>not</strong> able to be <strong>compiled directly in browsers</strong>. We need to use a transpiler called Babel.js to produce compatible JavaScript that the older browsers can read.</p><blockquote><em>Babel allows you to use ES6 features and syntax in your project and then translates it to ES5 so that you can use it in production.</em></blockquote><blockquote><em>Read: </em><a href="https://medium.com/@sara_gallardo/use-babel-once-your-project-is-built-e1ac01f2ee06"><em>How to: use Babel once your project is built</em></a><em>.</em></blockquote><h3>The Most Important ES2016 Updates</h3><h3>The most important ES2016 updates</h3><ul><li><strong>ES6</strong> — <a href="#639e">Array.prototype.includes( )</a>: .includes( )</li><li><strong>ES6</strong> — <a href="#11a3">The exponential operator</a>:**</li><li><strong>ES6 </strong>— latest update: <a href="#82cb"><strong>.map</strong></a><strong>: </strong>Map</li><li><strong>ES6</strong> — latest update:<a href="#8790"><strong> set</strong></a><strong>: </strong>Set</li><li><strong>ES6</strong> — latest update: <a href="#3370"><strong>Block-Scoped Let and Const</strong></a><strong>: </strong><em>let</em><strong> </strong><em>const</em></li><li><strong>ES6 </strong>— latest update: <a href="#d7d9"><strong>Arrow functions</strong></a><strong>: </strong>=&gt;</li><li><strong>ES6</strong> — latest update: <a href="#d87e"><strong>Classes</strong></a><strong>: </strong>class</li><li><strong>ES6</strong> — latest update: <a href="#7373"><strong>Template Literals</strong></a><strong>: </strong>${ }</li><li><strong>ES6</strong>- <a href="#3d3b">Other updates with <strong>ES6</strong></a></li><li><strong>ES6 </strong>— <em>deprecated : </em><a href="#3782"><strong><em>generators</em></strong></a><strong><em>: </em></strong><em>.next() </em>function*</li><li><strong>ES6</strong> — <a href="#https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Deprecated_and_obsolete_features">Other deprecated and obsolete features</a></li></ul><h4>ES6 — Array.prototype.includes( )</h4><p>The .includes( ) method makes it easier for you to check if particular values are stored in an array. In the past, JavaScript developers had to use indexOf and create a new function. But .include( ) will return true if an array includes an element and false if it does not. Take a look below to see it in action.</p><blockquote>let array = [1,3,5,9];<br>console.log(array.<strong>includes(</strong>4<strong>)</strong>);<br>// true<br>console.log(array.<strong>includes(</strong>5<strong>)</strong>);<br>// false</blockquote><h4>ES6 — The exponential operator</h4><p>The exponential operator simplifies the way we do math in JavaScript.</p><blockquote>In the past, we had to use loop, recursive functions, or Math.pow( ), which could get pretty messy with each concatenation.</blockquote><blockquote>console.log(2**2);<br>console.log(2**3);</blockquote><h3>ES6 — latest update: .map</h3><p>Before ES6, JavaScript developers used objects to map keys to values, but using an object as a map has some restrictions:</p><ul><li>There’s no dependable way to iterate over keys</li><li>The keys() method converts fields to strings, which creates key collision</li><li>There’s no simple way to add new keys and new values</li></ul><p>These issues were addressed in the ES6 release when the Map collection type was introduced. It can <strong>hold key-value pairs</strong> of any type and can remember <strong>key insertion order</strong>. Any value (objects and primitives) can be used as a key or a value.</p><p>JavaScript Map creates a new array, which contains the results from the iteration over the elements of the array and calls the provided function once for each element in order.</p><p>To create a new Map, follow this syntax:</p><pre>let map = new Map([iterable]);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FA7JQJuOVcBbud7CsjrooA.png" /><figcaption>JavaScript map syntax</figcaption></figure><blockquote>Description:<br><strong>· array:</strong> the array on which the specific function is called<br><strong>· map:</strong> the method called for the array with the required parameters<br><strong>· function(currentValue, index, arr):</strong> the function with its parameters, which is required to run for each element in the array<br> <strong>· currentValue:</strong> the value of the current element<strong> <br> · index:</strong> the index of the current element<br> <strong>· arr:</strong> the array object on which the <em>map()</em> is called<br><strong>· thisValue:</strong> the value used as the function’s <em>this</em> value when it’s executed</blockquote><blockquote><em>//creating an array<br>let an_array = [5, 3, 1, 4, 2]<br>//map calls a function with “item” as parameter<br>//map will pass each element of an_array as “item” in this function<br>//the function will triple each element passed and return it as the return value<br>result = an_array.map(function(item) {<br>return item*3;<br>});<br>//new list will print with the tripled values<br>console.log(result);</em></blockquote><h4>Return a value mapped to a specific key</h4><blockquote>userRoles.<strong>get</strong>(robin); // actress</blockquote><h4>Return a boolean value showing whether a specified key exists</h4><blockquote>userRoles.<strong>has</strong>(emma); // false<br>userRoles.<strong>has</strong>(ruby); // true</blockquote><h4>Return the number of entries in the map</h4><blockquote>console.log(userRoles.<strong>size</strong>); // 4</blockquote><h4>Return a new iterator object that includes the value of each element</h4><blockquote>for (let role of userRoles.<strong>values()</strong>) {<br>console.log(role);<br>}<br>// director<br>// producer<br>// writer<br>// actress</blockquote><h4>Remove specified elements from map object</h4><blockquote>userRoles.<strong>delete</strong>(ruby);</blockquote><h4>Remove all elements in map object</h4><blockquote>userRoles.<strong>clear</strong>();<br>console.log(userRoles.size); // 0</blockquote><h3>ES6 — Advanced map concepts</h3><p>JavaScript Map is a valuable collection type that makes programming with JavaScript cleaner and more efficient. <br>Some recommended concepts to cover next are:</p><ul><li>Metaprogramming</li><li>Prototypal inheritance</li><li>Implementing constructors</li><li>Literals</li></ul><h3>ES6 — latest update: set</h3><p>A <strong>JavaScript set</strong> is a collection of unique elements that can be traversed in the same order in which they were inserted.</p><blockquote><em>A set can store primitive or object values​.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*AwwXWTSAuCUrrxswpD0rEw.png" /></figure><blockquote>var example_set = new <strong>Set</strong>([“apple”,”bannana”,”mango”,”kiwi”]);<br>console.log(example_set)</blockquote><p>There are various methods and properties implemented in the Set class. <br>A few of them are described below.</p><ul><li><strong>Set.prototype.size</strong> returns the number of elements in the set.</li></ul><blockquote>// print size of the set<br>console.log(fruits.size)</blockquote><ul><li><strong>Set.prototype.add(val)</strong> adds the new element val at the end of the Set object.</li></ul><blockquote>// add “orange” to fruits.<br>fruits.<strong>add</strong>(“orange”)<br>console.log(fruits.values())</blockquote><ul><li><strong>Set.prototype.delete(val)</strong> deletes the element val from the Set object.</li></ul><blockquote>// remove “kiwi” from fruits.<br>fruits.<strong>delete</strong>(“kiwi”)<br>console.log(fruits.values())</blockquote><ul><li><strong>Set.prototype.clear()</strong> removes all the elements from the set.</li></ul><blockquote>// clear the set<br>fruits.<strong>clear</strong>()<br>console.log(fruits.values())</blockquote><ul><li><strong>Set.prototype.has(val)</strong> returns <em>true</em> if val is present in the Set object.</li></ul><blockquote>// check if fruits contains “apple”<br>console.log(fruits.<strong>has</strong>(“apple”))</blockquote><ul><li><strong>Set.prototype.values()</strong> returns all the values from the Set in the same insertion order.</li></ul><blockquote>console.log(fruits.<strong>values()</strong>)</blockquote><h3>ES6 — latest update: generators</h3><p>From its name, a generator is a <strong>function</strong> that allows you to <strong>generate</strong> one or more values by exiting and re-entering the execution procedure whilst saving its state (context) across multiple calls. To put it in simpler words, a generator is similar to normal functions, but has the ability to continue execution on demand at the point at which it was previously terminated, simply by saving its previous state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*EaxUp7d_eZdeYyzjJwg9-A.png" /></figure><p>There are some syntactic differences between a <strong>normal function</strong> and a <strong>generator</strong>:</p><pre>// Normal Function<br>function normalFunction(params) {<br>  // your logic goes here<br>  return value;<br>}</pre><pre>/* --------------------------------- */</pre><pre>// Generator Function<br>function* generatorFunction(params) {<br>  // your logic<br>  yield value1;</pre><pre>  // your logic<br>  yield value2;</pre><pre>  /*<br>    .<br>    .<br>    .<br>  */</pre><pre>  // your logic<br>  yield valueN;<br>}</pre><p>The first noticeable difference in syntax is that a generator is declared using the function* keyword instead of function. Also, notice how we use the return keyword in a normal function, while we use the yield keyword in a generator function instead, respectively. The yield keyword inside the generator allows us to &#39;return&#39; a value, terminate execution, save the state (context) of the current lexical scope and waits for the next invocation to resume execution at the last termination point.</p><p><strong>note:</strong> In a normal function, you can only execute the return keyword once, which will return a value and terminate the function completely. In a generator, you can use the yield keyword multiple times as much as you want to &#39;return&#39; values on consecutive calls. You can also use the return keyword inside a generator, but leave this discussion for a different day.</p><blockquote>Invocation</blockquote><pre>function normalFunction() {<br>  console.log(&#39;I have been invoked&#39;);<br>}</pre><pre>// invocation<br>normalFunction();</pre><pre>----</pre><pre>I have been invoked</pre><p>In general, you can invoke a normal function by typing the function’s signature followed by a pair of parentheses ().</p><p>Now let’s try to use the same procedure to invoke a generator:</p><pre>function* generatorFunction() {<br>  console.log(&#39;I have been invoked&#39;);<br>  yield &#39;first value&#39;;</pre><pre>  console.log(&#39;resuming execution&#39;);<br>  yield &#39;second value&#39;;<br>}</pre><pre>// does this invoke the generator?<br>generatorFunction();</pre><blockquote>In general, you can invoke a normal function by typing the function’s signature followed by a pair of parentheses <em>()</em>but it’s not on<em>Generator</em>Object case.</blockquote><p>The first and the most important method is called next(), which, from its name, yields the next value from the defined generator. Now lets modify our previous code to actually yield our values:</p><pre>function* generatorFunction() {<br> <em> console.log(&#39;I have been invoked&#39;);</em><br>  yield &#39;first value&#39;;<br>  <em>console.log(&#39;resuming execution&#39;);</em><br>  yield &#39;second value&#39;;<br>}</pre><pre>// store the Generator Object in a variable<br>let foo = generatorFunction();</pre><pre>// execute until we yield the first value<br><em>console.log(foo.</em><strong><em>next</em></strong><em>());</em><br>// resume execution until we yield the second value<br><em>console.log(foo.</em><strong><em>next</em></strong><em>());</em><br>// execute until the function ends<br><em>console.log(foo.</em><strong><em>next</em></strong><em>());</em></pre><pre>----</pre><pre>I have been invoked<br>{ value: &#39;first value&#39;, done: false }<br>resuming execution<br>{ value: &#39;second value&#39;, done: false }</pre><pre>{ value: undefined, done: true }</pre><p>When calling the first foo.next() method, the generator began to execute until it hit the first yield keyword and stops the execution. This is reflected in the first two lines of the output. Notice how the foo.next() returned an Object instead of the actual yielded value. This Object should always contain the following properties:</p><ul><li>‘value’: which holds the current yielded value from the generator.</li><li>‘done’: a boolean flag which indicates whether the generator execution has reached the end or not.</li></ul><h3>ES6 — latest update: Block-Scoped Let and Const</h3><p>ES6 introduced the keywords let and const that enable us to declare variables much easier. Previously, variables declared with var are function scoped, so if we declare them inside a for loop they will be available outside of the loop.</p><blockquote>Variables declared with let and const are block-scoped, which means they are only accessible within the block where they were declared. So, if we declare a variable with let, it does not change its value in the outer scope. Const is similar, but the value of variables declared with this keyword cannot change through reassignment.</blockquote><blockquote><em>// using `var`<br>var y = “global”;</em></blockquote><blockquote><em>if (y === “global”) {<br> var y= “block-scoped”;</em></blockquote><blockquote><em>console.log(y);<br> // expected output: block-scoped<br>}</em></blockquote><blockquote><em>console.log(y);<br>// expected output: block-scoped</em></blockquote><blockquote>// using `let`<br><strong>let</strong> x = “global”;</blockquote><blockquote>if (x === “global”) {<br><strong> let</strong> x = “block-scoped”;</blockquote><blockquote>console.log(x);<br> // expected output: block-scoped<br>}</blockquote><blockquote>console.log(x);<br>// expected output: global</blockquote><p>There is no hard-and-fast rule about <strong>when to use which variables</strong>. Here are <strong>two different opinions</strong> from popular JavaScript developers on how to use these three variables.</p><blockquote><strong><em>From Mathias Bynes:</em></strong><em> Use </em><em>const by default and </em><em>let if rebinding is needed. </em><em>var should never be used in ES6.</em></blockquote><blockquote><strong><em>From Kyle Simpson:</em></strong><em> Use </em><em>var for top-level variables that are shared across many scopes. Use </em><em>let for smaller scopes.</em></blockquote><h3>ES6 — latest update: Arrow functions</h3><p>ES6 introduced arrows (=&gt;) as a shorthand way to <strong>declare functions</strong>. This update has three notable advantages:</p><ul><li>You no longer have to use .bind( ) method</li><li>Code is much cleaner and less verbose</li><li>You can skip the explicit return</li></ul><blockquote>var greeting = (name) =&gt; {<br>console.log(`hello ${name}`);<br>}</blockquote><blockquote>There are some cases where you will want to avoid using arrow functions. You need to be careful when using it alongside the this keyword. Now, when you use the arrow function, the this keyword is inherited from the parent scope.</blockquote><h3>ES6 — latest update: Classes</h3><p>The updates to classes in ES6 do not introduce a new OO inheritance model. Instead, these classes are “syntactical sugar” to support prototype inheritance. This update is useful because it simplified your code without changing the basic model of JavaScript. It’s essentially a nicer, cleaner way of doing inheritance. You can create a class in two ways:</p><ul><li>class declaration</li><li>class expression</li></ul><p>You will need the method constructor to create a class.</p><blockquote>class Person {<br> constructor(name, age){<br> this.name = name;<br> this.age = age;<br> }<br> greet(){<br> console.log(`My name is ${this.name} and I am ${this.age} years old` );<br> } // no commas in between methods<br>}</blockquote><blockquote>const sarah = new Person(“Sarah”,35);</blockquote><blockquote>sarah.greet();</blockquote><h3>ES6 — latest update: Template Literals</h3><p>ES6 implemented the useful feature of template strings, now called template literals. This allows you to easily implement variables with a very simple syntax (${ }) and embed expressions.</p><p>It’s particularly useful for constructing API requests and nesting templates.</p><ul><li>The template literal syntax is enclosed in backticks.</li><li>The syntax placeholders in template literals use ${expression}</li></ul><blockquote>let name = “Sarah”;<br>const greeting = `Hello my name is <strong>${</strong>name<strong>}</strong>`;<br>console.log(greeting);</blockquote><h3>ES6 — Other updates with ES6</h3><ul><li>Additional String Methods</li><li>Destructuring</li><li>Array Improvements</li><li>Symbols</li><li>Promises</li><li>Default function arguments i.e. default parameters and default values</li><li>Generator</li><li>Proxies</li><li>Object literal updates</li><li>Sets, WeakSets, Maps, and WeakMaps</li></ul><p>Last updated: April 2022</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f7f06ddb82f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript ES7: A crash course on modern JS]]></title>
            <link>https://medium.com/@tibbz/javascript-es7-a-crash-course-on-modern-js-30820c712792?source=rss-30e6de4cf970------2</link>
            <guid isPermaLink="false">https://medium.com/p/30820c712792</guid>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[javascript-development]]></category>
            <category><![CDATA[javascriptes7]]></category>
            <dc:creator><![CDATA[Sara]]></dc:creator>
            <pubDate>Sun, 24 Apr 2022 22:26:36 GMT</pubDate>
            <atom:updated>2022-04-24T22:26:36.470Z</atom:updated>
            <content:encoded><![CDATA[<p>Summary — updated April 2022</p><h3>Babel</h3><p>One of the biggest changes from ES5 is that <strong>ES7 JavaScript</strong> is <strong>not</strong> able to be <strong>compiled directly in browsers</strong>. We need to use a transpiler called Babel.js to produce compatible JavaScript that the older browsers can read.</p><blockquote><em>Babel allows you to use ES6 features and syntax in your project and then translates it to ES5 so that you can use it in production.</em></blockquote><blockquote><em>Read: </em><a href="https://medium.com/@sara_gallardo/use-babel-once-your-project-is-built-e1ac01f2ee06"><em>How to: use Babel once your project is built</em></a><em>.</em></blockquote><h3>The Most Important ES2017 Updates</h3><ul><li><strong>ES7 </strong>— <a href="#b066">Object.entires( ) and Object.values( )</a>: Object.values( ) Object.entries( )</li><li><strong>ES7 </strong>— <a href="#5ad4">Async and Await</a>: .await( )</li><li><strong>ES7</strong> — latest update: <a href="#25de"><strong>async/await</strong></a><strong>: </strong>async await</li></ul><h3>ES7 — Object.entires( ) and Object.values( )</h3><p>Object.values( ) enables us to return an array of all the values of our Object, and Object.entries( ) returns an array that contains both keys and values.</p><blockquote>These are two new ways of accessing our objects, resolving some of the limitations of Object.keys( ), which return only the keys of the object.</blockquote><blockquote>const family = { father: “John Smith”, <br> mother: “Martha Smith”, <br>daughter: “Sarah Kent”, <br>} <br>console.log(Object.values(family)); <br>console.log(Object.entries(family)); <br>// [“father”, “John Smith”] <br>// [“mother”, “Martha Smith”] <br>// [“daughter”, “Sarah Smith”]</blockquote><h3>ES7 — Async and Await</h3><p>The .await( ) operator waits for a Promise inside the async function. Take a look at the new way of writing this code.</p><blockquote>This ES8 update offers an alternative to callbacks and Promise and uses much more manageable syntax. The Async function allows us to define an asynchronous function and return a Promise.</blockquote><blockquote>function resolveAfter2Seconds() {<br> return new Promise(resolve =&gt; {<br> setTimeout(() =&gt; {<br> resolve(‘resolved’);<br> }, 2000);<br> });<br>}</blockquote><blockquote>async function asyncCall() {<br> console.log(‘calling’);<br> const result =<strong> await</strong> resolveAfter2Seconds();<br> console.log(result);<br>}</blockquote><blockquote>asyncCall();</blockquote><ul><li>We make an async function with the async keyword</li><li>This will return a Promise</li><li>If we specify to return non-promise, it returns a value wrapped inside a Promise</li><li>The await keyword only works inside an async function</li></ul><h3>ES7 — latest update: async/await</h3><p><strong>Async/await</strong> helps with writing completely synchronous-looking code while performing asynchronous tasks.</p><p>await is used to wait for a promise to resolve or reject, and can only be used inside an asynchronous function.</p><blockquote>// The menu<br>var menu = [‘Hamburger’, ‘Chicken Soup’, ‘Pasta’];</blockquote><blockquote>// The following function returns a promise that resolves if the customer<br>// orders something from the menu:<br><strong>function</strong> order_food<strong> (</strong>order<strong>) {</strong><br> let <strong>promise</strong> = new Promise((resolve, reject) =&gt; { <br> if(menu.includes(order)) { <br><strong> resolve(); </strong><br> }else { <br><strong> reject(</strong>‘This item is not on the menu.’<strong>); </strong><br> } <br>});<br> <strong>return</strong> promise;<br>}</blockquote><blockquote>// The following function returns a promise that resolves if the customer<br>// pays 20 or more for the food:<br>function make_payment (payment) {<br> let promise = new Promise((resolve, reject) =&gt; { <br> if(payment &gt;= 20) { <br> resolve(); <br> }else { <br> reject(‘Your order costs 20.’); <br> } <br>});<br> return promise;<br>}</blockquote><blockquote>// await can only be used inside an async function<br><strong>async</strong> function eat(order, payment){<br> // waiting for the promises to resolve<br> try{<br> <strong>await</strong> order_food(order);<br> console.log(“Order received by the customer.”);<br> console.log(“Collect payment.”);<br><strong> await</strong> make_payment(payment);<br> console.log(“Payment received.”);<br> }<br> // Catching errors or rejected promises<br> catch (error){<br> console.log(error)<br> }<br>}</blockquote><blockquote>// Customer places his/her order and specifies the amount to pay<br>// Play around with these parameters to fully understand what is going on.<br>eat(“Hamburger”, 20);</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30820c712792" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript ES8]]></title>
            <link>https://medium.com/@tibbz/javascript-es8-dea21f84af95?source=rss-30e6de4cf970------2</link>
            <guid isPermaLink="false">https://medium.com/p/dea21f84af95</guid>
            <category><![CDATA[javascriptes8]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[javascript-development]]></category>
            <dc:creator><![CDATA[Sara]]></dc:creator>
            <pubDate>Sun, 24 Apr 2022 22:17:38 GMT</pubDate>
            <atom:updated>2022-04-24T22:26:56.675Z</atom:updated>
            <content:encoded><![CDATA[<h3>JavaScript ES8: A crash course on modern JS</h3><p>Summary — updated April 2022</p><h3>Babel</h3><p>One of the biggest changes from ES5 is that <strong>ES6 JavaScript</strong> is <strong>not</strong> able to be <strong>compiled directly in browsers</strong>. We need to use a transpiler called Babel.js to produce compatible JavaScript that the older browsers can read.</p><blockquote><em>Babel allows you to use ES6 features and syntax in your project and then translates it to ES5 so that you can use it in production.</em></blockquote><blockquote><em>Read: </em><a href="https://medium.com/@sara_gallardo/use-babel-once-your-project-is-built-e1ac01f2ee06"><em>How to: use Babel once your project is built</em></a><em>.</em></blockquote><h3>The Most Important ES2018 Updates</h3><ul><li><strong>ES8 </strong>— <a href="https://medium.com/@sara_gallardo/javascript-es7-6-tutorial-a-crash-course-on-modern-js-753b8086c7c1#5a13">Rest / Spread for Objects</a></li><li><strong>ES8 </strong>— <a href="https://medium.com/@sara_gallardo/javascript-es7-6-tutorial-a-crash-course-on-modern-js-753b8086c7c1#aa33">Asynchronous Iteration</a></li><li><strong>ES8 </strong>— <a href="https://medium.com/@sara_gallardo/javascript-es7-6-tutorial-a-crash-course-on-modern-js-753b8086c7c1#d2ab">Other updates from ES8</a></li></ul><h3>ES8 — Rest / Spread for Objects</h3><p>This feature builds off of updates from ES6 so we can use rest/spread syntax for objects. The spread operator enables us to create a clone of an Object so we can modify the original more easily.</p><blockquote><em>This feature should not be used at the end, or it will result in an error.</em></blockquote><blockquote><em>let myObj = {<br>a:1,<br>b:3,<br>c:5,<br>d:8,<br>}</em></blockquote><blockquote><em>// we use the rest operator to grab everything else left in the object.<br>let { a, b, …z } = myObj;<br>console.log(a); // 1<br>console.log(b); // 3<br>console.log(z); // {c: 5, d: 8}</em></blockquote><blockquote><em>// using the spread syntax we cloned our Object<br>let clone = { …myObj };<br>console.log(clone);<br>// {a: 1, b: 3, c: 5, d: 8}<br>myObj.e = 15;<br>console.log(clone)<br>// {a: 1, b: 3, c: 5, d: 8}<br>console.log(myObj)<br>// {a: 1, b: 3, c: 5, d: 8, e: 15}</em></blockquote><h3>ES8 — Asynchronous Iteration</h3><p>This update enables you to use await to declare asynchronous loops if the data comes from an asynchronous source. We use the for-await-of to convert the iterables to a <a href="https://www.educative.io/blog/javascript-promises-tutorial">Promise</a>.</p><p>The <a href="https://github.com/tc39/proposal-async-iteration">GitHub documentation</a> explains that “an async iterator is much like an iterator, except that its next() method returns a promise for a { value, done } pair.”</p><blockquote><em>const iterables = [1,2,3];</em></blockquote><blockquote><em>async function test() {<br></em><strong><em>for await</em></strong><em> (const value of iterables) {<br>console.log(value);<br>}<br>}<br>test();<br>// 1<br>// 2<br>// 3</em></blockquote><h3>ES8 — Other updates from ES8:</h3><ul><li>String Padding</li><li>Shared memory and atomics</li><li>Object.getOwnPropertyDescriptors( )</li><li>Trailing commas in function parameter lists and calls</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dea21f84af95" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript ES9: A crash course on modern JS]]></title>
            <link>https://medium.com/@tibbz/javascript-es9-78a197eb9a58?source=rss-30e6de4cf970------2</link>
            <guid isPermaLink="false">https://medium.com/p/78a197eb9a58</guid>
            <category><![CDATA[javascript-es9]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[javascript-development]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Sara]]></dc:creator>
            <pubDate>Sun, 24 Apr 2022 22:12:14 GMT</pubDate>
            <atom:updated>2022-04-24T22:21:24.829Z</atom:updated>
            <content:encoded><![CDATA[<p>Summary — updated April 2022</p><h3>Babel</h3><p>One of the biggest changes from ES5 is that <strong>ES6 JavaScript</strong> is <strong>not</strong> able to be <strong>compiled directly in browsers</strong>. We need to use a transpiler called Babel.js to produce compatible JavaScript that the older browsers can read.</p><blockquote><em>Babel allows you to use ES6 features and syntax in your project and then translates it to ES5 so that you can use it in production.</em></blockquote><blockquote><em>Read: </em><a href="https://medium.com/@sara_gallardo/use-babel-once-your-project-is-built-e1ac01f2ee06"><em>How to: use Babel once your project is built</em></a><em>.</em></blockquote><h3>The Most Important ES2019</h3><ul><li><strong>ES9 </strong>— <a href="https://medium.com/@sara_gallardo/javascript-es7-6-tutorial-a-crash-course-on-modern-js-753b8086c7c1#b08b">Array.prototype.flat</a>: Infinity</li><li><strong>ES9</strong> — <a href="https://medium.com/@sara_gallardo/javascript-es7-6-tutorial-a-crash-course-on-modern-js-753b8086c7c1#4eb1">Symbol.prototype.description</a>: .description</li><li><strong>ES9</strong> — <a href="https://medium.com/@sara_gallardo/javascript-es7-6-tutorial-a-crash-course-on-modern-js-753b8086c7c1#ed93">Changes to Object.fromEntries</a>: Object.fromEntries</li><li><strong>ES9</strong> — <a href="https://medium.com/@sara_gallardo/javascript-es7-6-tutorial-a-crash-course-on-modern-js-753b8086c7c1#99af">Other ES9 features</a></li><li><strong>ES9</strong> — <a href="https://medium.com/@sara_gallardo/javascript-es7-6-tutorial-a-crash-course-on-modern-js-753b8086c7c1#b8fe">Other updates include</a></li></ul><h3>ES9 — Array.prototype.flat</h3><p>This feature essentially flattens an array recursively up to a pre-specified depth. The flat() method makes a new array containing all sub-array elements. Infinity is used to flatten nested arrays.</p><blockquote><em>const letters = [‘a’, ‘b’, [‘c’, ‘d’, [‘e’, ‘f’]]];<br>// default depth of 1<br>console.log(letters.flat());<br>// [‘a’, ‘b’, ‘c’, ‘d’, [‘e’, ‘f’]]</em></blockquote><blockquote><em>// depth of 2<br>console.log(letters.flat(2));<br>// [‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’]</em></blockquote><blockquote><em>// which is the same as executing flat with depth of 1 twice<br>console.log(letters.flat().flat());<br>// [‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’]</em></blockquote><blockquote><em>// Flattens recursively until the array contains no nested arrays<br>console.log(letters.flat(</em><strong><em>Infinity</em></strong><em>));<br>// [‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’]</em></blockquote><h3>ES9 — Symbol.prototype.description</h3><p>The method .description allows you to return an optional description of a Symbol object.<br>Symbol objects can have an optional description used for debugging purposes, and this new update enables you to read that description but does not contain the enclosing Symbol ( ) string.</p><blockquote><em>const me = Symbol(“Sarah”);<br>console.log(me.</em><strong><em>description</em></strong><em>);<br>// “Sarah”</em></blockquote><blockquote><em>console.log(me.toString());<br>// “Symbol(Sarah)”</em></blockquote><h3>ES9 — Changes to Object.fromEntries</h3><p>This method transforms your list of key-value pairs into objects, and we can pass any iterable as an argument of Object.fromEntries.</p><blockquote><em>const keyValueArray = [<br>[‘key1’, ‘value1’],<br>[‘key2’, ‘value2’]<br>]</em></blockquote><blockquote><em>const obj = </em><strong><em>Object.fromEntries</em></strong><em>(keyValueArray);<br>console.log(obj);<br>// {key1: “value1”, key2: “value2”}</em></blockquote><h3>ES9 — Other ES9 Features</h3><ul><li>Lifting template literals restriction</li><li>RegExp features</li><li>Promise.prototype.finally ( )</li></ul><h3>ES9 — Other updates include</h3><ul><li>String.prototype.trimStart( )/ trimEnd( )</li><li>Changes to Array.sort</li><li>Function.prototype.toString( )</li><li>Optional Catch Binding</li></ul><p>Last updated: April 2022</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=78a197eb9a58" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Babel: How to use Babel once your project is built]]></title>
            <link>https://medium.com/@tibbz/use-babel-once-your-project-is-built-e1ac01f2ee06?source=rss-30e6de4cf970------2</link>
            <guid isPermaLink="false">https://medium.com/p/e1ac01f2ee06</guid>
            <category><![CDATA[babeljs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[javascript-development]]></category>
            <category><![CDATA[babel]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <dc:creator><![CDATA[Sara]]></dc:creator>
            <pubDate>Sun, 24 Apr 2022 18:49:36 GMT</pubDate>
            <atom:updated>2022-04-24T22:22:58.824Z</atom:updated>
            <content:encoded><![CDATA[<p>Updated 2022</p><p>One of the biggest changes from ES5 is that <a href="https://medium.com/@sara_gallardo/javascript-es7-6-tutorial-a-crash-course-on-modern-js-753b8086c7c1"><strong>ES6/ES7 JavaScript</strong></a> is not able to be <strong>compiled directly in browsers</strong>. We need to use a transpiler called Babel.js to produce compatible JavaScript that the older browsers can read.</p><blockquote>Babel allows you to use ES6 features and syntax in your project and then translates it to ES5 so that you can use it in production.</blockquote><p>To use Babel when your project is built, you’ll need to add a package.json to your project. This is where all of your dependencies for your project will be held.</p><p>Be sure that you have Node and npm installed (or Node and Yarn installed if you prefer to use Yarn) and then type in the npm init or the yarn init command in your terminal. Answer the questions that come up and the package.json will be pre-filled with those values.</p><p>Use npm/yarn to add babel to your dependencies with the command:</p><pre>npm install --save-dev babel-cli<br>// or<br>yarn add babel-cli --dev</pre><p>You’ll use the scripts field in your package.json to set your build command with Babel. The actual command will differ based upon the folder you are building from and where you want to build to.</p><p>Finally, in the root folder of your project (where the package.json resides), create a .babelrc file. This is a Babel configuration file that will tell Babel to transform your code to ES5. Install the preset with:</p><pre>npm install --save-dev babel-preset-env<br>// or<br>yarn add babel-preset-env --dev</pre><p>And then define it in your .babelrc file:</p><pre>{<br>    “presets”: [“env”]<br>}</pre><p>Now you can run Babel by running your build command. Your destination folder should now look exactly like your origin folder, except that the contents of the destination folder is ES5 code instead of ES6.</p><p>If you happen to use a <strong>JavaScript library</strong> or <strong>framework</strong> like create-react-app, more than likely the <strong>Babel is already configured</strong> for you and you won’t need to worry about it. This is for projects that are created from scratch.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e1ac01f2ee06" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript ES7/6 Tutorial: A crash course on modern JS]]></title>
            <link>https://medium.com/@tibbz/javascript-es7-6-tutorial-a-crash-course-on-modern-js-753b8086c7c1?source=rss-30e6de4cf970------2</link>
            <guid isPermaLink="false">https://medium.com/p/753b8086c7c1</guid>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[javascript-development]]></category>
            <dc:creator><![CDATA[Sara]]></dc:creator>
            <pubDate>Sun, 24 Apr 2022 18:38:09 GMT</pubDate>
            <atom:updated>2022-04-25T08:17:30.702Z</atom:updated>
            <content:encoded><![CDATA[<h3>JavaScript ES6/ES7/ES8/ES9: A crash course on modern JS</h3><p>Summary - updated 2022</p><p>JavaScript was invented on 1997 and became an ECMA standard. ECMAScript is the official language name. ECMAScript versions include ES1, ES2, ES3, ES5, and <a href="https://medium.com/@sara_gallardo/javascript-es6-a-crash-course-on-modern-js-8f7f06ddb82f">ES6</a>, <a href="https://medium.com/@sara_gallardo/javascript-es7-a-crash-course-on-modern-js-30820c712792">ES7</a>, <a href="https://medium.com/@sara_gallardo/javascript-es8-dea21f84af95">ES8</a>, <a href="https://medium.com/@sara_gallardo/javascript-es9-78a197eb9a58">ES9</a>.</p><h3>Babel</h3><p>One of the biggest changes from ES5 is that <strong>ES6 JavaScript</strong> is <strong>not</strong> able to be <strong>compiled directly in browsers</strong>. We need to use a transpiler called Babel.js to produce compatible JavaScript that the older browsers can read.</p><blockquote>Babel allows you to use ES6 features and syntax in your project and then translates it to ES5 so that you can use it in production.</blockquote><blockquote>Read: <a href="https://medium.com/@sara_gallardo/use-babel-once-your-project-is-built-e1ac01f2ee06">How to: use Babel once your project is built</a>.</blockquote><p>Here we will introduce from the latest to the oldest the most important concepts in Javascript:</p><h3>The most important ES2019</h3><ul><li><strong>ES9 </strong>— <a href="#b08b">Array.prototype.flat</a>: Infinity</li><li><strong>ES9</strong> — <a href="#4eb1">Symbol.prototype.description</a>: .description</li><li><strong>ES9</strong> — <a href="#ed93">Changes to Object.fromEntries</a>: Object.fromEntries</li><li><strong>ES9</strong> — <a href="#99af">Other ES9 features</a></li><li><strong>ES9</strong> — <a href="#b8fe">Other updates include</a></li></ul><h3>The most important ES2018 Updates</h3><ul><li><strong>ES8 </strong>— <a href="#5a13">Rest / Spread for Objects</a></li><li><strong>ES8 </strong>— <a href="#aa33">Asynchronous Iteration</a></li><li><strong>ES8 </strong>— <a href="#d2ab">Other updates from ES8</a></li></ul><h3>The most important ES2017 Updates</h3><ul><li><strong>ES7 </strong>— <a href="#b066">Object.entires( ) and Object.values( )</a>: Object.values( ) Object.entries( )</li><li><strong>ES7 </strong>— <a href="#5ad4">Async and Await</a>: .await( )</li><li><strong>ES7</strong> — latest update: <a href="#25de"><strong>async/await</strong></a><strong>: </strong>async await</li></ul><h3>The most important ES2016 updates</h3><ul><li><strong>ES6</strong> — <a href="#639e">Array.prototype.includes( )</a>: .includes( )</li><li><strong>ES6</strong> — <a href="#11a3">The exponential operator</a>:**</li><li><strong>ES6 </strong>— latest update: <a href="#82cb"><strong>.map</strong></a><strong>: </strong>Map</li><li><strong>ES6</strong> — latest update:<a href="#8790"><strong> set</strong></a><strong>: </strong>Set</li><li><strong>ES6</strong> — latest update: <a href="#3370"><strong>Block-Scoped Let and Const</strong></a><strong>: </strong><em>let</em><strong> </strong><em>const</em></li><li><strong>ES6 </strong>— latest update: <a href="#d7d9"><strong>Arrow functions</strong></a><strong>: </strong>=&gt;</li><li><strong>ES6</strong> — latest update: <a href="#d87e"><strong>Classes</strong></a><strong>: </strong>class</li><li><strong>ES6</strong> — latest update: <a href="#7373"><strong>Template Literals</strong></a><strong>: </strong>${ }</li><li><strong>ES6</strong>- <a href="#3d3b">Other updates with <strong>ES6</strong></a></li><li><strong>ES6 </strong>—Almost <em>deprecated : </em><a href="#3782"><strong><em>generators</em></strong></a><strong><em>: </em></strong><em>.next() </em>function*</li><li><strong>ES6</strong> — <a href="#https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Deprecated_and_obsolete_features">Other deprecated and obsolete features</a></li></ul><h3>The most important ES2019 updates</h3><h3><strong>ES9 </strong>— Array.prototype.flat</h3><p>This feature essentially flattens an array recursively up to a pre-specified depth. The flat() method makes a new array containing all sub-array elements. Infinity is used to flatten nested arrays.</p><blockquote>const letters = [‘a’, ‘b’, [‘c’, ‘d’, [‘e’, ‘f’]]];<br>// default depth of 1<br>console.log(letters.flat());<br>// [‘a’, ‘b’, ‘c’, ‘d’, [‘e’, ‘f’]]</blockquote><blockquote>// depth of 2<br>console.log(letters.flat(2));<br>// [‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’]</blockquote><blockquote>// which is the same as executing flat with depth of 1 twice<br>console.log(letters.flat().flat());<br>// [‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’]</blockquote><blockquote>// Flattens recursively until the array contains no nested arrays<br>console.log(letters.flat(<strong>Infinity</strong>));<br>// [‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’]</blockquote><h3>ES9 — Symbol.prototype.description</h3><p>The method .description allows you to return an optional description of a Symbol object. <br>Symbol objects can have an optional description used for debugging purposes, and this new update enables you to read that description but does not contain the enclosing Symbol ( ) string.</p><blockquote>const me = Symbol(“Sarah”);<br>console.log(me.<strong>description</strong>);<br>// “Sarah”</blockquote><blockquote>console.log(me.toString());<br>// “Symbol(Sarah)”</blockquote><h3>ES9 — Changes to Object.fromEntries</h3><p>This method transforms your list of key-value pairs into objects, and we can pass any iterable as an argument of Object.fromEntries.</p><blockquote>const keyValueArray = [<br> [‘key1’, ‘value1’],<br> [‘key2’, ‘value2’]<br>]</blockquote><blockquote>const obj = <strong>Object.fromEntries</strong>(keyValueArray);<br>console.log(obj);<br>// {key1: “value1”, key2: “value2”}</blockquote><h3>ES9 — Other ES9 Features</h3><ul><li>Lifting template literals restriction</li><li>RegExp features</li><li>Promise.prototype.finally ( )</li></ul><h3><strong>ES9</strong> — Other updates include</h3><ul><li>String.prototype.trimStart( )/ trimEnd( )</li><li>Changes to Array.sort</li><li>Function.prototype.toString( )</li><li>Optional Catch Binding</li></ul><h3>ES8 — Rest / Spread for Objects</h3><p>This feature builds off of updates from ES6 so we can use rest/spread syntax for objects. The spread operator enables us to create a clone of an Object so we can modify the original more easily.</p><blockquote>This feature should not be used at the end, or it will result in an error.</blockquote><blockquote>let myObj = {<br> a:1,<br> b:3,<br> c:5,<br> d:8,<br>}</blockquote><blockquote>// we use the rest operator to grab everything else left in the object.<br>let { a, b, …z } = myObj;<br>console.log(a); // 1<br>console.log(b); // 3<br>console.log(z); // {c: 5, d: 8}</blockquote><blockquote>// using the spread syntax we cloned our Object<br>let clone = { …myObj };<br>console.log(clone);<br>// {a: 1, b: 3, c: 5, d: 8}<br>myObj.e = 15;<br>console.log(clone)<br>// {a: 1, b: 3, c: 5, d: 8}<br>console.log(myObj)<br>// {a: 1, b: 3, c: 5, d: 8, e: 15}</blockquote><h3>ES8 — Asynchronous Iteration</h3><p>This update enables you to use await to declare asynchronous loops if the data comes from an asynchronous source. We use the for-await-of to convert the iterables to a <a href="https://www.educative.io/blog/javascript-promises-tutorial">Promise</a>.</p><p>The <a href="https://github.com/tc39/proposal-async-iteration">GitHub documentation</a> explains that “an async iterator is much like an iterator, except that its next() method returns a promise for a { value, done } pair.”</p><blockquote>const iterables = [1,2,3];</blockquote><blockquote>async function test() {<br> <strong>for await</strong> (const value of iterables) {<br> console.log(value);<br> }<br>}<br>test();<br>// 1<br>// 2<br>// 3</blockquote><h3>ES8 — Other changes from ES8:</h3><ul><li>String Padding</li><li>Shared memory and atomics</li><li>Object.getOwnPropertyDescriptors( )</li><li>Trailing commas in function parameter lists and calls</li></ul><h3>The Most Important ES2017 Updates</h3><h3>ES7 — Object.entires( ) and Object.values( )</h3><p>Object.values( ) enables us to return an array of all the values of our Object, and Object.entries( ) returns an array that contains both keys and values.</p><blockquote>These are two new ways of accessing our objects, resolving some of the limitations of <em>Object.keys( )</em>, which return only the keys of the object.</blockquote><blockquote>const family = { father: “John Smith”, <br> mother: “Martha Smith”, <br>daughter: “Sarah Kent”, <br>} <br>console.log(Object.values(family)); <br>console.log(Object.entries(family)); <br>// [“father”, “John Smith”] <br>// [“mother”, “Martha Smith”] <br>// [“daughter”, “Sarah Smith”]</blockquote><h3>ES7 — Async and Await</h3><p>The .await( ) operator waits for a Promise inside the async function. Take a look at the new way of writing this code.</p><blockquote>This ES8 update offers an alternative to callbacks and Promise and uses much more manageable syntax. The Async function allows us to define an asynchronous function and return a Promise.</blockquote><blockquote>function resolveAfter2Seconds() {<br> return new Promise(resolve =&gt; {<br> setTimeout(() =&gt; {<br> resolve(‘resolved’);<br> }, 2000);<br> });<br>}</blockquote><blockquote>async function asyncCall() {<br> console.log(‘calling’);<br> const result =<strong> await</strong> resolveAfter2Seconds();<br> console.log(result);<br>}</blockquote><blockquote>asyncCall();</blockquote><ul><li>We make an async function with the async keyword</li><li>This will return a Promise</li><li>If we specify to return non-promise, it returns a value wrapped inside a Promise</li><li>The await keyword only works inside an async function</li></ul><h3>ES7 — latest update: async/await</h3><p><strong>Async/await</strong> helps with writing completely synchronous-looking code while performing asynchronous tasks.</p><p>await is used to wait for a promise to resolve or reject, and can only be used inside an asynchronous function.</p><blockquote>// The menu<br>var menu = [‘Hamburger’, ‘Chicken Soup’, ‘Pasta’];</blockquote><blockquote>// The following function returns a promise that resolves if the customer<br>// orders something from the menu:<br><strong>function</strong> order_food<strong> (</strong>order<strong>) {</strong><br> let <strong>promise</strong> = new Promise((resolve, reject) =&gt; { <br> if(menu.includes(order)) { <br><strong> resolve(); </strong><br> }else { <br><strong> reject(</strong>‘This item is not on the menu.’<strong>); </strong><br> } <br>});<br> <strong>return</strong> promise;<br>}</blockquote><blockquote>// The following function returns a promise that resolves if the customer<br>// pays 20 or more for the food:<br>function make_payment (payment) {<br> let promise = new Promise((resolve, reject) =&gt; { <br> if(payment &gt;= 20) { <br> resolve(); <br> }else { <br> reject(‘Your order costs 20.’); <br> } <br>});<br> return promise;<br>}</blockquote><blockquote>// await can only be used inside an async function<br><strong>async</strong> function eat(order, payment){<br> // waiting for the promises to resolve<br> try{<br> <strong>await</strong> order_food(order);<br> console.log(“Order received by the customer.”);<br> console.log(“Collect payment.”);<br><strong> await</strong> make_payment(payment);<br> console.log(“Payment received.”);<br> }<br> // Catching errors or rejected promises<br> catch (error){<br> console.log(error)<br> }<br>}</blockquote><blockquote>// Customer places his/her order and specifies the amount to pay<br>// Play around with these parameters to fully understand what is going on.<br>eat(“Hamburger”, 20);</blockquote><h3>The most important ES2016 updates</h3><h3>ES6 — Array.prototype.includes( )</h3><p>The .includes( ) method makes it easier for you to check if particular values are stored in an array. In the past, JavaScript developers had to use indexOf and create a new function. But .include( ) will return true if an array includes an element and false if it does not. Take a look below to see it in action.</p><blockquote>let array = [1,3,5,9];<br>console.log(array.<strong>includes(</strong>4<strong>)</strong>);<br>// true<br>console.log(array.<strong>includes(</strong>5<strong>)</strong>);<br>// false</blockquote><h3>ES6 — The exponential operator</h3><p>The exponential operator simplifies the way we do math in JavaScript.</p><blockquote>In the past, we had to use loop, recursive functions, or Math.pow( ), which could get pretty messy with each concatenation.</blockquote><blockquote>console.log(2**2);<br>console.log(2**3);</blockquote><h3>ES6 — latest update: .map</h3><p>Before ES6, JavaScript developers used objects to map keys to values, but using an object as a map has some restrictions:</p><ul><li>There’s no dependable way to iterate over keys</li><li>The keys() method converts fields to strings, which creates key collision</li><li>There’s no simple way to add new keys and new values</li></ul><p>These issues were addressed in the ES6 release when the Map collection type was introduced. It can <strong>hold key-value pairs</strong> of any type and can remember <strong>key insertion order</strong>. Any value (objects and primitives) can be used as a key or a value.</p><p>JavaScript Map creates a new array, which contains the results from the iteration over the elements of the array and calls the provided function once for each element in order.</p><p>To create a new Map, follow this syntax:</p><pre>let map = new Map([iterable]);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FA7JQJuOVcBbud7CsjrooA.png" /><figcaption>JavaScript map syntax</figcaption></figure><blockquote>Description:<br><strong>· array:</strong> the array on which the specific function is called<br><strong>· map:</strong> the method called for the array with the required parameters<br><strong>· function(currentValue, index, arr):</strong> the function with its parameters, which is required to run for each element in the array<br> <strong>· currentValue:</strong> the value of the current element<strong> <br> · index:</strong> the index of the current element<br> <strong>· arr:</strong> the array object on which the map() is called<br><strong>· thisValue:</strong> the value used as the function’s this value when it’s executed</blockquote><blockquote><em>//creating an array<br>let an_array = [5, 3, 1, 4, 2]<br>//map calls a function with “item” as parameter<br>//map will pass each element of an_array as “item” in this function<br>//the function will triple each element passed and return it as the return value<br>result = an_array.map(function(item) {<br>return item*3;<br>});<br>//new list will print with the tripled values<br>console.log(result);</em></blockquote><h4>Return a value mapped to a specific key</h4><blockquote>userRoles.<strong>get</strong>(robin); // actress</blockquote><h4>Return a boolean value showing whether a specified key exists</h4><blockquote>userRoles.<strong>has</strong>(emma); // false<br>userRoles.<strong>has</strong>(ruby); // true</blockquote><h4>Return the number of entries in the map</h4><blockquote>console.log(userRoles.<strong>size</strong>); // 4</blockquote><h4>Return a new iterator object that includes the value of each element</h4><blockquote>for (let role of userRoles.<strong>values()</strong>) {<br>console.log(role);<br>}<br>// director<br>// producer<br>// writer<br>// actress</blockquote><h4>Remove specified elements from map object</h4><blockquote>userRoles.<strong>delete</strong>(ruby);</blockquote><h4>Remove all elements in map object</h4><blockquote>userRoles.<strong>clear</strong>();<br>console.log(userRoles.size); // 0</blockquote><h3>ES6 — Advanced map concepts</h3><p>JavaScript Map is a valuable collection type that makes programming with JavaScript cleaner and more efficient. <br>Some recommended concepts to cover next are:</p><ul><li>Metaprogramming</li><li>Prototypal inheritance</li><li>Implementing constructors</li><li>Literals</li></ul><h3>ES6 — latest update: set</h3><p>A <strong>JavaScript set</strong> is a collection of unique elements that can be traversed in the same order in which they were inserted.</p><blockquote><em>A set can store primitive or object values​.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/786/1*AwwXWTSAuCUrrxswpD0rEw.png" /></figure><blockquote>var example_set = new <strong>Set</strong>([“apple”,”bannana”,”mango”,”kiwi”]);<br>console.log(example_set)</blockquote><p>There are various methods and properties implemented in the Set class. <br>A few of them are described below.</p><ul><li><strong>Set.prototype.size</strong> returns the number of elements in the set.</li></ul><blockquote>// print size of the set<br>console.log(fruits.size)</blockquote><ul><li><strong>Set.prototype.add(val)</strong> adds the new element val at the end of the Set object.</li></ul><blockquote>// add “orange” to fruits.<br>fruits.<strong>add</strong>(“orange”)<br>console.log(fruits.values())</blockquote><ul><li><strong>Set.prototype.delete(val)</strong> deletes the element val from the Set object.</li></ul><blockquote>// remove “kiwi” from fruits.<br>fruits.<strong>delete</strong>(“kiwi”)<br>console.log(fruits.values())</blockquote><ul><li><strong>Set.prototype.clear()</strong> removes all the elements from the set.</li></ul><blockquote>// clear the set<br>fruits.<strong>clear</strong>()<br>console.log(fruits.values())</blockquote><ul><li><strong>Set.prototype.has(val)</strong> returns <em>true</em> if val is present in the Set object.</li></ul><blockquote>// check if fruits contains “apple”<br>console.log(fruits.<strong>has</strong>(“apple”))</blockquote><ul><li><strong>Set.prototype.values()</strong> returns all the values from the Set in the same insertion order.</li></ul><blockquote>console.log(fruits.<strong>values()</strong>)</blockquote><h3>ES6 — latest update: <strong>generators</strong></h3><p>From its name, a generator is a <strong>function</strong> that allows you to <strong>generate</strong> one or more values by exiting and re-entering the execution procedure whilst saving its state (context) across multiple calls. To put it in simpler words, a generator is similar to normal functions, but has the ability to continue execution on demand at the point at which it was previously terminated, simply by saving its previous state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*EaxUp7d_eZdeYyzjJwg9-A.png" /></figure><p>There are some syntactic differences between a <strong>normal function</strong> and a <strong>generator</strong>:</p><pre>// Normal Function<br>function normalFunction(params) {<br>  // your logic goes here<br>  return value;<br>}<br><br>/* --------------------------------- */<br><br>// Generator Function<br>function* generatorFunction(params) {<br>  // your logic<br>  yield value1;<br><br>  // your logic<br>  yield value2;<br><br>  /*<br>    .<br>    .<br>    .<br>  */<br><br>  // your logic<br>  yield valueN;<br>}</pre><p>The first noticeable difference in syntax is that a generator is declared using the function* keyword instead of function. Also, notice how we use the return keyword in a normal function, while we use the yield keyword in a generator function instead, respectively. The yield keyword inside the generator allows us to &#39;return&#39; a value, terminate execution, save the state (context) of the current lexical scope and waits for the next invocation to resume execution at the last termination point.</p><p><strong>note:</strong> In a normal function, you can only execute the return keyword once, which will return a value and terminate the function completely. In a generator, you can use the yield keyword multiple times as much as you want to &#39;return&#39; values on consecutive calls. You can also use the return keyword inside a generator, but leave this discussion for a different day.</p><blockquote>Invocation</blockquote><pre>function normalFunction() {<br>  console.log(&#39;I have been invoked&#39;);<br>}<br><br>// invocation<br>normalFunction();</pre><pre>----</pre><pre>I have been invoked</pre><p>In general, you can invoke a normal function by typing the function’s signature followed by a pair of parentheses ().</p><p>Now let’s try to use the same procedure to invoke a generator:</p><pre>function* generatorFunction() {<br>  console.log(&#39;I have been invoked&#39;);<br>  yield &#39;first value&#39;;<br><br>  console.log(&#39;resuming execution&#39;);<br>  yield &#39;second value&#39;;<br>}<br><br>// does this invoke the generator?<br>generatorFunction();</pre><blockquote>In general, you can invoke a normal function by typing the function’s signature followed by a pair of parentheses ()but it’s not onGeneratorObject case.</blockquote><p>The first and the most important method is called next(), which, from its name, yields the next value from the defined generator. Now lets modify our previous code to actually yield our values:</p><pre>function* generatorFunction() {<br> <em> console.log(&#39;I have been invoked&#39;);</em><br>  yield &#39;first value&#39;;<br>  <em>console.log(&#39;resuming execution&#39;);</em><br>  yield &#39;second value&#39;;<br>}</pre><pre>// store the Generator Object in a variable<br>let foo = generatorFunction();</pre><pre>// execute until we yield the first value<br><em>console.log(foo.</em><strong><em>next</em></strong><em>());</em><br>// resume execution until we yield the second value<br><em>console.log(foo.</em><strong><em>next</em></strong><em>());</em><br>// execute until the function ends<br><em>console.log(foo.</em><strong><em>next</em></strong><em>());</em></pre><pre>----</pre><pre>I have been invoked<br>{ value: &#39;first value&#39;, done: false }<br>resuming execution<br>{ value: &#39;second value&#39;, done: false }</pre><pre>{ value: undefined, done: true }</pre><p>When calling the first foo.next() method, the generator began to execute until it hit the first yield keyword and stops the execution. This is reflected in the first two lines of the output. Notice how the foo.next() returned an Object instead of the actual yielded value. This Object should always contain the following properties:</p><ul><li>‘value’: which holds the current yielded value from the generator.</li><li>‘done’: a boolean flag which indicates whether the generator execution has reached the end or not.</li></ul><h3>ES6 — latest update: Block-Scoped Let and Const</h3><p>ES6 introduced the keywords let and const that enable us to declare variables much easier. Previously, variables declared with var are function scoped, so if we declare them inside a for loop they will be available outside of the loop.</p><blockquote>Variables declared with let and const are <strong>block-scoped</strong>, which means they are only accessible within the block where they were declared. So, if we declare a variable with let, it does not change its value in the outer scope. Const is similar, but the value of variables declared with this keyword cannot change through reassignment.</blockquote><blockquote><em>// using `var`<br>var y = “global”;</em></blockquote><blockquote><em>if (y === “global”) {<br> var y= “block-scoped”;</em></blockquote><blockquote><em>console.log(y);<br> // expected output: block-scoped<br>}</em></blockquote><blockquote><em>console.log(y);<br>// expected output: block-scoped</em></blockquote><blockquote>// using `let`<br><strong>let</strong> x = “global”;</blockquote><blockquote>if (x === “global”) {<br><strong> let</strong> x = “block-scoped”;</blockquote><blockquote>console.log(x);<br> // expected output: block-scoped<br>}</blockquote><blockquote>console.log(x);<br>// expected output: global</blockquote><p>There is no hard-and-fast rule about <strong>when to use which variables</strong>. Here are <strong>two different opinions</strong> from popular JavaScript developers on how to use these three variables.</p><blockquote><strong><em>From Mathias Bynes:</em></strong><em> Use </em><em>const by default and </em><em>let if rebinding is needed. </em><em>var should never be used in ES6.</em></blockquote><blockquote><strong><em>From Kyle Simpson:</em></strong><em> Use </em><em>var for top-level variables that are shared across many scopes. Use </em><em>let for smaller scopes.</em></blockquote><h3>ES6 — latest update: Arrow functions</h3><p>ES6 introduced arrows (=&gt;) as a shorthand way to <strong>declare functions</strong>. This update has three notable advantages:</p><ul><li>You no longer have to use .bind( ) method</li><li>Code is much cleaner and less verbose</li><li>You can skip the explicit return</li></ul><blockquote>var greeting = (name) =&gt; {<br>console.log(`hello ${name}`);<br>}</blockquote><blockquote>There are some cases where you will want to avoid using arrow functions. You need to be careful when using it alongside the this keyword. Now, when you use the arrow function, the this keyword is inherited from the parent scope.</blockquote><h3>ES6 — latest update: Classes</h3><p>The updates to classes in ES6 do not introduce a new OO inheritance model. Instead, these classes are “syntactical sugar” to support prototype inheritance. This update is useful because it simplified your code without changing the basic model of JavaScript. It’s essentially a nicer, cleaner way of doing inheritance. You can create a class in two ways:</p><ul><li>class declaration</li><li>class expression</li></ul><p>You will need the method constructor to create a class.</p><blockquote>class Person {<br> constructor(name, age){<br> this.name = name;<br> this.age = age;<br> }<br> greet(){<br> console.log(`My name is ${this.name} and I am ${this.age} years old` );<br> } // no commas in between methods<br>}</blockquote><blockquote>const sarah = new Person(“Sarah”,35);</blockquote><blockquote>sarah.greet();</blockquote><h3>ES6 — latest update: Template Literals</h3><p>ES6 implemented the useful feature of template strings, now called template literals. This allows you to easily implement variables with a very simple syntax (${ }) and embed expressions.</p><p>It’s particularly useful for constructing API requests and nesting templates.</p><ul><li>The template literal syntax is enclosed in backticks.</li><li>The syntax placeholders in template literals use ${expression}</li></ul><blockquote>let name = “Sarah”;<br>const greeting = `Hello my name is <strong>${</strong>name<strong>}</strong>`;<br>console.log(greeting);</blockquote><h3>ES6 — Other updates with ES6</h3><ul><li>Additional String Methods</li><li>Destructuring</li><li>Array Improvements</li><li>Symbols</li><li>Promises</li><li>Default function arguments i.e. default parameters and default values</li><li>Generator</li><li>Proxies</li><li>Object literal updates</li><li>Sets, WeakSets, Maps, and WeakMaps</li></ul><p>Last updated: April 2022</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=753b8086c7c1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Javascript tips:]]></title>
            <link>https://medium.com/@tibbz/javascript-tips-ede7f6ca2230?source=rss-30e6de4cf970------2</link>
            <guid isPermaLink="false">https://medium.com/p/ede7f6ca2230</guid>
            <category><![CDATA[javascript-es6]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[javascript-development]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Sara]]></dc:creator>
            <pubDate>Sat, 23 Apr 2022 13:56:20 GMT</pubDate>
            <atom:updated>2022-04-24T22:20:25.447Z</atom:updated>
            <content:encoded><![CDATA[<h3>Javascript tips: best practices to simplify your code</h3><ol><li><a href="#1b39">Declare and initialize your <strong><em>variables</em></strong> <strong>at the top</strong></a><strong>: let / const</strong>.</li><li><a href="#4a6b">Build <strong>modular</strong>, <strong>specialized <em>Functions</em></strong></a>.</li><li><a href="#999c">Recognize and <strong>remove duplicate code</strong></a>.</li><li><a href="#b5ae"><strong>Comment</strong> your code <strong>often</strong></a><strong>: //.</strong></li><li><a href="#c382">Beware of <strong>recursion overuse</strong></a><strong>: 3+level Functions.</strong></li><li><a href="#98bd">Be efficient with <strong><em>DOM</em> manipulations</strong></a><strong>: $.</strong></li><li><a href="#3ca0"><strong>Avoid <em>global variables</em></strong> at all costs</a>.</li><li><a href="#c148">Make use of <strong>shorthand notation (<em>object literals</em>)</strong></a>.</li><li><a href="#3427"><strong>Use <em>Strict Mode</em></strong> to catch silent errors</a>: <strong>‘use strict’.</strong></li><li><a href="#dfbc">Set <strong>default values</strong></a>.</li><li><a href="#c0f6"><strong>Use template literals</strong> to combine strings</a>: <strong>``.</strong></li><li><a href="#0d28">Solve existence testing with <strong><em>includes</em></strong></a><strong><em>: includes( ).</em></strong></li><li><a href="#6fd9">Shorten <strong><em>conditionals</em></strong> with <strong>false values</strong></a><strong>: !.</strong></li><li><a href="#994d">Sharing methods with <strong><em>inheritance</em></strong></a><strong><em>: super( ).</em></strong></li><li><a href="#ffb0">Write shorter loops with array methods</a>: <strong>=&gt;.</strong></li></ol><p><a href="#a8a9">Wrapping up and resources</a>.</p><h3>1. Declare and initialize your <strong><em>variables</em></strong> <strong>at the top: let/const.</strong></h3><p>Nothing disrupts readability like a late declaration. It’s simpler to declare all variables before getting into your function.</p><p>It’s best practice to initialize your variables at the time of creation so you and your team can ensure none are left undefined.</p><pre>&lt;script&gt;<br>let x = 5;<br>&lt;/script&gt;</pre><h3>2. Build <strong>modular</strong>, <strong>specialized <em>Functions</em></strong>.</h3><p>Both for efficiency and readability’s sake, one function should NOT have to do it all. Instead, a single task should accomplish to complete that task only. Name the function to match that task.</p><pre>function table (columns, rows, item){<br>creates table and searches it for the passed item<br>}<br><br>// compared to<br><br>function createTable (columns, rows){<br>//creates table<br>}<br><br>function searchTable (table.length, item) {<br>//searches table for the passed item<br>}</pre><h3>3. Recognize and <strong>remove duplicate code.</strong></h3><p>You should move the duplicated code into a function and call the function in all the instances that it was used before.</p><p>This reduces visual clutter and aids in debugging later as the team can look at the one function rather than its multiple usage sections.</p><pre>&lt;script&gt;<br>let x = 5;<br>let y = 6;<br>let x = x*2<br>let y = y*2<br>&lt;/script&gt;<br><br>&lt;script&gt;<br>let x = 5;<br>let y = 6;<br><br>function double (value){<br>return value*2;<br>}<br>double (x);<br>double(y);<br>&lt;/script&gt;</pre><h3>4. Comment your code often: //.</h3><p>Comments are a great way to summarize a code fragment’s purpose, saving other developers the time to figure them out on their own.</p><p>If you’re unsure if you should leave a comment, just do it! It can always be deleted later if it’s too much clutter.</p><pre>//declares and initializes let x<br>&lt;script&gt;<br>let x = 5;<br>&lt;/script&gt;</pre><h3>5. Beware of recursion overuse: 3+level Functions.</h3><p>To avoid confusion, be mindful of where recursive functions can be pulled out of their nested place without significant runtime cost. Do so whenever possible. If you have 3+ levels of nested functions, chances are your fellow developers will have a hard time following it.</p><pre>function1 (a,b){<br>  function2{<br>    function3{<br>    //this is too hard to follow and can likely be solved another way<br>    }<br>  }<br>}<br>&lt;/script&gt;</pre><h3>6. Be efficient with DOM manipulations: $.</h3><p>Accessing the DOM is essential, but doing so repeatedly causes visual clutter and will slow down the program.</p><p>Instead, access it once and cache it for later use in a variable. From then on, you can access that variable instead of the DOM directly. This process is visually cleaner and more efficient.</p><p><strong><em>Note</em></strong><em>: It’s best practice to mark any DOM reference with the </em><em>$ symbol.</em></p><pre>function accountInfo(){<br>let email = $(&quot;#accounts&quot;).find(&quot;.email&quot;).val();<br>let accountNumber = $(&quot;#accounts&quot;).find(&quot;.accountNumber&quot;).val();<br>}<br><br>// Contents cached to variable &quot;accounts&quot;<br><br>function accountInfo(){ var $accounts = $(&quot;#accounts&quot;); <br>let name = $accounts.find(&quot;.email&quot;).val(); <br>let age = $accounts.find(&quot;.accountNumber&quot;).val();<br>}</pre><pre>const name = accountInfo().name<br>const age = accountInfo().age</pre><pre>//// Even simpler</pre><pre>const accountInfo = () =&gt; {<br>var $accounts = $(&quot;#accounts&quot;); <br>let name = $accounts.find(&quot;.email&quot;).val(); <br>let age = $accounts.find(&quot;.accountNumber&quot;).val();<br>}</pre><pre>const { name, age } = accountInfo()<br></pre><h3>7. Avoid global variables at all costs.</h3><p>If there are a<strong> <em>local variable</em></strong> and a<strong> <em>global variable</em></strong> with the same <strong><em>name</em></strong>, JavaScript will prioritize the local variable and ignore the global variable. Global variables should still be avoided, as they can accidentally overwrite window variables resulting in errors.</p><p>Further, <strong>having many global variables will slow down your program</strong> since <strong>they are not deleted until the window is closed</strong>, whereas local variables are deleted once the function is completed.</p><pre>&lt;html&gt;<br>      &lt;script&gt;<br>            let myVar = &quot;my global variable&quot;; // This variable is declared as global<br>            function localVariable( ) {<br>               let myVar = &quot;my local variable&quot;;  // This is a locally declared variable<br>      &lt;/script&gt;<br>   &lt;/body&gt;<br>&lt;/html&gt;</pre><h3>8. Make use of shorthand notation (Object Literals).</h3><p>When designing objects or arrays in JavaScript, line space can be saved by opting for shorthand notation. This is accomplished by setting the properties or cells of an object or array during declaration rather than after.</p><p>This saves you having to identify which object or array you’re setting for on each line, making the section easier to read. While this may seem like a small change, it can save a lot of eye strain for your team as the objects and arrays get more complex.</p><p><strong>Longhand Object:</strong></p><pre>let computer = new Object();<br>    computer.caseColor = &#39;black&#39;;<br>    computer.brand = &#39;Dell&#39;;<br>    computer.value = 1200;<br>    computer.onSale = true;</pre><p><strong>Shorthand Object:</strong></p><pre>let computer = {<br>    caseColor: &#39;black&#39;;<br>    brand: &#39;Dell&#39;;<br>    value: 1200;<br>    onSale: true;<br>}</pre><p><strong>Shorthand Array:</strong></p><pre>let computerBrands = [<br>&#39;Dell&#39;,<br>&#39;Apple&#39;,<br>&#39;Lenovo&#39;,<br>&#39;HP&#39;,<br>&#39;Toshiba&#39;,<br>&#39;Sony&#39;<br>];</pre><h3>9. Use Strict Mode to catch silent errors: ‘use strict’.</h3><p>JavaScript is a very forgiving language compared to other hardcoded languages like C++ and Java. While helpful for getting code to run without throwing errors, this leniency can lead to silent errors that pass without correction. This can also lead to inconsistent behavior if JavaScript can resolve the silent error in multiple ways.</p><p>To bypass this, opt into <strong>Strict Mode</strong>. This setting makes two major changes:</p><ul><li>Silent errors that would previously make it past the compiler now throw errors, allowing you to fine-tune your code before it reaches your team members.</li><li>Fixes mistakes that prevent JavaScript from optimizing your code</li><li>JavaScript Strict Code programs often run faster than their “sloppy” counterparts</li></ul><p>To opt into strict mode, add the line&#39;use strict&#39;; either at the top of your script section (if you want the whole section to be strict) or before the desired function (if only certain sections should be strict).</p><h3>10. Set default values.</h3><p>When creating objects, you can set default values for some or all properties of the object. Doing so ensures the values of each attribute are not undefined. It also demonstrates what type of data is expected for that attribute. Additionally, by not setting default values for certain properties, you can communicate to your team that those values are not required for the object to function correctly.</p><pre>function logProperty({<br>    address = &#39;111 11th Street, 11111&#39;, <br>    unit,   //optional<br>    landlord = &#39;Sara&#39;, <br>    tenant = &#39;Raj&#39;, <br>    rent = 500, <br>})</pre><p>Above, not all properties will have a unit number, but all will have the other four properties, which are populated with the data type expected. To demonstrate this, we leave unit blank.</p><h3>11. Use template literals to combine strings: ` `.</h3><p>Putting strings together is a pain, especially when combining strings and variables. To make this process simpler, you can use template literals (marked by backticks), which take both a string and variable.</p><pre>function greet(name) {<br>    return `Hi, ${name}`; //template literal<br>}<br>console.log(greet(&#39;Leo&#39;));</pre><p>Notice here that by using the template literal, we can log a greeting to any user based on the name passed to us, combining the string Hi, and the value of the passed variable name. This code therefore prints: Hi, Leo</p><h3>12. Solve existence testing with includes: includes( ).</h3><p>Testing the existence of a value within an array is a common problem. Thankfully, JavaScript comes with a special array method, includes(), which will return a Boolean if the array contains the searched value. Rather than searching the array, this method provides an efficient, easy-to-read solution.</p><pre>const sections = [&#39;contact&#39;, &#39;shipping&#39;];<br> <br>function displayShipping(sections) {<br>    return sections.includes(&#39;shipping&#39;);<br>}<br> <br>console.log(displayShipping(sections));</pre><h3>13. Shorten conditionals with falsy values: !.</h3><p>In JavaScript, there are many values that are equivalent to false across multiple types of variables. This includes:</p><ul><li>the Boolean false</li><li>null</li><li>0</li><li>NaN (not a number)</li><li>&#39; &#39;</li><li>&quot; &quot;</li></ul><p>In JavaScript, equivalent == means that the two objects share the same values, but they may not be the same type. Identical === means that the two objects are both the same type and same value. But how is this useful?</p><p>Well, instead of creating separate variables to hold Booleans, you can instead use the above as default values to report false if nothing overwrites it. Consider this example, you need to check if a given employee has equipment training (equipmentTraining). This machine only requires the lowest level of training, the level of training is unimportant.</p><p>As a result, our if statement checks if equipmentTraining still has a falsy value, the default &#39; &#39;. If it does, the if statement executes and returns that the employee is not authorized. If equipmentTraining contains any string other than the default, it will have a truthy value and therefore not execute the if statement.</p><pre>const employee = {<br>    name: &#39;Eric&#39;,<br>    equipmentTraining: &#39;&#39;,<br>}<br> <br>if (!employee.equipmentTraining) {<br>    console.log(&#39;Not authorized to operate machinery&#39;);<br>}</pre><h3>14. Sharing methods with inheritance: super( );</h3><p>Inheritance concerns a way of sharing properties or methods between classes. This is done using the super tag to allow the constructor in FlashCoupon to access the parent constructor in Coupon. In doing so, you enhance the readability of your code by only defining the methods once (in the parent class). This makes your code to be more modular since inheritor classes can be specialized for a given task.</p><p>Notice that the top code box establishes a parent class, Coupon, the properties and methods of which are shared to FlashCoupon as seen by FlashCoupon calling the getExpirationMessage method on its final line.</p><pre>class Coupon {<br>  constructor(price, expiration) {<br>    this.price = price;<br>    this.expiration = expiration || &#39;Two Weeks&#39;;<br>  }<br>  getExpirationMessage() {<br>    return `This offer expires in ${this.expiration}`;<br>  }<br>}<br>export default Coupon;</pre><pre>import Coupon from &#39;./extend&#39;;</pre><pre>///////////////////////////////////////////////////////////</pre><pre>class FlashCoupon extends Coupon {<br>    constructor(price, expiration) {<br>        super(price);<br>        this.expiration = expiration || &#39;two hours&#39;;<br>    }<br>}<br> <br>const flash = new FlashCoupon(10);<br>console.log(flash.getExpirationMessage());</pre><h3>15. Write shorter loops with array methods: =&gt;</h3><p>Loops are a common way to create and populate arrays. However, they cause a lot of clutter and can be hard to read due to the number of lines required.</p><p>Instead, you can use array methods to accomplish similar effects as for loops with only a fraction of the lines. Take this for loop for example.</p><pre>const prices = [&#39;1.0&#39;, &#39;negotiable&#39;, &#39;2.15&#39;];<br> <br>const formattedPrices = [];<br>for (let i = 0; i &lt; prices.length; i++) {<br>    const price = parseFloat(prices[i]);<br>    if (price) {<br>        formattedPrices.push(price);<br>    }<br>}<br>console.log(formattedPrices);</pre><p>Instead of the above code, we can get the same effect from three lines below by making use of the map method. This method creates an equivalently sized array with only the prices property. We then get float values of that price using the parseFloat.</p><pre>const prices = [&#39;1.0&#39;, &#39;2.15&#39;];<br>const formattedPrices = prices.map(price =&gt; parseFloat(price));<br>console.log(formattedPrices)</pre><h3>Wrapping up and resources</h3><p>The quest for cleaner code is an ongoing journey since best practices are constantly evolving with the language. This process is part of the fun of software development, and learning best practices demonstrates true mastery over a programming language.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ede7f6ca2230" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>