<?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 Piotr Szponder on Medium]]></title>
        <description><![CDATA[Stories by Piotr Szponder on Medium]]></description>
        <link>https://medium.com/@pszponder?source=rss-fb363d427808------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Yw3YtXJy6aUYgeEtMhnwBg.jpeg</url>
            <title>Stories by Piotr Szponder on Medium</title>
            <link>https://medium.com/@pszponder?source=rss-fb363d427808------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 22:59:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@pszponder/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[JavaScript: Functions]]></title>
            <link>https://pszponder.medium.com/javascript-functions-44328c4ed7ab?source=rss-fb363d427808------2</link>
            <guid isPermaLink="false">https://medium.com/p/44328c4ed7ab</guid>
            <dc:creator><![CDATA[Piotr Szponder]]></dc:creator>
            <pubDate>Mon, 09 Aug 2021 22:39:28 GMT</pubDate>
            <atom:updated>2021-08-09T22:39:28.916Z</atom:updated>
            <content:encoded><![CDATA[<h3>What is a Function?</h3><p>A function is a piece of reusable code. Understanding functions and how they work is essential to writing clean and maintainable code.</p><p>If you have a set of statements (lines of code) which you want to be able to run more than once, put that set of statements into a function and then every time you call (execute) that function, you can run those statements. A function allows you to recycle your code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*V_NUgpnpfshzB8oI" /><figcaption>Photo by <a href="https://unsplash.com/@hishahadat?utm_source=ghost&amp;utm_medium=referral&amp;utm_campaign=api-credit">Shahadat Rahman</a> / <a href="https://unsplash.com/?utm_source=ghost&amp;utm_medium=referral&amp;utm_campaign=api-credit">Unsplash</a></figcaption></figure><h4>Function Declarations and the “function” Keyword:</h4><p>The most basic way to create a function is by declaring the function using the function keyword followed by the name of the function you want to give it, a set of parenthesis ( ) followed by a code block { }. You can optionally put in one or more parameters into the function&#39;s parenthesis to be able to use them in the function&#39;s code.</p><p>Creating a function in this way is called <em>“Function Declaration”</em>.</p><pre>function myFuncName(optionalParam1, optionalParam2, ...) {<br>  // Code that runs when the function is called / executed.<br>}</pre><h4>Running a Function:</h4><p>In order to run or execute the code inside a function, you have to “call” the function (this is also referred to as “invoking” a function).</p><p>To invoke a function, type the name of the function followed by parenthesis and any required function arguments. When you put the parenthesis after the function name, this tells JavaScript to execute the function.</p><pre>// Declare a function without function parameters<br>function sayHello() {<br>  console.log(&quot;Hello&quot;);<br>}<br><br>// Call / Invoke the sayHello function<br>sayHello(); // prints &quot;Hello&quot; to the console<br><br>// Declare a function that takes in a parameter<br>function sayWord(word) {<br>  console.log(word);<br>}<br><br>// Call / Invoke the sayWord function<br>sayWord(&quot;Hi&quot;); // prints &quot;Hi&quot; to the console<br>sayWord(); // returns undefined</pre><h4>Function Scope (Block Scope):</h4><p>Functions in JavaScript are block scoped, meaning that any variable declared inside the function’s blocks is part of the function’s block scope and is not accessible outside of the function.</p><p>Variables in the global scope can still be accessed and modified by the function.</p><pre>// define variable in global scope<br>let word = &quot; World!&quot;;<br><br>// Declare sayHello function<br>function sayHello() {<br>  let greeting = &quot;Hello&quot;;<br>  // Update greeting using variable from global scope<br>  greeting += word;<br>  console.log(greeting);<br>}<br><br>// Call the sayHello function<br>sayHello(); // prints &quot;Hello World!&quot; from the console<br><br>// Try to access the greeting variable declared inside the sayHello function<br>// This will not work as it was declared inside the function&#39;s scope and is not<br>// accessible in the global scope<br>console.log(greeting); // Returns &quot;ReferenceError: greeting is not defined&quot;</pre><h4>The Return Statement:</h4><p>The return statement is used in a function to return a value when the function is called.</p><p>return also ends execution of the function. Any code below a return statement in a function is not run after the return statement is executed.</p><p>To create a return statement, simply use the return keyword, optionally followed by an expression or value.</p><ul><li>If return is followed by a variable or expression, the evaluated value of that variable / expression will be returned by the function when it is called.</li><li>If return is not followed by a variable or expression, the function will return undefined when it is called.</li></ul><p>Example of using the return keyword to return a value when the function is called</p><pre>// Declare a function that returns the word &quot;Hello&quot;<br>function sayHello() {<br>  return &quot;Hello&quot;;<br>}<br><br>// Store the return value of the sayHello() function in greeting<br>let greeting = sayHello();<br>console.log(greeting); // Hello</pre><p>Example of using return to break out of a function. Notice in the function that the return statement breaks out of the while loop AND the function so that we don’t get an infinite loop.</p><pre>// Declare function that counts down from input number down to 0<br>// this function uses a return statement nested in an if statement<br>// to break out of the function when the function parameter is less than 0<br>function countDown(n) {<br>  while (true) {<br>    console.log(n);<br>    n--;<br>    if (n &lt; 0) {<br>      return;<br>    }<br>  }<br>}<br><br>// Call the countDown() function<br>countDown(10);<br><br>/*<br>10<br>9<br>8<br>7<br>6<br>5<br>4<br>3<br>2<br>1<br>0<br>*/</pre><h4>Parameters vs Arguments in Functions:</h4><p>Parameters are placeholder variables that are specified inside the parentheses of a function. These variables are used inside the function. A function can accept zero or more parameters.</p><p>When a user calls a function, if that function was declared with one or more parameters, the user must pass in values to those parameters. The values that the user passes in are referred to as function arguments. When the arguments are passed into the function, JavaScript replaces all instances of the function parameters with the value of the arguments that the user passed in.</p><p><strong>NOTE:</strong> When a user passes in an argument to the function, the function is actually copying the value of that argument and uses a copy to run its tasks. Keep this in mind because depending on the variable type passed in (primitive or reference), you will either end up making a copy of the value, or a copy of the reference to the value respectively.<br> Even though parameters and arguments are written in the same location in the function, they are different.</p><ul><li>parameters are placeholder variables written during function declaration</li><li>arguments are the actual value passed into the function when calling the function.</li></ul><h4>Setting Default Values for Parameters:</h4><p>In JavaScript, you can set default values for function parameters. If the user does not specify a particular argument when calling a function, JavaScript will use the default value assigned to the function parameter during function assignment.</p><p>To set a default value to a function parameter, set the parameter equal to a value during the function declaration.</p><pre>// Create a countUp function that will count up from a start point<br>// up to an end point<br>// Assign a default value of 10 to the end parameter<br>function countUp(start, end = 10) {<br>  while (true) {<br>    console.log(start);<br>    start++; // increment start value<br><br>    // Return condition<br>    if (start &gt; end) {<br>      return;<br>    }<br>  }<br>}<br><br>// Call the countUp function with both argument inputs<br>countUp(1, 5);<br>/*<br>https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters<br>*/<br><br>// Call the countUp function with only one input argument<br>// CountUp will start from 1 and go all the way up to 10<br>// which is the default value of the end parameter if not specified as an argument<br>countUp(1);<br>/*<br>countUp with 1 input:<br>1<br>2<br>3<br>4<br>5<br>6<br>7<br>8<br>9<br>10<br>*/</pre><p><strong>NOTE:</strong> You cannot use default parameters properly if a parameter to the right of the default parameter is not set to a default as well. In the example below, a sum function is made with the parameter a having a default of 1. Notice that the 2nd parameter to the sum function does not have a default parameter. When the sum function is called with only one input parameter, the function assumes that the single argument (2 in the example) is actually the value for the parameter a. JavaScript assumes that a value for b was never defined and so the resulting input is NaN.</p><pre>function sum(a = 1, b) {<br>  return a + b;<br>}<br><br>sum(2); // returns NaN</pre><p>To avoid this situation, when you assign a default parameter, make sure that anything to the right of that parameter, also has a default parameter, so that the values can be properly assigned if the user does not specify them. Another way to think about this is that parameters that don’t have a default assigned ALWAYS need to be to the LEFT of any parameters which are assigned a default value.</p><h4>Accepting Extra Parameters with the rest (…) Parameter:</h4><p>In JavaScript, use the rest parameter ... to allow a function to accept an unspecified amount of arguments.</p><p>To use the rest parameter, enter the rest parameter directly followed by an array name as the last parameter in the function declaration or argument. When the rest parameter is used, any additional arguments input into the function call will get stored in an array with the same name which was passed into the rest parameter.</p><pre>// Using the rest operator as the 3rd parameter of the product function expression<br>const product = (a, b, ...args) =&gt; {<br>  let prod = a * b;<br><br>  if (!args) {<br>    return prod;<br>  } else {<br>    args.forEach((element) =&gt; (prod *= element));<br>    return prod;<br>  }<br>};<br><br>console.log(product(1, 2, 3, 4, 5)); // 120<br><br>// Can also simply use ...args as the only parameter input into the function<br>const product2 = (...args) =&gt; {<br>  return args.reduce((accumulator, currentValue) =&gt; accumulator * currentValue);<br>};<br><br>console.log(product2(1, 2, 3, 4, 5)); // 120</pre><h4>Rest vs. Spread Operators:</h4><p>The rest parameter looks exactly like the spread operator however, they serve two different purposes.</p><ul><li>The spread operator is used to “unpack” an array or other iterable so that the values of the iterable can be used as function arguments.</li><li>The spread operator is used when invoking a function.</li><li>The spread operator can also be used to make a copy of the properties of an objects or the elements of an array by unpacking the values and then wrapping the unpacked values in either array or object literals.</li><li>The rest operator is used to “pack” comma separated values which are entered as arguments to a function.</li><li>The rest operator is used when creating a function definition or expression.</li><li>Basically, the spread and rest operators are opposites of each other</li><li>Spread “unpacks” the values of an array or object into individual elements.</li><li>Rest “packs” individual elements together into a single element (such as an array)</li></ul><h4>Function Best Practices:</h4><p>Be specific! Every function that you write should only perform one task. If you find that you wrote a function that performs 2 or more tasks (especially if they are unrelated), strongly consider breaking up the function into smaller functions, each which performs only one task. If you write a function called addTwoNumbers(), it should only add two numbers, if it does anything else, such as multiplying the two numbers, that should go into another function.</p><p>Try to give your functions names that give some detail about what the function does. For example, if you write a function called sayHello(), then this probably means that the function will either return or print to the console a greeting such as &quot;Hello&quot;.</p><p>This will help with code readability and maintenance.</p><h3>Other Ways to Create a Function:</h3><h4>Function Expressions:</h4><p>A function expression is simply a function declaration stored in a value.</p><p>To create a function expression, write a function declaration and then assign it to a variable name.</p><pre>// Create a function expression<br>const myFuncExp = function sayHello() {<br>  console.log(&quot;hello&quot;);<br>};<br><br>// Call myFuncExp<br>myFuncExp(); // prints &quot;hello&quot; to the console<br><br>// Call sayHello<br>sayHello(); // returns &quot;ReferenceError: sayHello is not defined&quot;</pre><p>In the code above, notice that you no longer can call the function using sayHello(). Instead, we have to call the function expression using the myFuncExp() variable name we defined to the left of the assignment operator.</p><h4>Anonymous Functions:</h4><p>In the introduction to Function Expressions, we showed that the function name on the right hand side can no longer be used to invoke the function, and instead, you had to use the variable name assigned to the function expression. You can actually remove the function name to the right of the function keyword and the function expression would still work.</p><p>A function without a declared name is referred to as an anonymous function. Anonymous functions are most often seen in conjunction with function expressions as a sort of “shorthand” to writing the function expression.</p><pre>// Create a function expression<br>const sayHi = function sayHello() {<br>  console.log(&quot;hello&quot;);<br>};<br><br>// Create another function expression but assign it the value of an anonymous function<br>const sayGoodbye = function () {<br>  console.log(&quot;goodbye&quot;);<br>};<br><br>// Call sayHi function expression<br>sayHi(); // prints &quot;hello&quot; to the console<br><br>// Call the sayGoodbye function expression<br>sayGoodbye(); // prints &quot;goodbye&quot; to the console</pre><p><strong>NOTE:</strong> You can also create anonymous arrow functions using the following syntax () =&gt; {}. These can be used as callback functions. See additional information below for more information on callback functions and arrow functions.</p><h4>Arrow Functions:</h4><p>Arrow functions (also referred to as arrow function expressions) are further shorthand for anonymous function expressions which omit the use of the function keyword altogether and instead use what is called a &quot;fat arrow&quot; as the trigger to tell JavaScript that the statement is a function. The fat arrow is denoted with an equal sign next to a greater than sign =&gt;.</p><h4>Arrow Function Syntax:</h4><p>In general, when creating an arrow function, declare a function name and assign it to parenthesis with 0 or more parameters, add an “fat arrow” after the parenthesis and then add brackets with the function code inside. You should also add a semicolon after the closing bracket.</p><p>General Arrow Function Syntax</p><pre>const myFuncArrow = (param1, param2, param3, ...) =&gt; {<br>  // CODE HERE<br>};</pre><p><strong>NOTE:</strong> If the arrow function only has 1 parameter, you can omit the parenthesis around the parameter however, some style guides such as the <a href="https://github.com/airbnb/javascript#arrow-functions">Airbnb JavaScript Style Guide</a> recommend to keep the parenthesis for better clarity.</p><p><strong>NOTE 2:</strong> If the arrow function does not accept any parameters, you need to use a pair of empty parenthesis as part of the arrow function syntax.</p><p>Example of writing an arrow function without parameters</p><pre>const myFunc = () =&gt; {<br>  return &quot;hello&quot;;<br>};</pre><p>If you only have one line of code inside your arrow function, you can use an implicit return. This requires you to omit the return keyword as well as the brackets. If the single line is particularly long, you can add parenthesis to wrap around the statement.</p><pre>// Standard Arrow Function Syntax<br>const sumNum = (a, b) =&gt; {<br>  return a + b;<br>};<br><br>// Single-statement Arrow Function Syntax<br>const sumNum2 = (a, b) =&gt; a + b;<br><br>// Call both functions<br>console.log(&quot;sumNum: &quot;, sumNum(1, 2)); // returns 3<br>console.log(&quot;sumNum2: &quot;, sumNum2(1, 2)); // returns 3</pre><p><strong>NOTE 3:</strong> Be careful when using the single line, implicit return with objects. If you try to return an object in a single line without the return statement (“implicitly”), JS will try to interpret the object’s curly braces with the arrow function’s braces. A way to work around this is to enclose the whole object in parenthesis.</p><pre>// BAD<br>const myArrowFunc = () =&gt; {key1: &quot;value1&quot;, key2: &quot;value2&quot;, key3: &quot;value3&quot;};<br><br>// GOOD<br>const myArrowFunc = () =&gt; ({key1: &quot;value1&quot;, key2: &quot;value2&quot;, key3: &quot;value3&quot;});</pre><h4>Anonymous Arrow Function Syntax:</h4><p>It is possible to create anonymous arrow functions. These often appear when using the arrow function expression as an input to a function (i.e. a callback function).</p><p>Anonymous Arrow Function Syntax</p><pre>() =&gt; {}</pre><p>Example of using an anonymous arrow function as a callback function to the array method .filter()</p><pre>// Initialize an array of numbers<br>let myArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];<br><br>// Call the .filter() method on myArray and use an anonymous arrow function<br>// as the callback function to help filter the array for even numbers<br>let evens = myArray.filter((element) =&gt; element % 2 === 0);<br><br>console.log(evens); // [ 2, 4, 6, 8, 10 ]</pre><h4>Limitations of Arrow Functions:</h4><p>While arrow function syntax looks clean, it cannot be used in all cases due to some limitations. Here are the most notable limitations:</p><ul><li>Arrow functions do not have their own bindings to this or super</li><li>Thus, arrow functions should not be used for object methods (functions associated with an object)</li><li>Generally can’t be used with call, apply, or bind methods</li><li>Cannot be used to create constructor functions</li></ul><h4>IIFE (Immediately Invoked Function Expression):</h4><p>As the name implies, use an IIFE (Immediately Invoked Function Expression) to invoke an anonymous function expression as soon as it is defined.</p><p>To turn an anonymous function expression into an IIFE, wrap the anonymous function expression in parenthesis, and then add an empty set of parenthesis right afterwards, just like you would use to invoke a regular function.</p><pre>// IIFE which prints &quot;hi&quot; to the console as soon as code is executed<br>(function () {<br>  console.log(&quot;hi&quot;);<br>})();<br><br>// IIFE which accepts 2 arguments, prints 15 to the console in this case<br>(function (a, b) {<br>  console.log(5 + 10);<br>})(5, 10);</pre><p>Per the Mozilla Developer Network, IIFEs can be used during program initialization if we just want to temporarily define some variables. As soon as the function finishes running, any variables defined within the function will be garbage collected and will not be part of the global scope helping to reduce the amount of global variables which is generally best practice.</p><p>You can also wrap your code in an IIFE to prevent the code from being read as any code inside the IFFE will not be accessible y the user.</p><h3>Function Hoisting:</h3><p>In a previous article, I spoke about hoisting which is the process that JavaScript uses to bring variable declarations to the top of the code prior to executing it.</p><p>Hoisting also works with function declarations. Any function created using a function declaration is “hoisted” to the top of the code and loaded by JavaScript before the rest of the code is executed. This allows us to write code where we call functions created by function declarations before the function declaration is actually declared.</p><p><strong>NOTE:</strong> Unlike function declarations, function expressions are NOT hoisted by JavaScript. If you try to call a function expression before it is defined in code, you will get a ReferenceError. Apart from how function declarations and function expressions are written, the fact that function declarations are hoisted and function expressions aren&#39;t is really the only major difference between the two function creation methods.</p><pre>// Call sayHi function expression above where the function is defined<br>sayHello(); // prints &quot;hello&quot; to the console<br><br>// Create a function declaration named sayHello<br>function sayHello() {<br>  console.log(&quot;hello&quot;);<br>}<br><br>// Call the sayGoodbye function expression above where the function is defined<br>sayGoodbye(); // prints &quot;ReferenceError: Cannot access &#39;sayGoodbye&#39; before initialization&quot;<br><br>// Create a function expression named sayGoodbye<br>const sayGoodbye = function () {<br>  console.log(&quot;goodbye&quot;);<br>};</pre><h3>Callback Functions</h3><p>A callback function is an anonymous function which is defined as a parameter of another function.</p><p>You will typically find callback functions in built-in JavaScript functions and methods. For example, a common function which accepts a callback function is the addEventListener method in JavaScript.</p><p>Lets take an example of the in-built array method filter. filter accepts a callback function which checks a condition for each element that filter is being called on. When JavaScript executes the filter function, the filter function will iterate through each element in the array and for each element, it will invoke the callback function.</p><pre>// Declare an array of numbers<br>const myArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];<br><br>// Filter myArray<br>// create an odds array with just the odd numbers in myArray<br>// Here, we are using an anonymous arrow function which we<br>// declare as a parameter to the filter function<br>const odds = myArray.filter((element) =&gt; {<br>  if (element % 2 !== 0) {<br>    return element;<br>  }<br>});<br><br>console.log(odds); // [ 1, 3, 5, 7, 9 ]<br><br>// We can also create the callback function outside of the calling function&#39;s<br>// parameters and just reference the callback function&#39;s name in the parameter list<br>// of the calling function<br>const evenCallback = (element) =&gt; {<br>  if (element % 2 === 0) {<br>    return element;<br>  }<br>};<br><br>// call the evenCallback function inside the filter function<br>// NOTICE THAT WE DID NOT INCLUDE THE PARENTHESIS NEXT TO evenCallback INSIDE THE PARAMETER TO .filter<br>// THIS IS BECAUSE WE DON&#39;T WANT TO INVOKE THE FUNCTION, THE .filter METHOD WILL INVOKE evenCallback FOR US<br>const evens = myArray.filter(evenCallback);<br><br>console.log(evens); // [ 2, 4, 6, 8, 10 ]</pre><p><strong>NOTE 1:</strong> Notice that I used arrow function syntax to define my callback functions in the above example. You can also use regular function expressions or function declarations to create a callback function.</p><p><strong>NOTE 2:</strong> It is important to understand that when you pass in the name of a callback function as a parameter, you DO NOT want to include parenthesis with the function name. Including parenthesis with the callback function’s name as a parameter will force JavaScript to immediately invoke the function at runtime which is not what you want to happen typically.</p><h3>References</h3><ul><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/return">MDN — return</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters">MDN — default parameters</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions">MDN — Arrow function expressions</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters">MDN — Rest parameters</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax">MDN — Spread Syntax</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Glossary/IIFE">MDN — IIFE</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind">MDN — Function.prototype.bind()</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply">MDN — Function.prototype.apply()</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call">MDN — Function.prototype.call()</a></li><li><a href="https://wesbos.com/javascript/02-functions/different-ways-to-declare-functions">Wes Bos — Different Ways to Declare Functions</a></li><li><a href="https://eloquentjavascript.net/03_functions.html">Eloquent JavaScript, 3rd Edition — Chapter 3, Functions</a></li><li><a href="https://javascript.info/function-basics">JavaScript.info — Functions</a></li><li><a href="https://javascript.info/function-expressions">JavaScript.info — Function Expressions</a></li><li><a href="https://javascript.info/arrow-functions-basics">JavaScript.info — Arrow functions, the basics</a></li><li><a href="https://blog.alexdevero.com/method-chaining-in-javascript/">What Method Chaining in JavaScript Is, How it Works and How to Use It</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=44328c4ed7ab" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Structures in JS: Objects]]></title>
            <link>https://pszponder.medium.com/data-structures-in-js-objects-d247257374b6?source=rss-fb363d427808------2</link>
            <guid isPermaLink="false">https://medium.com/p/d247257374b6</guid>
            <dc:creator><![CDATA[Piotr Szponder]]></dc:creator>
            <pubDate>Mon, 26 Jul 2021 13:58:03 GMT</pubDate>
            <atom:updated>2021-07-26T13:58:03.827Z</atom:updated>
            <content:encoded><![CDATA[<h3>Data Structures:</h3><p>This series of blogs will discuss various data structures in the context of JavaScript. Data structures are different ways to organize data to solve different types of problems.</p><p>This article is an introduction to objects. I will be discussing the object data type, what it is, how it is created, how to access it, and how to manipulate it.</p><figure><img alt="Shot with @expeditionxdrone" src="https://cdn-images-1.medium.com/proxy/0*DLoKwfQv7eKLducS" /><figcaption>Photo by <a href="https://unsplash.com/@chuttersnap?utm_source=ghost&amp;utm_medium=referral&amp;utm_campaign=api-credit">CHUTTERSNAP</a> / <a href="https://unsplash.com/?utm_source=ghost&amp;utm_medium=referral&amp;utm_campaign=api-credit">Unsplash</a></figcaption></figure><h3>The Object Data Type:</h3><ul><li>An object is a collection of key-value pairs.</li><li>Objects allow us to group related variables and functions together.</li><li>The data stored in objects is unordered, meaning that the order in which you enter the data into the object may not the the same order in which the javascript interpreter retrieves the data.</li><li>An object can contain any type of data (numbers, booleans, strings, arrays, other objects, etc.).</li><li>The object can also store functions inside of it which can be accessed and called at a later time.</li><li>Data inside an object is retrieved by referencing the key associated with the particular value we want to access.</li><li>Because of this, an object is not considered iterable as the values in the object don’t have an index.</li><li>Data inside an object is unordered.</li></ul><p>Example of an Object:</p><pre>let myObj = {<br>  firstName: &quot;Jane&quot;,<br>  lastName: &quot;Doe&quot;,<br>  favoriteColor: &quot;green&quot;,<br>  favoriteNumber: 42,<br>  favoriteBookSeries: [&quot;The Hobbit&quot;, &quot;Lord of the Rings&quot;, &quot;Harry Potter&quot;],<br>  likesToDance: true,<br>};</pre><h4>Key — Value Pairs</h4><p>Unlike arrays whose element’s are stored and accessed via an index, values in objects are stored with what is called key-value pairs.</p><p>For each value stored in an object, there is an accompanying key that can be used to access the value. When writing a key-value pair in a JS object, the key and value are separated by semicolons with a comma after the key-value when there are more key-value pairs in the object.</p><pre>let myObject = {<br>  key: value,<br>  key2: value2,<br>  key3: value3,<br>};</pre><p><strong>NOTE:</strong> The key is typically written without quotes but if your key will contain spaces, dashes or other characters other than letters and numbers, you will need to enclose the key with quotes.</p><pre>let myObject = {<br>  key: value,<br>  &quot;my-key&quot;: value2,<br>  &quot;this is my key&quot;: value3,<br>};</pre><h4>Properties</h4><p>In an object, a key-value pair can either represent a property or a method. This derives from Object Oriented Programming where an object is a representation of a &quot;thing&quot; that has certain characteristics and can do stuff. A property of the object represents a characteristic of the object.</p><p>For example, if we make a car object, what are its attributes / characteristics? Well, a car has an engine, it has a color, it has a make and a model number, it has a certain amount of wheels, it has a total occupancy limit, it has a top speed. The list can go on and on. The point is that properties describe the object, they are the characteristics of the object.</p><p>Example of the car object:</p><pre>let car = {<br>  make: &quot;toyota&quot;,<br>  model: &quot;avalon&quot;,<br>  hasEngine: true,<br>  color: &quot;red&quot;,<br>  wheels: 4,<br>  occupancy: 5,<br>  topSpeed: 100,<br>};</pre><h4>Methods</h4><p>Continuing with the conversation of the car object, we have discussed how properties are used to describe attributes or characteristics of the object. So what do methods do?</p><p>Methods are functions that belong to the object. These methods can be accessed though the object to do various sorts of things. To write a method, we assign an anonymous function to the value of a key-value pair.</p><p>For the car example, let’s add a function that will return a string when called.</p><pre>let car = {<br>  make: &quot;toyota&quot;,<br>  model: &quot;avalon&quot;,<br>  hasEngine: true,<br>  color: &quot;red&quot;,<br>  wheels: 4,<br>  occupancy: 5,<br>  topSpeed: 100,<br><br>  startEngine: function () {<br>    console.log(&quot;Vroom&quot;);<br>  },<br><br>  pressHorn: function () {<br>    console.log(&quot;Beep beep&quot;);<br>  },<br>};<br><br>// Access the startEngine function<br>car.startEngine(); // Logs &quot;Vroom&quot; to the console<br><br>// Access the pressHorn function<br>car.pressHorn(); // Logs &quot;Beep beep&quot; to the console</pre><h4>Method Shorthand:</h4><p>Instead of declaring an anonymous function, we can actually omit the key-value assignment as well as the function keyword to create an object method using a shorthand technique.</p><p>To use the shorthand for declaring an object method, simply write the function name followed directly by parenthesis and then open yp your curly brackets.</p><pre>// Initialize a wizard object<br>let warrior = {<br>  health: 20,<br>  specialization: &quot;melee&quot;,<br>  attacks: [&quot;headbutt&quot;, &quot;slash&quot;, &quot;chop&quot;, &quot;stun&quot;],<br>  inventory: [&quot;roast mutton&quot;, &quot;sword&quot;, &quot;axe&quot;],<br>  attack: function () {<br>    console.log(&quot;Warrior attacks with...&quot;, this.attacks[1]);<br>  },<br>  // Use the method shorthand to define the eat() method<br>  eat() {<br>    // If roast mutton exists in object&#39;s inventory<br>    if (this.inventory.indexOf(&quot;roast mutton&quot;) &gt;= 0) {<br>      // Remove roast mutton<br>      this.inventory = this.inventory.filter(<br>        (element) =&gt; element !== &quot;roast mutton&quot;<br>      );<br>      // Increase health<br>      this.health += 10;<br>    }<br>  },<br>};<br><br>console.log(warrior);<br>/*<br>{<br>  health: 20,<br>  specialization: &#39;melee&#39;,<br>  attacks: [ &#39;headbutt&#39;, &#39;slash&#39;, &#39;chop&#39;, &#39;stun&#39; ],<br>  inventory: [ &#39;roast mutton&#39;, &#39;sword&#39;, &#39;axe&#39; ],<br>  attack: [Function: attack],<br>  eat: [Function: eat]<br>}<br>*/<br><br>// Call the eat() method which was defined using the shorthand technique<br>warrior.eat();<br>console.log(warrior.health); // 30<br>console.log(warrior.inventory); // [ &#39;sword&#39;, &#39;axe&#39; ]</pre><h4>this keyword:</h4><p>The this keyword is used in objects to reference that particular instance of the object. When a function with the this keyword is used and the function is a method of an object, this will refer to the object which the method is being called on.</p><p>In the below example of the wizard object, there are two methods. Instead of just trying to access the inventory in the “checkInventory()” function for example, we access the inventory of the current object using the this keyword. Using the this keyword tells JavaScript that it needs to access the inventory key-value pair of the current object it is accessing (wizard in this case).</p><pre>let wizard = {<br>  element: &quot;fire&quot;,<br>  damage: 10,<br>  spell: &quot;fireball&quot;,<br>  intelligence: 90;<br>  inventory: [&quot;staff&quot;, &quot;scroll&quot;, &quot;magic potion&quot;],<br><br>  checkInventory: function () {<br>    console.log(&quot;Checking Inventory...&quot;);<br>    for (const item of this.inventory) {<br>      console.log(item);<br>    }<br>  },<br><br>  castSpell: function () {<br>    console.log(&quot;Wizard casts: &quot;, this.spell);<br>  },<br>};<br><br>wizard.checkInventory();<br>/*<br>Checking Inventory...<br>staff<br>scroll<br>magic potion<br>*/<br><br>wizard.castSpell(); // Wizard casts: fireball</pre><p>This may not seem important right now but once we start talking more about objects in the context of OOP and having multiple instances of the same class, it will make more sense why we want to use the this keyword.</p><p><strong>NOTE:</strong> There are actually two different items that the this keyword actually represents.</p><ul><li>When this is used as part of a method inside the object, it references the object which that method is being called on. So when we call a method on an object (ex. myObject.myMethod), the this keyword inside the method references the object that it is being called on.</li><li>When this is called in a function outside of an object (a function which does not belong to the object itself), it references the global window object in the browser.</li><li>Another important note to make is that an object can have a method which references a callback function. That callback function is not necessarily a method of the object itself and use of the this keyword in the callback function might actually reference the global window object, not the properties of the object.</li></ul><h3>Primitive vs Reference Values in JavaScript:</h3><p>Every value in JavaScript has one of two types, it is either a primitive type or it is a reference type.</p><h4>Primitive Data Types:</h4><p>A primitive data type is defined as any data that is not an object and does not have any methods.</p><p>There are 7 primitive data types in JavaScript:</p><ul><li>number</li><li>string</li><li>boolean</li><li>undefined</li><li>null</li><li>symbol</li><li>bigint</li></ul><p>A primitive value is immutable, which means that it&#39;s data cannot be changed or altered.</p><p><strong>NOTE:</strong> When we reassign a variable with a primitive data type, we are actually assigning a new value in memory to the variable, we are not changing the original piece of data in memory which the variable referenced.</p><p>As an example, if I have a variable called myVar and I set it&#39;s initial value to &quot;hello&quot; and then reassign that value to &quot;goodbye&quot;, what is happening is that the myVar<br> variable is now pointing to a new location in memory with the value of &quot;goodbye&quot; instead of the original location in memory which stored &quot;hello&quot;. The location in memory which stored &quot;hello&quot; was not altered in any way.</p><p>Another important thing to understand is that when we copy a primitive data type to a new variable, an actual copy is made. In the example below, if we create a new variable called myVar2 and assign it to the value of myVar, what happens is that the value of myVar is copied to a new location in memory and assigned to myVar2. So both myVar and myVar2 have their own copies of the &quot;goodbye&quot; value in their own locations in memory.</p><pre>// Initialize the myVar variable<br>// myVar points to a location in memory which stores<br>// the value of &quot;hello&quot;<br>let myVar = &quot;hello&quot;;<br><br>// myVar is now redirected to a new location in memory<br>// which holds the value of &quot;goodbye&quot;<br>// The original value of &quot;hello&quot; in memory was not modified<br>myVar = &quot;goodbye&quot;;<br><br>// Copy the value of myVar to a new location in memory<br>// and assign that copied  value to myVar2<br>let myVar2 = myVar;</pre><p>Here is another example taken from <a href="https://developer.mozilla.org/en-US/docs/Glossary/Mutable">MDN</a> on how immutable data types work under the hood:</p><pre>// Declare a string variable and set its value<br>// equal to &quot;Hello&quot;<br>let immutableString = &quot;Hello &quot;;<br><br>// Append the value of &quot;World&quot; to the current value<br>// of immutableString<br>immutableString = immutableString + &quot;World&quot;;<br><br>/*<br>What is happening in the line above:<br>1. The current value of immutableString (&quot;Hello &quot;) is accessed in memory.<br>2. &quot;World&quot; is appended to the value of &quot;Hello&quot;.<br>3. The new string value &quot;Hello World&quot; is stored in a new location in memory.<br>4. The variable immutableString now points to the new value of &quot;Hello World&quot; which is in a different memory location than the original value of &quot;Hello &quot;.<br>*/</pre><h4>Reference Data Types:</h4><p>All objects are reference data types.</p><p>Instead of pointing to the actual piece of data in memory, an object variable actually stores an address which then points to the object’s value in memory.</p><p>So the reference refers to the address which points to the location of the object&#39;s data in memory.</p><p>Reference data types (like objects and arrays) work by storing an address to where the data in memory is located. So when you declare an object or array variable, the data itself is not stored with the variable name, instead, a memory address where the data is located is stored with the variable name.</p><p>When a variable with a reference type value is copied, the value itself in memory is not copied. Instead, the reference to the value in memory is copied. This results in both variables (original and copied) pointing to the same value in memory, their variables hold &quot;references&quot; to the same value in memory.</p><pre>// =================================================<br>// Base Case: Copying and Modifying Primitive Values<br>// =================================================<br><br>// Create a primitive type variable<br>let myString = &quot;hello&quot;;<br><br>// Create a copy of the primitive type variable<br>let myStringCopy = myString;<br><br>// log both string variables to the console<br>console.log(`myString:`, myString);<br>// myString: hello<br><br>console.log(`myStringCopy:`, myStringCopy);<br>// myStringCopy: hello<br><br>// Change the value of myString<br>myString = &quot;goodbye&quot;;<br><br>// Log both string variables to the console<br>// Notice how only the value of myString has changed<br>// The value of myStringCopy is still &quot;hello&quot;<br>console.log(`myString:`, myString);<br>// myString: goodbye<br>console.log(`myStringCopy:`, myStringCopy);<br>// myStringCopy: hello<br><br>// ==================================================<br>// Copying and Modifying Reference Types with Objects<br>// ==================================================<br><br>// Create an object named myObject<br>let myObject = {<br>  key1: &quot;hello&quot;,<br>  key2: &quot;world&quot;,<br>};<br><br>// Create an object named myObjectCopy which<br>// is a copy of myObject<br>let myObjectCopy = myObject;<br><br>// Log both objects to the console<br>console.log(&quot;myObject:&quot;, myObject);<br>// myObject: { key1: &#39;hello&#39;, key2: &#39;world&#39; }<br><br>console.log(&quot;myObjectCopy:&quot;, myObjectCopy);<br>// myObjectCopy: { key1: &#39;hello&#39;, key2: &#39;world&#39; }<br><br>// Modify the value of key1 in myObjectCopy<br>myObjectCopy.key1 = &quot;goodbye&quot;;<br><br>// Log both objects to the console<br>// Notice how the value of key1 in both objects has changed<br>console.log(`myObject:`, myObject);<br>// myObject: { key1: &#39;goodbye&#39;, key2: &#39;world&#39; }<br><br>console.log(`myObjectCopy:`, myObjectCopy);<br>// myObjectCopy: { key1: &#39;goodbye&#39;, key2: &#39;world&#39; }<br><br>// ==================================================<br>// Copying and Modifying Reference Types with Arrays<br>// (arrays are also reference type values)<br>// ==================================================<br><br>// Create an array called myArray<br>let myArray = [0, 1, 2, 3, 4, 5];<br><br>// Create a copy of myArray<br>myArrayCopy = myArray;<br><br>// Log both arrays to the console<br>console.log(`myArray:`, myArray);<br>// myArray: [ 0, 1, 2, 3, 4, 5 ]<br><br>console.log(`myArrayCopy:`, myArrayCopy);<br>// myArrayCopy: [ 0, 1, 2, 3, 4, 5 ]<br><br>// Change the value of the 1st element in the original array<br>myArray[0] = &quot;Hello&quot;;<br><br>// Log both arrays to the console<br>// Notice how the 1st element in both arrays has changed<br>console.log(`myArray:`, myArray);<br>// myArray: [ &quot;Hello&quot;, 1, 2, 3, 4, 5 ]<br><br>console.log(`myArrayCopy:`, myArrayCopy);<br>// myArrayCopy: [ &quot;Hello&quot;, 1, 2, 3, 4, 5 ]</pre><p>It is important to understand that everything in JavaScript, other than the primitive values, is considered to be an object and is therefore, a reference data type. So arrays and maps for example are also objects. If the data that you are looking at has a method attached to it, then it is considered an object.</p><p>Reference data types are mutable meaning that their values can be changed in memory.</p><pre>// Create an object named myObject<br>let myObject = {<br>  key1: &quot;hello&quot;,<br>  key2: &quot;world&quot;,<br>};<br><br>// Update the value of key1 to &quot;goodbye&quot;<br>myObject.key1 = &quot;goodbye&quot;;<br><br>// Log myObject to the console<br>console.log(`myObject:`, myObject);<br>// myObject: { key1: &#39;goodbye&#39;, key2: &#39;world&#39; }<br><br>/*<br>What is happening?<br>1. The object points to data in a location in memory.<br>2. JavaScript moves to that location in memory and extracts the value associated with key1 (&quot;hello&quot;).<br>3. The value (&quot;hello&quot;) is replaced with the new value &quot;goodbye&quot;<br>4. Changing the value does not change its location in memory.<br>5. The object is still pointing to the same value in memory as it was prior to the reassignment.<br>*/</pre><h3>How to Create an Object:</h3><p>To create an object, use either object literals or using the new keyword and the Object() constructor function.</p><h4>Using an Object Literal:</h4><p>To create an object literal (you are “literally” creating the object value) in JavaScript, simply enclose as many (or as little) key-value pairs inside curly braces and assign that to a variable.</p><pre>let emptyObject = {};<br><br>let myObject = {<br>  key1: &quot;value1&quot;,<br>  key2: &quot;value2&quot;,<br>  key3: 3,<br>  key4: [4, 5, 6],<br>};</pre><h4>Using the new Object() Constructor Function:</h4><p>Use the new keyword accompanied by the Object() constructor function to create a new empty object</p><pre>let myObject = new Object();<br><br>console.log(myObject); // {}</pre><h3>How to Copy and Object using the Spread Operator:</h3><p>Since objects are reference types, you cannot directly make a “deep copy” of an object by using the equality operator. Trying to do so will result in making 2 objects which reference the same data in memory. This is because when using the assignment operator, the reference to the location in memory where the values are stored are copied, instead of the values actually being copied. Therefore, if the values in either of these 2 objects would change, the change will be visible in both objects.</p><p>Example:</p><pre>// Initialize myFirstObject object<br>let myFirstObject = {<br>  greeting: &quot;Hello&quot;,<br>};<br><br>// Create a &quot;shallow copy&quot; of myFirstObject and store<br>// it in mySecondObject<br>// (mySecondObject points to the same data in memory as<br>// myFirstObject)<br>let mySecondObject = myFirstObject;<br><br>// Add a property to mySecondObject<br>// Since mySecondObject is a shallow copy, myFirstObject will<br>// also reference the sayGoodbye property<br>mySecondObject.sayGoodbye = &quot;Bye!&quot;;<br><br>console.log(`myFirstObject:`, myFirstObject);<br>// myFirstObject: { greeting: &#39;Hello&#39;, sayGoodbye: &#39;Bye!&#39; }<br><br>console.log(`mySecondObject:`, mySecondObject);<br>// mySecondObject: { greeting: &#39;Hello&#39;, sayGoodbye: &#39;Bye!&#39; }</pre><p>In order to make a deep copy of an object which stores its own copy of all of the values of a copied object, we have to use the spread operator.</p><p>The spread operator consists of three dots ... and works on arrays, strings, objects, and other iterables in JavaScript. The spread operator basically destructures / unpacks the contents of whatever it is called on so that they can be used to create copies using literal expressions such as object literals and string literals.</p><pre>// Initialize myFirstObject object<br>let myFirstObject = {<br>  greeting: &quot;Hello&quot;,<br>};<br><br>// Create a &quot;deep copy&quot; of myfirstObject using the spread operator<br>// myThirdObject stores copies of the key-value pairs of myFirstObject<br>let myThirdObject = { ...myFirstObject };<br><br>// Add a property to myThirdObject<br>// Since myThirdObject is a deep copy, myFirstObject will NOT contain this property<br>myThirdObject.sayGoodbye = &quot;Bye!&quot;;<br><br>console.log(`myFirstObject:`, myFirstObject);<br>// myFirstObject: { greeting: &#39;Hello&#39; }<br><br>console.log(`myThirdObject:`, myThirdObject);<br>// myThirdObject: { greeting: &#39;Hello&#39;, sayGoodbye: &#39;Bye!&#39; }</pre><p><strong>NOTE 1</strong>: Keep in mind that the spread operator only copies one level down. So if you have a nested object for example, the properties of the copied nested object will still be a reference to the values of the nested object from the original object.</p><pre>// Initialize myFirstObject object<br>let myFirstObject = {<br>  greeting: &quot;Hello&quot;,<br>  nestedObject: { nestedObjectKey: &quot;nested object value&quot; },<br>};<br><br>// Create a &quot;deep copy&quot; of myfirstObject using the spread operator<br>// myThirdObject stores copies of the key-value pairs of myFirstObject<br>let myThirdObject = { ...myFirstObject };<br><br>// Change the value of the nestedObject<br>// This value is a reference value<br>myThirdObject.nestedObject.nestedObjectKey =<br>  &quot;I changed the nested object value&quot;;<br><br>console.log(`myFirstObject:`, myFirstObject);<br>/*<br>myFirstObject: {<br>  greeting: &#39;Hello&#39;,<br>  nestedObject: { nestedObjectKey: &#39;I changed the nested object value&#39; }<br>}<br>*/<br><br>console.log(`myThirdObject:`, myThirdObject);<br>/*<br>myThirdObject: {<br>  greeting: &#39;Hello&#39;,<br>  nestedObject: { nestedObjectKey: &#39;I changed the nested object value&#39; }<br>}<br>*/<br><br>// Change the value of the nestedObject property to a string instead of an object<br>// Since this is at the first level, this change will not propagate through both of the objects.<br>myThirdObject.nestedObject = &quot;value changed to string from object&quot;;<br><br>console.log(`myFirstObject:`, myFirstObject);<br>/*<br>myFirstObject: {<br>  greeting: &#39;Hello&#39;,<br>  nestedObject: { nestedObjectKey: &#39;I changed the nested object value&#39; }<br>}<br>*/<br>console.log(`myThirdObject:`, myThirdObject);<br>/*<br>myThirdObject: {<br>  greeting: &#39;Hello&#39;,<br>  nestedObject: &#39;value changed to string from object&#39;<br>}<br>*/</pre><p><strong>NOTE 2</strong>: The spread syntax is also very useful with functions that take in a list of values, such as Math.max(). If you had an array of numbers and you wanted to find the max value in that array, you can use the spread operator to &quot;unpack&quot; the values of the array so that they can be read by the .max() method.</p><pre>let myArray = [1, 2, 3, 4, 5];<br>let max = Math.max(...myArray); // same as writing Math.max(1, 2, 3, 4, 5)<br>console.log(max); // returns 5</pre><h3>How to Access and Change Properties and Methods of the Object:</h3><p>As with object declaration, there are a few ways to access the properties and methods of objects.</p><p>Once a property or method is accessed, it can be changed.</p><p>You can also add a new property or method to an object by using the methods below.</p><h4>Dot Notation:</h4><p>Dot notation can be used to access any property or method of an object. It can also be used to modify or even add properties and objects.</p><p>To use dot notation, simply write the name of the object, followed by a dot, followed by the name of the key whose value you want to access (or modify).</p><p>Using dot notation with a key name that does not exist will add it and the value which you assign to the object.</p><pre>// Initialize a wizard object<br>let wizard = {<br>  health: 5,<br>  type: &quot;magic&quot;,<br>  specialization: &quot;fire&quot;,<br>  spells: [&quot;fireball&quot;, &quot;conflaguration&quot;],<br>  inventory: [&quot;apple&quot;, &quot;scroll&quot;, &quot;potion&quot;],<br>  castSpell: function () {<br>    console.log(&quot;Wizard casts...&quot;, this.spells[1]);<br>  },<br>};<br><br>// Use dot notation to access properties and methods of<br>// the object<br>console.log(wizard.health); // 5<br>console.log(wizard.inventory); // [ &#39;apple&#39;, &#39;scroll&#39;, &#39;potion&#39; ]<br>wizard.castSpell(); // Wizard casts... conflaguration<br><br>// Use dot notation change the value of the spells array<br>wizard.spells[1] = &quot;fizzle&quot;;<br>console.log(wizard.spells); // [ &#39;fireball&#39;, &#39;fizzle&#39; ]<br><br>// Use dot notation to add additional properties to the<br>// wizard object<br>wizard.mana = 20;<br>console.log(wizard.mana); // 20<br><br>wizard.weapon = &quot;staff&quot;;<br>console.log(wizard.weapon); // &quot;staff&quot;<br><br>// Use dot notation to add additional methods to the<br>// wizard object<br>wizard.drinkHealthPotion = function () {<br>  this.health += 5;<br>  console.log(&quot;Health has been restored to...&quot;, this.health);<br>};<br><br>// Call the newly added method 2 times<br>// watch how the value of the health property is updated<br>wizard.drinkHealthPotion(); // Health has been restored to... 10<br>wizard.drinkHealthPotion(); // Health has been restored to... 15</pre><h4>Bracket Notation:</h4><p>Another way to access, modify or add properties to an object is by using square brackets.</p><p>In application, this is very similar to using dot notation but instead of using the dot, use square brackets to encapsulate the name of the property key. You also need to wrap the name of the property in strings unless you are entering an iterator in a loop.</p><p>In the example below, we are accessing a property of myObject called keyName and we retrieve the value of &quot;myValue&quot;.</p><pre>let myObject = {<br>  keyName: &quot;myValue&quot;,<br>  hello: &quot;world&quot;,<br>};<br><br>console.log(myObject[&quot;keyName&quot;]); // Returns &quot;myValue&quot;</pre><p>When you enter a keyName without quotes to try to access an object’s value, JS will actually try to interpret the value of the item placed in brackets and use that value as the key name.</p><p>In this 2nd example below, since keyName is not wrapped in quotes, JS searches for a value named keyName outside of the object and then uses the value assigned to keyName as the name of the object property. Since keyName is defined as the string &quot;hello&quot;, JavaScript accesses the property of the object with a key, &quot;hello&quot; which has a value of &quot;world&quot; in myObject.</p><pre>let myObject = {<br>  keyName: &quot;myValue&quot;,<br>  hello: &quot;world&quot;,<br>};<br><br>let keyName = &quot;hello&quot;;<br><br>console.log(myObject[keyName]); // Returns &quot;world&quot;</pre><p><strong>NOTE:</strong> Bracket notation cannot be used to access or add object methods.</p><p><strong>NOTE 2:</strong> Sometimes you will find that you have to use bracket notation as dot notation does not always work. If for example, you are looping through the properties of an object using a for loop, object.iterator will not work because JavaScript will be looking for a key called iterator which does not exist, and you will get undefined. When you use brackets, JavaScript interprets the value of what is inside as the actual key name. Take a look a the example below.</p><p>Another reason why you would use bracket notation is if the key is in the form of a string (ex. &quot;my key name&quot;: value).</p><pre>// Initialize a wizard object<br>let wizard = {<br>  health: 5,<br>  type: &quot;magic&quot;,<br>  specialization: &quot;fire&quot;,<br>  spells: [&quot;fireball&quot;, &quot;conflaguration&quot;],<br>  inventory: [&quot;apple&quot;, &quot;scroll&quot;, &quot;potion&quot;],<br>};<br><br>// Retrieve and log the value of each property<br>// of the wizard object using bracket notation<br>for (const key in wizard) {<br>  console.log(`${key}: ${wizard[key]}`);<br>}<br><br>// The word &quot;key&quot; inside the brackets is being interpreted<br>// as the current key name of the iteration<br>// (i.e. health, type, specialization, etc.)<br>// Results of running above for loop:<br>/*<br>health: 5<br>type: magic<br>specialization: fire<br>spells: fireball,conflaguration<br>inventory: apple,scroll,potion<br> */<br><br>// Retrieve and log the value of each property<br>// of the wizard object using dot notation<br>for (const key in wizard) {<br>  console.log(`${key}: ${wizard.key}`);<br>}<br><br>// Notice how all the values are undefined<br>// This is because JavaScript is looking for a key<br>// named &quot;key&quot; but it does not exist, so we get<br>// a value of `undefined` returned instead<br>// Results of running above for loop:<br>/*<br>health: undefined<br>type: undefined<br>specialization: undefined<br>spells: undefined<br>inventory: undefined<br> */</pre><h4>Should I use dot notation or bracket notation?</h4><p>Use dot notation unless you have to use bracket notation, such as when using a for loop to access the properties of an object using an iterator or if the key name is in the form of a string.</p><h4>Removing an Object’s Properties using the delete operator:</h4><p>The delete operator can be used to remove a property from an object.</p><p>The delete operator will return true if deletion of the specified property was successful and will return false otherwise.</p><pre>// Initialize a wizard object<br>let wizard = {<br>  health: 5,<br>  type: &quot;magic&quot;,<br>  specialization: &quot;fire&quot;,<br>  spells: [&quot;fireball&quot;, &quot;conflaguration&quot;],<br>  inventory: [&quot;apple&quot;, &quot;scroll&quot;, &quot;potion&quot;],<br>  castSpell: function () {<br>    console.log(&quot;Wizard casts...&quot;, this.spells[1]);<br>  },<br>};<br><br>console.log(wizard);<br>// {<br>//   health: 5,<br>//   type: &#39;magic&#39;,<br>//   specialization: &#39;fire&#39;,<br>//   spells: [ &#39;fireball&#39;, &#39;conflaguration&#39; ],<br>//   inventory: [ &#39;apple&#39;, &#39;scroll&#39;, &#39;potion&#39; ],<br>//   castSpell: [Function: castSpell]<br>// }<br><br>console.log(delete wizard.inventory); // returns true<br>console.log(delete wizard.castSpell); // returns true<br>console.log(wizard);<br>// {<br>//   health: 5,<br>//   type: &#39;magic&#39;,<br>//   specialization: &#39;fire&#39;,<br>//   spells: [ &#39;fireball&#39;, &#39;conflaguration&#39; ]<br>// }</pre><p><strong>NOTE</strong>: There are some technicalities that you should understand about what delete can and cannot do. You can see more in the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete">MDN documentation</a>.</p><ul><li>If the property you are trying to remove does not exist, delete will still return true. This is because the return value of delete is based on if the operation was successful, not whether or not a property exists.</li><li>delete only works on properties that belong to the object instance and not ones that exist in the object&#39;s prototype chain. So if an object instance has the same property name as a property in the prototype chain and you use delete to remove that property from the object instance, the object will just use the property from the prototype instead.</li></ul><p>Example of delete returning true when trying to delete a property that is not part of the object</p><pre>// Initialize a wizard object<br>let wizard = {<br>  health: 5,<br>  type: &quot;magic&quot;,<br>  specialization: &quot;fire&quot;,<br>  spells: [&quot;fireball&quot;, &quot;conflaguration&quot;],<br>  inventory: [&quot;apple&quot;, &quot;scroll&quot;, &quot;potion&quot;],<br>  castSpell: function () {<br>    console.log(&quot;Wizard casts...&quot;, this.spells[1]);<br>  },<br>};<br><br>console.log(delete wizard.vehicles); // returns true<br>console.log(delete wizard.pets); // returns true</pre><h3>Iterating Over an Object’s Properties:</h3><h4>for…in loop:</h4><p>Unlike arrays or strings, the object does not have a built in length method so you cannot iterate over an object’s properties using a traditional for loop. You can use a for...in loop instead to iterate over properties of an object.</p><p>The iterator takes on the value of the object’s keys and loops through all of the keys in the object. Remember, since objects don’t have an order to them, the properties may not be extracted in the same order that they were written in.</p><pre>// Initialize a wizard object<br>let wizard = {<br>  health: 5,<br>  type: &quot;magic&quot;,<br>  specialization: &quot;fire&quot;,<br>  spells: [&quot;fireball&quot;, &quot;conflaguration&quot;],<br>  inventory: [&quot;apple&quot;, &quot;scroll&quot;, &quot;potion&quot;],<br>};<br><br>for (const property in wizard) {<br>  console.log(`${property}: ${wizard[property]}`);<br>}<br><br>// health: 5<br>// type: magic<br>// specialization: fire<br>// spells: fireball,conflaguration<br>// inventory: apple,scroll,potion</pre><p><strong>NOTE:</strong> The for...in method iterates over ALL enumerable properties of an object which are keyed by strings, <em>including inherited enumerable properties</em> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in">MDN</a>. The alternative solutions to iterating over object properties do not iterate over inherited properties of the object.</p><h4>Accessing object keys using Object.keys():</h4><p>Using the Object.keys() method on an object returns an array containing all of the keys in the object. The keys which are returned as elements in the array are converted to strings.</p><pre>let myObject = {<br>  key1: 1,<br>  key2: &quot;hi&quot;,<br>  key3: [1, 2, 3],<br>  key4: { myKey: &quot;myValue&quot; },<br>  key5: function () {<br>    console.log(&quot;hello&quot;);<br>  },<br>};<br><br>let keys = Object.keys(myObject);<br>console.log(keys); // [ &#39;key1&#39;, &#39;key2&#39;, &#39;key3&#39;, &#39;key4&#39;, &#39;key5&#39; ]</pre><p>The Object.keys() can be used in conjunction with a for...of loop to iterate over the keys in an object:</p><pre>let myObject = {<br>  key1: 1,<br>  key2: &quot;hi&quot;,<br>  key3: [1, 2, 3],<br>  key4: { myKey: &quot;myValue&quot; },<br>  key5: function () {<br>    console.log(&quot;hello&quot;);<br>  },<br>};<br><br>for (const key of Object.keys(myObject)) {<br>  console.log(`${key}: ${myObject[key]}`);<br>}<br><br>/* Output of code:<br>key1: 1<br>key2: hi<br>key3: 1,2,3<br>key4: [object Object]<br>key5: function () {<br>    console.log(&quot;hello&quot;);<br>  }<br>*/</pre><h4>Accessing object values using Object.values():</h4><p>Using the Object.values() method on an object returns an array containing all of the values in the object.</p><pre>let myObject = {<br>  key1: 1,<br>  key2: &quot;hi&quot;,<br>  key3: [1, 2, 3],<br>  key4: { myKey: &quot;myValue&quot; },<br>  key5: function () {<br>    console.log(&quot;hello&quot;);<br>  },<br>};<br><br>let values = Object.values(myObject);<br>console.log(values); // [ 1, &#39;hi&#39;, [ 1, 2, 3 ], { myKey: &#39;myValue&#39; }, [Function: key5] ]</pre><p>The Object.values() can be used in conjunction with a for...of loop to iterate over the values in an object:</p><pre>let myObject = {<br>  key1: 1,<br>  key2: &quot;hi&quot;,<br>  key3: [1, 2, 3],<br>  key4: { myKey: &quot;myValue&quot; },<br>  key5: function () {<br>    console.log(&quot;hello&quot;);<br>  },<br>};<br><br>for (const value of Object.values(myObject)) {<br>  console.log(value);<br>}<br><br>/* Output of code:<br>1<br>hi<br>[ 1, 2, 3 ]<br>{ myKey: &#39;myValue&#39; }<br>[Function: key5]<br>*/</pre><p><strong>NOTE:</strong> This is typically less useful than the Object.keys() method since you can&#39;t do much with just the values of the object other than print them out.</p><h4>Accessing the keys and values of an object using Object.entries():</h4><p>The Object.entries() method returns an array with nested arrays. Each nested array represents a property of the object. The 1st element of each sub-array is the key of a property and the 2nd element is the value corresponding to the same property.</p><pre>let myObject = {<br>  key1: 1,<br>  key2: &quot;hi&quot;,<br>  key3: [1, 2, 3],<br>  key4: { myKey: &quot;myValue&quot; },<br>  key5: function () {<br>    console.log(&quot;hello&quot;);<br>  },<br>};<br><br>let entries = Object.entries(myObject);<br>console.log(entries);<br><br>/* Output of Code<br>[<br>  [ &#39;key1&#39;, 1 ],<br>  [ &#39;key2&#39;, &#39;hi&#39; ],<br>  [ &#39;key3&#39;, [ 1, 2, 3 ] ],<br>  [ &#39;key4&#39;, { myKey: &#39;myValue&#39; } ],<br>  [ &#39;key5&#39;, [Function: key5] ]<br>]<br>*/</pre><p>Since the output of Object.entries() still provides us with an array, we can use the for...of loop to loop through both the keys and values of the object.</p><pre>let myObject = {<br>  key1: 1,<br>  key2: &quot;hi&quot;,<br>  key3: [1, 2, 3],<br>  key4: { myKey: &quot;myValue&quot; },<br>  key5: function () {<br>    console.log(&quot;hello&quot;);<br>  },<br>};<br><br>for (const entry of Object.entries(myObject)) {<br>  // Each entry represents a property of the object<br>  // entry[0] is the key of the current property<br>  // entry[1] is the value of the current property<br>  console.log(`${entry[0]}: ${entry[1]}`);<br>}<br><br>/* Output of Code<br>key1: 1<br>key2: hi<br>key3: 1,2,3<br>key4: [object Object]<br>key5: function () {<br>    console.log(&quot;hello&quot;);<br>  }<br>*/</pre><h4>Using Destructuring to Simplify Iteration of keys and values of Objects using Object.entries():</h4><p>Destructuring syntax uses string or object literals on the left hand side of the assignment operator to destructure and map elements of arrays or properties of objects to new variables.</p><pre>// ===================<br>// Array Destructuring<br>// ===================<br><br>// Initialize an array<br>const myArray = [1, 2, 3, &quot;hi&quot;];<br><br>// Use destructuring to assign the values of myArray to variables<br>// The values of myArray are being &quot;unpacked&quot;<br>// and each value is mapped to a variable name in the array<br>// to the left of the assignment operator<br>// the value of 1 is mapped to the variable name &quot;a&quot;<br>// the value of 2 is mapped to the variable name &quot;b&quot;<br>// the value of 3 is mapped to the variable name &quot;c&quot;<br>// the value of &quot;hi&quot; is mapped to the variable name &quot;d&quot;<br><br>const [a, b, c, d] = myArray;<br>// [a, b, c, d] = [1, 2, 3, &quot;hi&quot;]<br><br>// Print the values of the a, b, c, d variables which were<br>// assigned using array destructuring<br>console.log(`a:`, a); // a: 1<br>console.log(`b:`, b); // b: 2<br>console.log(`c:`, c); // c: 3<br>console.log(`d:`, d); // d: hi<br><br>// ====================<br>// Object Destructuring<br>// ====================<br><br>// Initialize an object<br>const myObject = {<br>  key1: 1,<br>  key2: &quot;hi&quot;,<br>  key3: [1, 2, 3],<br>  key4: { myKey: &quot;myValue&quot; },<br>  key5: function () {<br>    console.log(&quot;hello&quot;);<br>  },<br>};<br><br>// Destructure the properties of myObject<br>// And assign each to their own variable<br>// NOTE: For object destrucuring, the variable name<br>// must match the key name due to objects not being iterable<br>const { key1, key2, key3, key4, key5 } = myObject;<br><br>console.log(`key1 =&gt;`, key1); // key1 =&gt; 1<br>console.log(`key2 =&gt;`, key2); // key2 =&gt; hi<br>console.log(`key3 =&gt;`, key3); // key3 =&gt; [ 1, 2, 3 ]<br>console.log(`key4 =&gt;`, key4); // key4 =&gt; { myKey: &#39;myValue&#39; }<br>console.log(`key5 =&gt;`, key5); // key5 =&gt; [Function: key5]</pre><p>Now that destructuring makes a little more sense, let’s take another look at the example of iterating over the keys and values using the Object.entries() method and use destructuring to remap each item in the entry element to a &quot;key&quot; and &quot;value&quot; variable.</p><pre>let myObject = {<br>  key1: 1,<br>  key2: &quot;hi&quot;,<br>  key3: [1, 2, 3],<br>  key4: { myKey: &quot;myValue&quot; },<br>  key5: function () {<br>    console.log(&quot;hello&quot;);<br>  },<br>};<br><br>// Use array destructuring to break out a key and value<br>// variable for each iteration of the for...of loop<br>for (const [key, value] of Object.entries(myObject)) {<br>  console.log(`${key}: ${value}`);<br>}<br><br>/* Output of Code<br>key1: 1<br>key2: hi<br>key3: 1,2,3<br>key4: [object Object]<br>key5: function () {<br>    console.log(&quot;hello&quot;);<br>  }<br>*/</pre><h3>References:</h3><ul><li><a href="https://developer.mozilla.org/en-US/docs/Glossary/Primitive">MDN — Primitive</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Glossary/Mutable">MDN — Mutable</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax">MDN — Spread syntax (…)</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete">MDN — delete</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in">MDN — for…in</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment">MDN — Destructuring Assignment</a></li><li><a href="https://javascript.info/object">JavaScript.info — Objects</a></li><li><a href="https://javascript.info/object-methods">JavaScript.info — Object methods, “this”</a></li><li><a href="https://www.digitalocean.com/community/tutorials/understanding-objects-in-javascript">Understanding Objects in JavaScript</a></li><li><a href="https://www.digitalocean.com/community/tutorials/how-to-use-object-methods-in-javascript">How to Use Object Methods in JavaScript</a></li><li><a href="https://www.youtube.com/watch?v=gvicrj31JOM">Programming with Mosh: JavaScript this keyword</a></li><li><a href="https://www.javascripttutorial.net/javascript-primitive-vs-reference-values/">JavaScript Primitive vs. Reference Values</a></li><li><a href="https://attacomsian.com/blog/javascript-iterate-objects">How to Iterate through an object keys and values in JavaScript</a></li><li><a href="https://attacomsian.com/blog/objects-prototypes-classes-javascript#prototypes">Objects, Prototypes, and Classes in JavaScript</a></li><li><a href="https://www.youtube.com/watch?v=tVq4L8tnWuA">Looping Over Objects — JavaScript Tutorial</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d247257374b6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Structures in JS: Arrays]]></title>
            <link>https://medium.com/geekculture/data-structures-in-js-arrays-2347380696a0?source=rss-fb363d427808------2</link>
            <guid isPermaLink="false">https://medium.com/p/2347380696a0</guid>
            <dc:creator><![CDATA[Piotr Szponder]]></dc:creator>
            <pubDate>Mon, 19 Jul 2021 12:37:04 GMT</pubDate>
            <atom:updated>2021-07-22T06:59:57.063Z</atom:updated>
            <content:encoded><![CDATA[<p>This series of blogs will discuss various data structures in the context of JavaScript. Data structures are different ways to organize data to solve different types of problems.</p><figure><img alt="Shot with @expeditionxdrone" src="https://cdn-images-1.medium.com/proxy/0*WDGTWG7mRO_xOh3B" /><figcaption>Photo by <a href="https://unsplash.com/@chuttersnap?utm_source=ghost&amp;utm_medium=referral&amp;utm_campaign=api-credit">CHUTTERSNAP</a> / <a href="https://unsplash.com/?utm_source=ghost&amp;utm_medium=referral&amp;utm_campaign=api-credit">Unsplash</a></figcaption></figure><h3>What is an Array?:</h3><p>Officially, arrays are “list-like objects”. An array is a data structure that stores an <strong>ordered</strong> collection of values.</p><h4>Properties of an Array:</h4><ul><li>The array holds a collection of values</li><li>This allows us to organize multiple values and assign them to one variable</li><li>The values stored in an array are ordered, meaning each of the items is associated with a specific index</li><li>Array indexes in JS start with 0</li><li>The array can hold ANY type of value (number, string, boolean, NaN, undefined, other arrays, objects…)</li><li>In JS, the array can hold ANY combination of data types at the same time</li><li>The array data structure is stored in one contiguous block of memory</li><li>If an element in an array needs to be added, then the whole array may need to be moved to another location in memory to retain the continuous block of memory with the expanded array</li><li>Arrays are mutable, which means that their values can be accessed and changed at a later time (even if they are defined using a const keyword)</li></ul><p>Example of an array containing multiple data types:</p><pre>let myArray = [<br>  1,<br>  2,<br>  &quot;water&quot;,<br>  true,<br>  NaN,<br>  { name: &quot;Bob&quot; },<br>  0,<br>  undefined,<br>  [100, 200, 300],<br>];</pre><p>Example of the values of the array being accessed and changed after being declared with a const keyword. This demonstrates mutability:</p><pre>const myArray = [1, 2, 3, 4, 5];<br>console.log(myArray); // [ 1, 2, 3, 4, 5 ]<br><br>myArray[0] = 100;<br>console.log(myArray); // [ 100, 2, 3, 4, 5 ]</pre><h3>How to Create an Array:</h3><p>There are 2 common ways of creating an array, using bracket notation and by calling the Array() constructor function.</p><p><strong>NOTE:</strong> Each item in the array is referred to as an “element”.</p><h4>Creating an Array Literal Using Square Brackets:</h4><p>This is the most common way of creating an array. To create an array using square brackets, define a variable and on the right hand side of the assignment operator, add all of the values you wish to hold in the array in between square brackets, separated by commas.</p><p>Example of creating an array using square brackets:</p><pre>let myArray = [1, 2, 3, 4, 5];<br>let myArray2 = [&quot;Hi&quot;, &quot;my&quot;, &quot;name&quot;, &quot;is&quot;, &quot;Bob&quot;];<br>let myArray3 = [1, false, &quot;word&quot;];<br><br>let favoriteNum = 9;<br>let myArray4 = [1, 2, 3, favoriteNum];</pre><p><strong>NOTE:</strong> If the word “array literal” caught you off guard, take a look at the MDN resources I referenced in the resources section on literals and array literals. Just know that from a practical and functional standpoint, array literals and arrays are the same thing.</p><h4>Creating an Array using the new keyword and the Array() Constructor Function:</h4><p>To create an array using the Array() constructor, set a variable equal to new Array() with the list of values you want to store in the array inside the brackets of the Array() constructor.</p><p>Example of creating arrays using the Array() constructor method:</p><pre>let myArray = new Array(1, 2, 3, 4, 5);</pre><h3>Obtaining the length of the array using the length property</h3><p>In order to find out the length of an array, call the length property on the array using dot notation. This will return the length of the array which is the number of elements in the array.</p><pre>// Create an array<br>let myArray = [&quot;a&quot;, &quot;b&quot;, &quot;c&quot;, &quot;d&quot;];<br><br>// Create a myArrayLength variable and assign it<br>// the value equal to the length of myArray<br>let myArrayLength = myArray.length;<br>console.log(myArrayLength); // 4</pre><h3>How to Access Elements in an Array:</h3><p>In order to access an element in an array, we add a set of square brackets to the end of the array name and inside the brackets, add the index value of the array element we want to access. Remember that array indexes start at 0 in JS so the first element in the array will be at the 0th index.</p><p>Example of how accessing array elements in JS works:</p><pre>// Define an array literal using bracket notation<br>let myArray = [&quot;A&quot;, &quot;B&quot;, &quot;C&quot;];<br><br>// access the individual elements in the array and log them<br>// to the console<br>console.log(myArray[0]); // &quot;A&quot;<br>console.log(myArray[1]); // &quot;B&quot;<br>console.log(myArray[2]); // &quot;C&quot;<br><br>// undefined (there isn&#39;t a 4th element in the array)<br>console.log(myArray[3]);</pre><h4>Accessing multi-dimensional arrays</h4><p>Multi-dimensional arrays are arrays that are nested inside other arrays. The most common multi-dimensional array is a 2D array which is an array which contains 1 or more arrays as elements. You can have as many nested arrays as you like (ex. 3D, 4D…).</p><p>To access a multi-dimensional array, use as many brackets as there are “dimensions” of the array.</p><pre>let myArray = [<br>  [1, 2, 3],<br>  [4, 5, 6],<br>  [7, 8, 9],<br>];<br><br>// log the 2nd sub-array in myArray<br>console.log(myArray[1]); // [4, 5, 6]<br><br>// take the 0th element in myArray ([1, 2, 3])<br>// and access the 0th element in that sub-array (1)<br>console.log(myArray[0][0]); // 1<br><br>// take the 3rd element in myArray ([7, 8, 9])<br>// and access the 3rd element in that sub-array (9)<br>console.log(myArray[2][2]); // 9</pre><h3>How to Reassign Elements in an Array:</h3><p>In order to reassign or modify elements in an array, we access the current value of the desired element in the array and use the assignment operator to change its value.</p><p>In order to change a value of an element in an array, you need to first know what its index is. Remember that the 1st element in an array is at index 0 because JavaScript uses a 0-based index system.</p><pre>// Define an array literal using bracket notation<br>let myArray = [&quot;A&quot;, &quot;B&quot;, &quot;C&quot;];<br>console.log(myArray); // [&quot;A&quot;, &quot;B&quot;, &quot;C&quot;]<br><br>// Access the 1st element of the array<br>// and reassign it to a new value<br>myArray[0] = 1;<br>console.log(myArray); // [1, &quot;B&quot;, &quot;C&quot;]<br><br>// Access the 2nd element of the array<br>// and reassign it to a new value<br>myArray[1] = 2;<br>console.log(myArray); // [1, 2, &quot;C&quot;]<br><br>// Access the 3rd element of the array<br>// and reassign it to a new value<br>myArray[2] = 3;<br>console.log(myArray); // [1, 2, 3]</pre><h3>Adding and Removing Elements at the End of an Array:</h3><p>There are different strategies and methods (functions) that can be used to add or remove elements in an array depending on where they are located within the array.</p><p><strong>NOTE:</strong> From a computational standpoint, it is easiest and least intensive to remove or add elements to the end of an array. It takes the most time to remove or add an element to the front of the array because the indexes of all the elements in the array then need to be changed to account for the removal or addition of a new element. In the case of adding and removing elements from the back of the array, none of the other elements in the array need to change their index.</p><h4>Using square brackets to append to the end of the array:</h4><p>You can use the reassignment process to actually add to the end of the array.</p><p><strong>NOTE:</strong> It is HIGHLY recommended to use the .push() method instead of this way to append elements to the end of the array.</p><pre>// Define an array literal using bracket notation<br>let myArray = [&quot;A&quot;, &quot;B&quot;, &quot;C&quot;];<br>console.log(myArray); // [&quot;A&quot;, &quot;B&quot;, &quot;C&quot;]<br><br>myArray[3] = &quot;D&quot;;<br>console.log(myArray); // [&quot;A&quot;, &quot;B&quot;, &quot;C&quot;, &quot;D&quot;]<br><br>myArray[5] = &quot;E&quot;;<br>console.log(myArray);<br>// [ &#39;A&#39;, &#39;B&#39;, &#39;C&#39;, &#39;D&#39;, &lt;1 empty item&gt;, &#39;E&#39; ] (from node)<br>// [&quot;A&quot;, &quot;B&quot;, &quot;C&quot;, empty × 2, &quot;E&quot;] (from web console)</pre><h4>.push() to append an element to the end of an array:</h4><p>Use the push() method to append 1 or more elements to the end of an array.</p><p>The push() method will also return the new length of the array.</p><pre>// Define an array literal using bracket notation<br>let myArray = [&quot;A&quot;, &quot;B&quot;, &quot;C&quot;];<br>console.log(myArray); // [&quot;A&quot;, &quot;B&quot;, &quot;C&quot;]<br><br>// Append the &quot;D&quot; string to the end of the array<br>myArray.push(&quot;D&quot;);<br>console.log(myArray); // [&quot;A&quot;, &quot;B&quot;, &quot;C&quot;, &quot;D&quot;]<br><br>// Append the &quot;E&quot; string to the end of the array<br>myArray.push(&quot;E&quot;);<br>console.log(myArray); // [&quot;A&quot;, &quot;B&quot;, &quot;C&quot;, &quot;D&quot;, &quot;E&quot;]<br><br>// Append multiple values to the end of the array<br>myArray.push(&quot;X&quot;, &quot;Y&quot;, &quot;Z&quot;);<br>// [&#39;A&#39;, &#39;B&#39;, &#39;C&#39;,&#39;D&#39;, &#39;E&#39;, &#39;X&#39;,&#39;Y&#39;, &#39;Z&#39;]<br>console.log(myArray);<br><br>// console.log the return value of the push() method<br>// (the length of the new array)<br>console.log(myArray.push(1)); // 9<br>console.log(myArray.push(2)); // 10<br>console.log(myArray.push(3)); // 11<br>console.log(myArray.push(4, 5, 6)); // 14</pre><h4>.pop() to remove an element from the end of an array:</h4><p>The pop() method removes the <strong>LAST</strong> element in the array and returns the value of the element which was removed.</p><p>Unlike the push() method which allows you to ADD multiple elements to the end of the array, you can only remove ONE element (the last one) using the push() method.</p><pre>// Define an array literal using bracket notation<br>let myArray = [1, 2, 3, 4, 5];<br>console.log(myArray); // [1, 2, 3, 4, 5]<br><br>// Remove the last element in the array<br>myArray.pop();<br>console.log(myArray); // [1, 2, 3, 4]<br><br>// Remove the last element in the array<br>myArray.pop();<br>console.log(myArray); // [1, 2, 3]<br><br>// Remove the last element in the array and print out its value<br>console.log(myArray.pop()); // 3<br>console.log(myArray); // [1, 2]</pre><h3>Adding and Removing Elements at the Beginning of an Array:</h3><h4>.shift() to remove an item from the start of an array:</h4><p>The shift() method removes the first element in an array and returns the value of the returned element.</p><pre>let myArray = [&quot;A&quot;, &quot;B&quot;, &quot;C&quot;];<br>console.log(myArray); // [&quot;A&quot;, &quot;B&quot;, &quot;C&quot;]<br><br>// Remove the 1st element in the array<br>myArray.shift();<br>console.log(myArray); // [&quot;B&quot;, &quot;C&quot;]<br><br>// Remove the 1st element in the array and log its value<br>console.log(myArray.shift()); // B<br>console.log(myArray); // [&quot;C&quot;]</pre><h4>.unshift() to add an item to the beginning of an array:</h4><p>The unshift() method adds one (or more) elements to the beginning of the array and returns the new length of the array.</p><pre>let myArray = [&quot;A&quot;, &quot;B&quot;, &quot;C&quot;];<br>console.log(myArray); // [&quot;A&quot;, &quot;B&quot;, &quot;C&quot;]<br><br>// Add an element to the beginning of the array<br>myArray.unshift(&quot;Z&quot;);<br>console.log(myArray); // [&quot;Z&quot;, &quot;A&quot;, &quot;B&quot;, &quot;C&quot;]<br><br>// Add multiple elements to the beginning of the array<br>myArray.unshift(1, 2, 3);<br>console.log(myArray); // [1, 2, 3, &quot;Z&quot;, &quot;A&quot;, &quot;B&quot;, &quot;C&quot;]<br><br>// Review the new length of the array after use of the unshift method<br>console.log(myArray.unshift(99)); // 8<br>console.log(myArray); // [99, 1, 2, 3, &quot;Z&quot;, &quot;A&quot;, &quot;B&quot;, &quot;C&quot;];</pre><h3>Adding, Removing and Replacing Elements inside an Array using splice():</h3><p>The splice() method can be used to add, remove and replace elements inside an array starting at a given index. For more information on the splice() method, review the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice">MDN documentation on splice()</a>.</p><p>To help with explaining how to use splice(), review the syntax and explanation of the parameters below taken from the MDN web page:</p><pre>splice(start)<br>splice(start, deleteCount)<br>splice(start, deleteCount, item1)<br>splice(start, deleteCount, item1, item2, itemN)</pre><ul><li>start: This is the index of the element in the array where you want to start either adding, removing or replacing elements in the array. Basically, it’s your starting point.</li><li>deleteCount: This is the number of elements you want to delete/remove to the right of the start index. If you do not want to remove any elements in the array, just add elements, set the value of deleteCount to 0.</li><li>item1, item2, … itemN: These are the element(s) that will be inserted or replaced into the array using the splice() method.</li></ul><p>The splice() method returns an array containing all of the elements which were removed from the array which splice() operated on. If no elements were removed, an empty array will be returned.</p><p><strong>NOTE: </strong>It is important to understand thatsplice() modifies the existing array and since arrays arereference types, you need to be careful in case you are not intending to modify the contents of the original array.</p><h4>Adding Elements inside an Array using splice():</h4><p>To add elements inside an array using the splice() method, you need to input the starting index, set the 2nd parameter (deleteCount) to 0, and then input as many elements as you wish to put inside the array using the splice method.</p><p><strong>NOTE:</strong> If you want to add elements in between 2 existing elements in the array (say “a” and “b”), make sure your start index in the splice() method represents the current index of the element which will be to the right of the insertion (“b” in this example). This is because the way splice() works, it inserts at the start index. So whatever is currently at the start index gets pushed over to the right when performing element insertion.</p><pre>// Initialize an array<br>let myArray = [&quot;a&quot;, &quot;b&quot;, &quot;c&quot;, &quot;d&quot;];<br>console.log(myArray); // [&quot;a&quot;, &quot;b&quot;, &quot;c&quot;, &quot;d&quot;]<br><br>// add a number in between &quot;c&quot; and &quot;d&quot;.<br>myArray.splice(3, 0, 1);<br>console.log(myArray); // [&quot;a&quot;, &quot;b&quot;, &quot;c&quot;, 1, &quot;d&quot;]<br><br>// add 2 additional numbers in between 1 and &quot;d&quot;<br>myArray.splice(4, 0, 2, 3);<br>console.log(myArray); // [&quot;a&quot;, &quot;b&quot;, &quot;c&quot;, 1, 2, 3, &quot;d&quot;]</pre><h4>Removing Elements inside an Array using splice():</h4><p>To remove elements inside an array using splice(), set the deleteCount parameter (2nd parameter) to 1 or more depending on how many elements you wish to remove. You still set the start index to where you wish to start your deletion from. Don&#39;t put in a third parameter if you only want to delete elements in an array using splice().</p><pre>// Initialize an array<br>let myArray = [&quot;a&quot;, &quot;b&quot;, &quot;c&quot;, &quot;d&quot;];<br>console.log(myArray); // [&quot;a&quot;, &quot;b&quot;, &quot;c&quot;, &quot;d&quot;]<br><br>// Remove &quot;b&quot; from the array<br>myArray.splice(1, 1);<br>console.log(myArray); // [&quot;a&quot;, &quot;c&quot;, &quot;d&quot;]<br><br>// Remove &quot;c&quot; and &quot;d&quot; from the array<br>myArray.splice(1, 2);<br>console.log(myArray); // [&quot;a&quot;]</pre><h4>Replacing Elements inside an Array using splice():</h4><p>Replacing elements inside an array using the splice() method is essentially a combination of adding and removing elements in an array. Set the value of the start index to where you want to start your replacement, set the 2nd parameter (deleteCount) to how many elements you wish to remove from the current array. Then as a third+ parameter, add either one or more elements which you wish to insert into the array.</p><pre>// Initialize an array<br>let myArray = [&quot;a&quot;, &quot;b&quot;, &quot;c&quot;, &quot;d&quot;];<br>console.log(myArray); // [&quot;a&quot;, &quot;b&quot;, &quot;c&quot;, &quot;d&quot;]<br><br>// Replace &quot;b&quot; in the array with 1<br>myArray.splice(1, 1, 1);<br>console.log(myArray); // [&quot;a&quot;, 1, &quot;c&quot;, &quot;d&quot;]<br><br>// Replace &quot;d&quot; in the array with 2 and 3<br>myArray.splice(3, 1, 2, 3);<br>console.log(myArray); // [&quot;a&quot;, 1, &quot;c&quot;, 2, 3]</pre><h3>How to Obtain the Index of an Element in an Array using .indexOf():</h3><p>There will be occasions where you will want to search an array and identify the index of a specific element. You can do this using the indexOf() method. Note that if there are multiple instances of the same value in the array, the indexOf() method will only return the index of the 1st occurence of the value. If indexOf() does not find the specified value in the array, it will return -1.</p><pre>// Initialize an array<br>let myArray = [&quot;One&quot;, &quot;Two&quot;, &quot;Three&quot;, &quot;Four&quot;];<br><br>// Return the index of &quot;Two&quot; in the array<br>console.log(myArray.indexOf(&quot;Two&quot;)); // 1<br><br>// Return the index of &quot;Four&quot; in the array<br>console.log(myArray.indexOf(&quot;Four&quot;)); // 3<br><br>// Return the index of &quot;Five&quot; in the array<br>// Note that &quot;Five&quot; is not in the array<br>console.log(myArray.indexOf(&quot;Five&quot;)); // -1</pre><p>The indexOf() method optionally accepts a 2nd parameter which specifies the starting index for the search. The below example taken from <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf">MDN</a> shows how to use this optional parameter to create an array which contains the indicies of all of the instances of the variable &quot;a&quot; in a given array.</p><pre>// Initialize an empty array indicies which will<br>// hold all of the indicies of the values of &quot;a&quot;<br>// found in the &quot;array&quot; variable<br>var indices = [];<br><br>// Create an array with multiple instances of &quot;a&quot;<br>var array = [&quot;a&quot;, &quot;b&quot;, &quot;a&quot;, &quot;c&quot;, &quot;a&quot;, &quot;d&quot;];<br><br>// Initialize the element in the array variable which<br>// will be searched for using the indexOf() method<br>var element = &quot;a&quot;;<br><br>// Initialize the idx variable which holds the index<br>// of the 1st occurance of &quot;element&quot; in &quot;array&quot;<br>var idx = array.indexOf(element);<br><br>// Run this loop while idx is not -1<br>while (idx != -1) {<br>  // push the current value stored in idx to the indicies<br>  // array<br>  indices.push(idx);<br><br>  // Update the value of idx with a new value<br>  // based on the indexOf() method but starting from the<br>  // next index up of the previous &quot;element&quot; in &quot;array&quot;<br>  idx = array.indexOf(element, idx + 1);<br>}<br>console.log(indices);<br>// [0, 2, 4]</pre><h3>How to Sort Arrays using the sort() method:</h3><p>There is a built-in sort() method which can be used to sort the elements in an array.</p><p>By default, the sort() method iterates over every element in the array, converts the elements in the array to strings and then sorts them in ascending order. This may be fine if you are sorting strings but if you have numbers in the array for example, they will be converted to strings and sorted. The problem with this is that a number converted to a string is sorted by Unicode value, and not by the actual numerical value. So &quot;100&quot; will be sorted before &quot;8&quot; for example.</p><p>To properly sort an array of numbers using the sort() method, you need to provide it with a comparison function or condition. The comparison function accepts 2 arguments, representing the current element in the iteration as well as the next element in the iteration. Basically, the comparison function accepts 2 adjacent values (typically referred to as &quot;a&quot; and &quot;b&quot;) or pairs of elements. If the comparison function returns a value that is greater than 0, then the 2nd element (&quot;b&quot;) is sorted before the 1st element (&quot;a&quot;). If the comparison function returns a value &lt;=0, then the current order of the 1st and 2nd element is preserved.</p><pre>// Define a comparison function that will be used<br>// to sort the array in ascending order<br>function compareAscending(a, b) {<br>  // if a &gt; b, return 1<br>  // The sort() method will flip the order of a and b<br>  if (a &gt; b) {<br>    return 1;<br>    // Do not flip the order of a and b otherwise<br>  } else {<br>    return -1;<br>  }<br>}<br><br>// Define a comparison function that will be used<br>// to sort the array in descending order<br>function compareDescending(a, b) {<br>  // if a &lt; b, return 1<br>  // The sort() method will flip the order of a and b<br>  if (a &lt; b) {<br>    return 1;<br>    // Do not flip the order of a and b otherwise<br>  } else {<br>    return -1;<br>  }<br>}<br><br>// Define an array with unsorted numbers<br>let unsorted = [5, 1, 7, 3, 10, 9, 2, 4, 6, 8];<br><br>// Test the sort() method without the use of comparison function<br>console.log(&quot;Using sort() method:&quot;);<br>console.log(unsorted.sort());<br><br>// Test the sort() method using the compareAscending function<br>console.log(&quot;Using sort() method with compareAscending:&quot;);<br>console.log(unsorted.sort((a, b) =&gt; compareAscending(a, b)));<br><br>// Test the sort() method using the compareDescending function<br>console.log(&quot;Using sort() method with compareDescending:&quot;);<br>console.log(unsorted.sort((a, b) =&gt; compareDescending(a, b)));</pre><h4>sort() method shorthand for sorting arrays with numbers</h4><p>There is a shorthand way to use arrow functions for the sort() method to help sort arrays with numbers. Instead of writing a comparison function with an if statement like we did in the above example, create a comparison function which accepts 2 inputs (a and b) and returns either the difference of a - b or b-a. Returning a-b will sort the array in ascending order while b-a will sort in descending order.</p><pre>// Define an array with unsorted numbers<br>let unsorted = [5, 1, 7, 3, 10, 9, 2, 4, 6, 8];<br><br>// Sort the unsorted array in ascending order<br>let sortedAscending = unsorted.sort((a, b) =&gt; a - b);<br>// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];<br>console.log(sortedAscending);<br><br>// Sort the unsorted array in descending order<br>let sortedDescending = unsorted.sort((a, b) =&gt; b - a);<br>// [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]<br>console.log(sortedDescending);</pre><h3>Reversing Arrays:</h3><p>Use the reverse() method to reverse the order of the elements in an array.</p><pre>let myArray = [1, 2, 3, 4, 5];<br>console.log(myArray); // [1, 2, 3, 4, 5]<br><br>// Reverse myArray<br>myArray.reverse();<br>console.log(myArray); // [ 5, 4, 3, 2, 1 ]<br><br>let myArray2 = [&quot;Hi&quot;, &quot;my&quot;, &quot;name&quot;, &quot;is&quot;, &quot;joe&quot;];<br>console.log(myArray2); // [&quot;Hi&quot;, &quot;my&quot;, &quot;name&quot;, &quot;is&quot;, &quot;joe&quot;]<br><br>// Reverse myArray2<br>myArray2.reverse();<br>console.log(myArray2); // [ &#39;joe&#39;, &#39;is&#39;, &#39;name&#39;, &#39;my&#39;, &#39;Hi&#39; ]</pre><h3>Looping through Arrays:</h3><p>Several methods exist for looping through the elements in an array. This is a common practice used to access and perform operations on elements in an array.</p><h4>for loops:</h4><p>Use the iterator in the for loop to access all (or some) of the elements in an array. In order for this to call the length method on the array to obtain the length of the array and use it as the end condition in the for loop.</p><p>Typically, we will use the for loop to access each element in the array from start to finish. However, we can also use the flexibility of the for loop to iterate over only specific values in the array (ex. iterate every other value or iterate from the end of the loop to the start of the loop)</p><pre>// Initialize an array<br>let myArray = [&quot;One&quot;, &quot;Two&quot;, &quot;Three&quot;, &quot;Four&quot;];<br><br>// Iterate over every value in the array<br>// from start to finish and print it to the console<br>for (let i = 0; i &lt; myArray.length; i++) {<br>  console.log(myArray[i]);<br>}<br>/*<br>One<br>Two<br>Three<br>Four<br>*/<br><br>// Iterate over every odd value in the array<br>// and print it to the console<br>for (let i = 0; i &lt; myArray.length; i += 2) {<br>  console.log(myArray[i]);<br>}<br>/*<br>One<br>Three<br>*/<br><br>// Iterate over every even value in the array<br>// and print it to the console<br>for (let i = 1; i &lt; myArray.length; i += 2) {<br>  console.log(myArray[i]);<br>}<br>/*<br>Two<br>Four<br>*/<br><br>// Iterate over every value in the array<br>// starting with the last value and ending in the first<br>// value, print the result to the console<br>for (let i = myArray.length - 1; i &gt;= 0; i--) {<br>  console.log(myArray[i]);<br>}<br>/*<br>Four<br>Three<br>Two<br>One<br>*/</pre><h4>for…of loop:</h4><p>The for...of loop works very similar to the standard for loop implementation. Instead of using an iterator that then needs to be used to access the element of the array using brackets, each iteration of the for...of extracts a consecutive element in the array as the value for that iteration.</p><p>The drawback to using for...of loops is that you cannot access the index of the element as you can with a standard for loop or the forEach() method (see below for more information on the forEach() method).</p><pre>// Initialize an array<br>let myArray = [&quot;One&quot;, &quot;Two&quot;, &quot;Three&quot;, &quot;Four&quot;];<br><br>// In the for...of condition, during each iteration,<br>// number, which is the iterator, takes on the value<br>// of the next element in the specified array<br>// (myArray in this case)<br>// So number will take on the value of &quot;One&quot; in the 1st iteration<br>// Then in the second iteration, it will become &quot;Two&quot;,<br>// followed by &quot;Three&quot;, and &quot;Four&quot;<br>for (let number of myArray) {<br>  console.log(number);<br>}<br>/*<br>One<br>Two<br>Three<br>Four<br>*/</pre><p><strong>NOTE:</strong> While we will not discuss this here, the for...of loop can be used to iterate over any JS type which is considered iterable. Other examples of iterable types in JS (other than arrays) include strings, Map, and Set.</p><h4>forEach() method:</h4><p>The forEach() calls a function for each element in the array starting from the 0th element and up to the last element in the array. The forEach() function optionally allows us to access the index of the current element being iterated.</p><p>The forEach() returns undefined.</p><p>All you need to do to call the forEach() method on an array is to enter a name for the current element being iterated on (ex. &quot;element&quot;) and use arrow-function notation to specify the function or block of code that you want to run for each iteration.</p><pre>// Initialize an array<br>let myArray = [&quot;a&quot;, &quot;b&quot;, &quot;c&quot;, &quot;d&quot;];<br>console.log(myArray); // 4<br><br>// Use the forEach() method to log each<br>// element in the array to the console<br>myArray.forEach((element) =&gt; console.log(element));<br><br>// Initialize a new array<br>let myArray2 = [1, 2, 3, 4, 5];<br>console.log(myArray2);<br><br>// Use the forEach() method to add 1 to each<br>// element in the array and log it to the console<br>// Notice that the original values of myArray2 are not changed by the forEach() loop<br>myArray2.forEach((element) =&gt; {<br>  element += 1;<br>  console.log(element);<br>});<br>console.log(myArray2);<br><br>// Use the forEach() method to add 1 to each<br>// element in the array and log it to the console<br>// This time, store element in a new array<br>// We can do this because the forEach() method allows us to optionally include the index of the current element<br><br>let newArray = [];<br><br>myArray2.forEach((element, i) =&gt; {<br>  element += 1;<br>  newArray[i] = element;<br>  console.log(element);<br>});<br>console.log(newArray);</pre><p><strong>NOTE:</strong> The function called by the forEach() method is referred to as a callback function because it is a function being called from within another function. If you want to find out more about callback functions, I recommend <a href="https://www.youtube.com/watch?v=cNjIUSDnb9k">this video made by Ania Kubow</a> as it really helped me understand how callback functions work and how they are invoked.</p><h3>Creating a new array from modified elements of an existing array using .map():</h3><p>The map() method is very similar to the forEach() method. The only difference between the 2 methods is that map() returns a new array while forEach() returns undefined. Neither method modifies the array they are called on by default.</p><p>The map() method takes a callback function that performs operations on each element in the array. map() then takes those modified values and stores them in a new array which is then returned by the map method.</p><pre>// Initialize a new array<br>let myArray = [1, 2, 3, 4, 5];<br>console.log(myArray); // [ 1, 2, 3, 4, 5 ]<br><br>// create a new array using the map method which holds the<br>//squared values of myArray<br>let square = myArray.map((element) =&gt; element ** 2);<br>console.log(square); // [ 1, 4, 9, 16, 25 ]<br><br>// create a new array using the map method which holds the<br>// cubed values of myArray<br>let cube = myArray.map((element) =&gt; {<br>  return element ** 3;<br>});<br>console.log(cube); // [ 1, 8, 27, 64, 125 ]</pre><h3>How to remove unwanted elements in an array using .filter():</h3><p>The filter() method uses a callback function or a code block to perform a conditional test on each element in the array. Any element that passes the conditional is then put in a new array by the filter() method. The filter() method returns the new array with the &quot;filtered&quot; elements. If none of the elements pass the conditional test, an empty array will be returned instead.</p><p>The code below shows you multiple different ways of implementing the filter() method:</p><pre>let myArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];<br><br>// Use the filter method to create an array of even numbers<br>// from myArray<br>let even = myArray.filter((element) =&gt; element % 2 === 0);<br>console.log(even);<br><br>// Define the isOdd function<br>function isOdd(number) {<br>  if (number % 2 !== 0) {<br>    return number;<br>  }<br>}<br><br>// Use the filter method to create an array of odd elements<br>// from myArray by passing in the isOdd() callback function<br>let odd = myArray.filter((element) =&gt; isOdd(element));<br>console.log(odd);<br><br>// Use the filter method to create an array of multiples<br>// of 3 from myArray by passing in a code block<br>let multipleOf3 = myArray.filter((element) =&gt; {<br>  if (element % 3 === 0) {<br>    return element;<br>  }<br>});<br>console.log(multipleOf3);<br><br>// Use the filter method to create an array of multiples<br>// of 5 from myArray<br>let multipleOf5 = myArray.filter((element) =&gt; {<br>  return element % 5 === 0;<br>});<br>console.log(multipleOf5);</pre><h3>How to find the first occurrence of a specific element using .find():</h3><p>The find() method accepts a callback function which performs a test on each element and returns the value of the first element in the array which passes the test.</p><pre>let myArray = [1, 2, 3, 4, 5];<br>console.log(myArray); // [1, 2, 3, 4, 5]<br><br>// Find the first element in the array which is greater than 3<br>let itemFound = myArray.find((element) =&gt; element &gt; 3);<br>console.log(itemFound); // 4<br><br>// Set itemFound2 to the first element which is<br>// greater than 1 and less than 4 (should be 2)<br>let itemFound2 = myArray.find((element) =&gt; {<br>  if (element &gt; 1 &amp;&amp; element &lt; 4) {<br>    return element;<br>  }<br>});<br>console.log(itemFound2); // 2</pre><h3>Copying an array using .slice():</h3><p>Use the slice() method to copy an array or a portion of the array.</p><ul><li>If called without any parameters, the slice() method will create a copy of the whole array.</li><li>Enter a starting index as the first parameter of slice() if you want to make a copy of only a portion of the array, starting from the specified index.</li><li>You can also control where you want stop slice() from copying by entering a 2nd parameter which is the stop index.slice() will copy everything up to <strong>BUT NOT INCLUDING</strong> the stop index.</li></ul><pre>let myArray = [1, 2, 3, 4, 5];<br>console.log(myArray); // [1, 2, 3, 4, 5]<br><br>// Create a copy of myArray<br>let myArrayCopy = myArray.slice();<br>console.log(myArrayCopy); // [1, 2, 3, 4, 5]<br><br>// Create a copy of the 2nd half of myArray<br>// starting from the 2nd index (# 3)<br>let myArray2ndHalf = myArray.slice(2);<br>console.log(myArray2ndHalf); // [3, 4, 5]<br><br>// Create a slice of myArray, only copying<br>// elements at index 2 through 4<br>let myArraySlice = myArray.slice(1, 4);<br>console.log(myArraySlice); // [2, 3, 4]</pre><h4>How slice() works when copying objects inside an array:</h4><p>When copying objects in an array using slice() a <em>reference</em> to that object is copied. This means that if you change the value of that object in the original or the copied array, the change will be seen in both arrays since both of the arrays point to the same piece of data in memory due to how reference types work.</p><pre>let myArray = [[&quot;a&quot;], { letter: &quot;b&quot; }, &quot;c&quot;, &quot;d&quot;, &quot;e&quot;];<br>let myArrayCopy = myArray.slice();<br><br>// [ [ &#39;a&#39; ], { letter: &#39;b&#39; }, &#39;c&#39;, &#39;d&#39;, &#39;e&#39; ]<br>console.log(&quot;myArray:&quot;, myArray);<br><br>// [ [ &#39;a&#39; ], { letter: &#39;b&#39; }, &#39;c&#39;, &#39;d&#39;, &#39;e&#39; ]<br>console.log(&quot;myArrayCopy:&quot;, myArrayCopy);<br><br>// Change values of the nested object and array in myArray<br>myArray[1].letter = &quot;hello&quot;;<br>myArray[0][0] = 200;<br><br>// [ [ 200 ], { letter: &#39;hello&#39; }, &#39;c&#39;, &#39;d&#39;, &#39;e&#39; ]<br>console.log(&quot;myArray:&quot;, myArray);<br><br>// [ [ 200 ], { letter: &#39;hello&#39; }, &#39;c&#39;, &#39;d&#39;, &#39;e&#39; ]<br>console.log(&quot;myArrayCopy:&quot;, myArrayCopy);</pre><p>In the example above, a copy of myArray is made using splice(). myArray contains a nested array at index 0 and a nested object at index 1. splice() creates a shallow copy of any non-primitive variable type (i.e. objects and arrays for example). A shallow copy means that the reference to the value in memory is copied, not the actual value. So both the nested array and nested object in myArrayCopy and myArray actually point to the same value in memory. This means that when one value is accessed and changed, that change is reflected in both copies.</p><h3>Converting list-like iterable objects using Array.from():</h3><p>The Array.from() method will convert a list-like iterable object (a NodeList for example) and convert it to an array. This allows you to use all of the array methods on the converted array which can be helpful sometimes.</p><h3>Additional Array Methods</h3><p>There are many more array methods that I have not discussed in this article. If you want to learn more, I suggest looking at the Mozilla Developer Network (see links in resources section). They have great and detailed explanations on all topics in JavaScript.</p><h3>Resources:</h3><ul><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array">MDN — Array</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Learn/JavaScript/First_steps/Arrays">MDN — Arrays</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Glossary/Mutable">MDN — Mutable</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Glossary/Literal">MDN — Literal</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#array_literals">MDN — Array Literals</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/length">MDN — Array.prototype.length</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push">MDN — Array.prototype.push()</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/pop">MDN — Array.prototype.pop()</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/shift">MDN — Array.prototype.shift()</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/unshift">MDN — Array.prototype.unshift()</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of">MDN — for…of</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach">MDN — Array.prototype.forEach()</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf">MDN — Array.prototype.indexOf()</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort">MDN — Array.prototype.sort()</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map">MDN — Array.prototype.map()</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find">MDN — Array.prototype.find()</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse">MDN — Array.prototype.reverse()</a></li><li><a href="https://javascript.info/array">Javascript.Info — Arrays</a></li><li><a href="https://www.digitalocean.com/community/tutorial_series/working-with-arrays-in-javascript">Working with Arrays in JavaScript</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2347380696a0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/data-structures-in-js-arrays-2347380696a0">Data Structures in JS: Arrays</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Control Flow in JavaScript: Loops]]></title>
            <link>https://medium.com/geekculture/control-flow-in-javascript-loops-a4d257ab1c1b?source=rss-fb363d427808------2</link>
            <guid isPermaLink="false">https://medium.com/p/a4d257ab1c1b</guid>
            <dc:creator><![CDATA[Piotr Szponder]]></dc:creator>
            <pubDate>Sat, 17 Jul 2021 12:03:28 GMT</pubDate>
            <atom:updated>2021-07-17T17:40:27.980Z</atom:updated>
            <content:encoded><![CDATA[<p>This article is part of my Control Flow in JavaScript Series.<br>In this article, we will be discussing loops.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-67fV0oKjXS83pIT" /><figcaption>Photo by <a href="https://unsplash.com/@rohanmakhecha?utm_source=medium&amp;utm_medium=referral">Rohan Makhecha</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Why do we need loops?</h3><p>Very often in code, you will find yourself in the situation where you need to perform a particular task or tasks repeatedly.</p><p>Let’s say that you want to print to the console the numbers 1 though 10. One way to do that would be the following:</p><pre>console.log(1);<br>console.log(2);<br>console.log(3);<br>console.log(4);<br>console.log(5);<br>console.log(6);<br>console.log(7);<br>console.log(8);<br>console.log(9);<br>console.log(10);</pre><p>Ok, that’s only 10 lines of code, that’s not that bad you may say. What if instead of printing the numbers 1 through 10, you were asked to print the number 1 through 1000! Do you really want to type out 1000 console.log() statements? Instead of writing 1000 lines, we can implement the following loop for example:</p><pre>// Print out the numbers 1 through 1000 to the console<br>for (let i = 0; i &lt; 1000; i++) {<br>  console.log(i);<br>}</pre><p>Loops enable a program to repeat a piece of code for a specified (or unspecified) amount of time.</p><h3>Loop Basics</h3><p>All 3 of the standard loops (for, while, and do-while) need 3 things to run correctly:</p><ol><li>An iterator / initial condition.</li><li>A condition to evaluate to true or false to determine whether or not the loop should run. Typically, this condition is associated with the iterator / initial condition.</li><li>A way to increment the iterator / initial condition.</li></ol><h4>for loops:</h4><p>The for loop is the most often used loop out of all 3 of the standard loops.</p><p>Here is the syntax:</p><pre>for (iterator; condition; incrementIterator) {<br>  // Code in for block goes here<br>  // This code will only execute if the condition<br>  // evaluates to true<br>}</pre><p>Let’s look at an example of a for loop and step though what is happening:</p><pre>// Initialize an array<br>let myArray = [&quot;a&quot;, &quot;b&quot;, &quot;c&quot;, &quot;d&quot;, &quot;e&quot;];<br><br>// Loop through the array and print each element<br>for (let i = 0; i &lt; myArray.length; i++) {<br>  console.log(myArray[i]);<br>}<br><br>// The above loop prints out<br>// a<br>// b<br>// c<br>// d<br>// e<br><br>// This console.log() will run after the for loop has<br>// completed printing out all of the elements in the<br>// array<br>console.log(&quot;For loop ended&quot;);</pre><ol><li>When the for loop is run for the 1st time, the iterator is set to 0.</li><li>The condition is then checked and since 0 is less than myArray.length (5), the condition evaluates to true.</li><li>Since the condition evaluated to true, then the code inside the for loop is run once and the first element in the array is printed to the console.</li><li>After the code inside the loop has executed once, the iterator is incremented from 0 to 1 by i++.</li><li>After this, the condition is checked again, since 1 is less than the length of the array, the code inside the for loop is run once again and the 2nd value of the array is printed to the console.</li><li>After the code runs a second time, the iterator is again increased by 1 so now its value is 2.</li><li>The loop of checking the condition, running the code and incrementing the iterator is repeated until the iterator is incremented to the length of the array which is 5. At this point, the condition is no longer true since 5 &lt; 5 is false. This results in the for loop terminating and moving to the next set of code which is console.log(&quot;For loop ended&quot;);</li></ol><h4>while loops:</h4><p>Unlike for loops, while loops have their iterator initialized outside of the while loop declaration. Also different from the for loop, the incrementing of the iterator does not happen automatically, instead it needs to be specifically declared within the while loop code block, otherwise, the iterator will not increment and the while loop will keep looping forever. This is called an infinite loop condition. This should be avoided as once you get into an infinite loop, you cannot break out of it from within the code, you will have to manually close or quit out of your program.</p><p>Here is the syntax for a while loop:</p><pre>let iterator = someValue;<br>while (condition) {<br>  // Code goes here<br><br>  // If we don&#39;t increment the iterator here, our<br>  // loop will probably keep going to infinity<br>  iterator++;<br>}</pre><p><strong>NOTE</strong>: Technically, you don’t need an iterator in order to use a while (or a do…while) loop. However, if you don’t use an iterator, you need to have some other way of ensuring that the condition in your while loop eventually evaluates to false, otherwise you will end up with an infinite loop. Instead of using an iterator, you can have an if condition inside your loop that checks if a flag is a certain value and if it is, change the condition in the while loop to evaluate to false.</p><pre>// Initialize variable to be printed (and decremented) in loop<br>let n = 5;<br><br>// Initialize flag to be used in while loop evaluation<br>let flag = true;<br><br>// Loop while flag evaluates to true<br>while (flag) {<br>  // Log values to console<br>  console.log(&quot;Flag is true&quot;);<br>  console.log(n);<br>  n--; // Decrement n<br><br>  // Condition that flips flag to false and ends<br>  // execution of while loop<br>  if (n &lt; -5) {<br>    console.log(&quot;Flag is false&quot;);<br>    flag = false;<br>  }<br>}<br><br>/* CODE OUTPUT:<br>Flag is true<br>5<br>Flag is true<br>4<br>Flag is true<br>3<br>Flag is true<br>2<br>Flag is true<br>1<br>Flag is true<br>0<br>Flag is true<br>-1<br>Flag is true<br>-2<br>Flag is true<br>-3<br>Flag is true<br>-4<br>Flag is true<br>-5<br>Flag is false<br>*/</pre><p>Now let’s see an example where we loop through an array and print all it’s values:</p><pre>// Initialize an array<br>let myArray = [&quot;a&quot;, &quot;b&quot;, &quot;c&quot;, &quot;d&quot;, &quot;e&quot;];<br><br>// Set an iterator with an initial value<br>// for the while loop<br>let i = 0;<br><br>// Loop through the array and print each element<br>while (i &lt; myArray.length) {<br>  // Log the current element in the array to the console<br>  console.log(myArray[i]);<br><br>  // Increment the iterator<br>  i++;<br>}<br><br>// The above loop prints out<br>// a<br>// b<br>// c<br>// d<br>// e<br><br>// This console.log() will run after the loop has<br>// completed printing out all of the elements in the<br>// array<br>console.log(&quot;while loop ended&quot;);</pre><ol><li>In the example above, we initialize the iterator outside of the while loop and set it’s value to 0.</li><li>The while loop checks the condition which is i &lt; myArray.length and since i is currently 0, the loop will run and print the 1st element in the array as well as increment the iterator which is declared outside the loop.</li><li>This is then repeated with the condition of the while loop being checked before the code inside runs.</li><li>Once the iterator inside the while loop is incremented to a value 5 which is the same as the length of the array,the condition on the while loop will no longer be true and the while loop will exit and move to the next set of instructions which is to console.log(&quot;while loop ended&quot;).</li></ol><h4>do…while loops:</h4><p>Do while loops are very similar to while loops except the checking of the condition happens after the contents inside the loop are executed. This ensures that even if the condition inside the while loop will evaluate to false right away, the contents inside the loop will run once before the loop exits due to the condition evaluating to false.</p><p>Syntax of a do...while loop:</p><pre>// Initialize an iterator which will be used to control<br>// how many times the loop will run.<br>let iterator = someValue;<br><br>// Run the code inside the do code block<br>do {<br>  // Code goes here<br><br>  // If we don&#39;t increment the iterator here, our<br>  // loop will probably keep going to infinity<br>  iterator++;<br><br>  // check the condition evaluates to true<br>  // before going back and running the code again<br>  // inside the do loop<br>} while (condition);</pre><p>Example of do…while loop:</p><pre>// Initialize an array<br>let myArray = [&quot;a&quot;, &quot;b&quot;, &quot;c&quot;, &quot;d&quot;, &quot;e&quot;];<br><br>// Set an iterator with an initial value<br>// for the do...while loop<br>let i = 0;<br><br>// Loop through the array and print each element<br>do {<br>  // Log the current element in the array to the console<br>  console.log(myArray[i]);<br><br>  // Increment the iterator<br>  i++;<br>} while (i &lt; myArray.length);<br><br>// The above loop prints out<br>// a<br>// b<br>// c<br>// d<br>// e<br><br>// This console.log() will run after the loop has<br>// completed printing out all of the elements in the<br>// array<br>console.log(&quot;do...while loop ended&quot;);</pre><ol><li>Here, the iterator is also declared outside of the loop and initialized to a starting value of 0.</li><li>The code inside the do...while loop is run and the iterator is incremented by 1.</li><li>The condition in the while loop is then checked. Since 1 is less than the length of the array, the code in the do portion of the loop is run once again.</li><li>This cycle of checking the condition and running the code inside the do block is repeated until the condition inside of the while loop is no longer true. At this point, the do...while loop exits and the next section of code is run which is the console.log(&quot;do...while loop ended&quot;).</li></ol><h3>Skipping Iterations and Escaping Out of Loops:</h3><h4>break:</h4><p>The break statement in JavaScript is used inside a loop to prematurely break out of the loop. These are typically found in if statements and used to aid in the control of the loop.</p><p>A particularly useful use for the break statement is to break out of an infinite while loop.</p><p>If a break statement is found inside a nested (loop within a loop) loop, then the break statement only forces JavaScript to break out of the inner-most loop containing the break statement.</p><p>Examples of using the break statement:</p><pre>for (let i = 0; i &lt; 10; i++) {<br>  console.log(i);<br>  if (i === 3) {<br>    break;<br>  }<br>}<br><br>console.log(&quot;printing outside for loop&quot;);<br><br>/*<br>Output of code above<br>0<br>1<br>2<br>3<br>printing outside for loop<br>*/<br><br>for (let i = 0; i &lt; 5; i++) {<br>  console.log(&quot;Printing i:&quot;, i);<br>  for (let j = 0; j &lt; 5; j++) {<br>    if (j &gt; 3) {<br>      break;<br>    }<br>    console.log(&quot;Printing j:&quot;, j);<br>  }<br>}<br><br>/*<br>Output of Nested For Loop:<br>Printing i: 0<br>Printing j: 0<br>Printing j: 1<br>Printing j: 2<br>Printing j: 3<br>Printing i: 1<br>Printing j: 0<br>Printing j: 1<br>Printing j: 2<br>Printing j: 3<br>Printing i: 2<br>Printing j: 0<br>Printing j: 1<br>Printing j: 2<br>Printing j: 3<br>Printing i: 3<br>Printing j: 0<br>Printing j: 1<br>Printing j: 2<br>Printing j: 3<br>Printing i: 4<br>Printing j: 0<br>Printing j: 1<br>Printing j: 2<br>Printing j: 3<br>*/<br><br>// You can also use the break statement to break out of an infinite while loop<br><br>let counter = 0;<br>while (true) {<br>  console.log(counter);<br>  counter++;<br>  if (counter &gt; 5) {<br>    break;<br>  }<br>}<br><br>/*<br>Output of while loop:<br>0<br>1<br>2<br>3<br>4<br>5<br>*/</pre><h4>continue:</h4><p>The continue statement works similarly to to the break statement except that instead of completely breaking out of the loop containing the continue statement, continue just forces the current loop to start its next iteration, while skipping any additional statements below the continue statement.</p><p>More specifically, when the continue statement is executed, there are 2 possibilities that occur depending on the type of loop the statement is located in:</p><ul><li>For a while loop, continue forces the loop to proceed with its next iteration.</li><li>For a for loop, continue forces the loop to update the current iterator and then proceed with the next iteration.</li></ul><p>Also similar to the break statement, continue only works on the inner-most loop which contains the continue statement.</p><pre>for (let i = 0; i &lt; 5; i++) {<br>  if (i === 3) {<br>    continue;<br>  }<br>  console.log(i);<br>}<br><br>console.log(&quot;printing outside for loop&quot;);<br><br>/*<br>Notice how the value of 3 is not printed. This is because<br>the if statement triggers and the continue causes<br>the console.log(i) to get skipped and the next iteration<br>proceeds.<br>Output of code above:<br>0<br>1<br>2<br>4<br>printing outside for loop<br>*/<br><br>for (let i = 0; i &lt; 5; i++) {<br>  console.log(&quot;Printing i:&quot;, i);<br>  for (let j = 0; j &lt; 5; j++) {<br>    if (j === 2) {<br>      continue;<br>    }<br>    console.log(&quot;Printing j:&quot;, j);<br>  }<br>}<br><br>/*<br>NOTE: Notice how the number 2 is not being printed<br>inside the nested for loop. This is because of the<br>continue statement.<br>Output of Nested For Loop:<br>Printing i: 0<br>Printing j: 0<br>Printing j: 1<br>Printing j: 3<br>Printing j: 4<br>Printing i: 1<br>Printing j: 0<br>Printing j: 1<br>Printing j: 3<br>Printing j: 4<br>Printing i: 2<br>Printing j: 0<br>Printing j: 1<br>Printing j: 3<br>Printing j: 4<br>Printing i: 3<br>Printing j: 0<br>Printing j: 1<br>Printing j: 3<br>Printing j: 4<br>Printing i: 4<br>Printing j: 0<br>Printing j: 1<br>Printing j: 3<br>Printing j: 4<br>*/</pre><h3>Looping through Iterables and Objects in JS with for…of and for…in loops:</h3><h4>for…of loops:</h4><p>for...of loops are a shorthand way to write a for loop to iterate over all elements in an iterable object. strings, arrays, maps and sets are examples of iterable objects in JavaScript. Elements in an array-like object such as a NodeList can also be accessed using for...of.</p><p>When using a for...of loop, the iterator which is declared inside the conditional statement of the loop takes on the value of the current element in the iterable being evaluated.</p><pre>let myArray = [&quot;a&quot;, &quot;b&quot;, &quot;c&quot;, &quot;d&quot;, &quot;e&quot;];<br><br>for (let letter of myArray) {<br>  console.log(letter);<br>}<br><br>/*<br>Output from for...of array<br>a<br>b<br>c<br>d<br>e<br>*/</pre><h4>for…in loops:</h4><p>for...in loops iterate through properties in an object, specifically their keys.</p><pre>let myObject = {<br>  firstName: &quot;John&quot;,<br>  lastName: &quot;Doe&quot;,<br>  age: 50,<br>};<br><br>for (let property in myObject) {<br>  console.log(`${property}: ${myObject[property]}`);<br>}<br><br>/*<br>Output from the for...in loop<br>firstName: John<br>lastName: Doe<br>age: 50<br>*/</pre><p><strong>NOTE:</strong> While it is possible to use the for...in loop to iterate over an array, please only use for...in loops to iterate over object properties. for...in loops will not necessarily iterate over the array in a specific order.</p><h3>References</h3><ul><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for">MDN — for</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/while">MDN — while</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/do...while">MDN — do…while</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/continue">MDN — continue</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/break">MDN — break</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#built-in_iterables">MDN — Built-in iterables</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of">MDN — for…of</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in">MDN — for…in</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a4d257ab1c1b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/control-flow-in-javascript-loops-a4d257ab1c1b">Control Flow in JavaScript: Loops</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Control Flow in JavaScript: Conditional Statements]]></title>
            <link>https://medium.com/geekculture/control-flow-in-javascript-conditional-statements-acfdda94c97a?source=rss-fb363d427808------2</link>
            <guid isPermaLink="false">https://medium.com/p/acfdda94c97a</guid>
            <dc:creator><![CDATA[Piotr Szponder]]></dc:creator>
            <pubDate>Mon, 05 Jul 2021 23:20:32 GMT</pubDate>
            <atom:updated>2021-07-17T17:40:38.734Z</atom:updated>
            <content:encoded><![CDATA[<p>This article is part of my Control Flow in JavaScript Series. In this article, we will be discussing conditional statements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2__M-h1V0ojPOrkA" /><figcaption>Photo by <a href="https://unsplash.com/@rohanmakhecha?utm_source=medium&amp;utm_medium=referral">Rohan Makhecha</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>What is Control Flow and why do we need it?</h4><p><a href="https://en.wikipedia.org/wiki/Control_flow"><em>“In computer science, </em><strong><em>control flow</em></strong><em> is the order in which individual statements, instructions, or function calls are executed / evaluated.</em></a>”</p><p>Instead of always executing instructions linearly, often times in programming, there will be more than one possible option that can be executed, depending on the current conditions.</p><p>This results in the need to have ways to be able to branch a decision into 2 or more options, and even loop back in certain cases.</p><p>Conditional statements enable a program to select one out of 2 or more possible execution paths depending on the current conditions.</p><p>Loops enable the program to repeat a piece of code for a specified (or unspecified) amount of time.</p><h4>Truthy and Falsy</h4><p>Before diving into conditional statements, let’s understand “truthyness” and “falsyness” of values in JavaScript.</p><p>Just like how a bit in memory either only evaluates to 1 or 0 (true or false), each value in JavaScript evaluates to either true or false in a boolean context.</p><p>A value which evaluates to <em>true</em> in a boolean context is considered <strong>truthy</strong>. Most values in JavaScript are <strong>truthy</strong>. Per the Mozilla Developer Network, “all values are truthy unless they are defined as <strong>falsy</strong>.”</p><p>A value which evaluates to <em>false</em> in a boolean context is considered <strong>falsy</strong>.</p><p>List of all values in JavaScript which are <strong>falsy</strong> (evaluate to <em>false</em>):</p><ul><li>false</li><li>0</li><li>-0</li><li>0n</li><li>&quot;&quot;</li><li>null</li><li>undefined</li><li>NaN</li></ul><p>NOTE: See the <a href="https://developer.mozilla.org/en-US/docs/Glossary/Falsy">MDN Falsy</a> webpage for more information.</p><h4>Comparison Operators</h4><p>Comparison operators are in boolean statements which evaluate to either true or false depending on the conditions that are on both sides of the comparison operator.</p><p>Types of Comparison Operators:</p><ul><li>== (loose equality)</li><li>!= (negation of loose equality)</li><li>=== (strict equality)</li><li>!== (negation of strict equality)</li><li>&gt; (greater than)</li><li>&lt; (less than)</li><li>&gt;= (greater than or equal to)</li><li>&lt;= (less than or equal to)</li></ul><p>Examples of Comparison Operators:</p><pre>let x = 1;<br>let y = 2;<br>console.log(x == y); // false<br>console.log(x != y); // true<br>console.log(x === y); // false<br>console.log(x !== y); // true<br>console.log(x &gt; y); // false<br>console.log(x &lt; y); // true<br>console.log(x &gt;= y); // false<br>console.log(x &lt;= y); // true</pre><h4>Logical Operators</h4><p>Logical operators are most commonly used to link multiple boolean comparison statements and return either true or false depending on the conditions.</p><p>The 3 most common logical operators are logical AND (&amp;&amp;), logical OR (||) and logical NOT (!).</p><h4>Logical AND (&amp;&amp;)</h4><p>Logical AND (&amp;&amp;) is used in a boolean statement and evaluates to true only when both sides of the statement evaluate to true.</p><pre>console.log(true &amp;&amp; true); // true<br>console.log(true &amp;&amp; false); // false<br>console.log(false &amp;&amp; true); // false<br>console.log(false &amp;&amp; false); // false</pre><h4>Logical OR (||)</h4><p>Logical OR (||) is used in a boolean statement and evaluates to true as long as one side of the statement evaluates to true.</p><pre>console.log(true || true); // true<br>console.log(true || false); // true<br>console.log(false || true); // true<br>console.log(false || false); // false</pre><h4>Short Circuit Evaluation</h4><p>So what is actually happening “under the hood” when either &amp;&amp; or || are called to evaluate a boolean expression?</p><p>When given an expression to evaluate, both &amp;&amp; and || will evaluate the left side of the expression to either true or false. After this, depending if the operator was a Logical AND or OR, either the <em>original</em> left side of the expression is returned or the <em>original</em> right side will be returned. This is referred to short-circuit evaluation</p><p>&amp;&amp; returns the first falsy value / evaluation. If all expressions evaluate to truthy, then the right most value is returned.</p><pre>// 0 (0 is falsy, everything else is ignored)<br>console.log(0 &amp;&amp; 1 &amp;&amp; 2); // 0<br><br>// 0 (1 is truthy, so we look at the next value which is 0,<br>// since 0 is falsy, it is returned, and everything else<br>// is skipped)<br>console.log(1 &amp;&amp; 0 &amp;&amp; 2); // 0<br><br>// 0 (1 is truthy, and so is 2, so the next value to the right is 0, which is falsy, it is therefore returned)<br>console.log(1 &amp;&amp; 2 &amp;&amp; 0); // 0<br><br>// 3 (everything is truthy, return right most item)<br>console.log(1 &amp;&amp; 2 &amp;&amp; 3); // 3<br><br>// true, (both left and right sides of &amp;&amp; first evaluate to<br>// true, since true on both sides of &amp;&amp;, return true<br>// (nothing is falsy))<br>console.log(1 &lt; 2 &amp;&amp; 4 &gt; 3); // true</pre><p>|| returns the first truthy value / evaluation. If expressions evaluate to falsy, then the right most value is returned.</p><pre>// 1 (0 is falsy, so 1 is evaluated next,<br>// since 1 is truthy, it is returned and everything else<br>// is ignored)<br>console.log(0 || 1 || 2); // 1<br><br>// 1 (1 is truthy, so it is returned,<br>// everything else is ignored)<br>console.log(1 || 0 || 2); // 1<br><br>// 1 (1 is truthy, and so is 2, but since 1 was the 1st<br>// truthy value, it is returned, and everything is skipped)<br>console.log(1 || 2 || 0); // 1<br><br>// 3 (0 and undefined are both falsy, and 3 is truthy, so<br>// 3 is returned)<br>console.log(0 || undefined || 3); // 3<br><br>// undefined (since 0, false, and undefined are falsy,<br>// the right-most falsy value is returned)<br>console.log(0 || false || undefined); // undefined</pre><p><strong>NOTE</strong>: Keep in mind, that the way that short circuit evaluation works is that boolean expressions which use comparison operators are first evaluated, then the short circuit evaluation kicks in and takes over. So anything with a comparison operator will evaluate to either true or false and that is what the logical AND or OR will return.</p><pre>// returns true (1 &lt; 2 evaluates to true,<br>// so the value of true is returned)<br>console.log(1 &lt; 2 || 0); // true<br><br>// returns 0 (1 &gt; 2 evaluates to false, so || returns<br>// the right hand side by default, which is 0)<br>console.log(1 &gt; 2 || 0); // 0</pre><h4>Logical NOT (!)</h4><p>Logical NOT (!) reverses the truthyness or falsyness of the operand that it is in front of. Basically, if something evaluates to true, the logical NOT changes that to false and vice versa.</p><pre>console.log(!true); // false<br>console.log(!false); // true</pre><h4>if statement:</h4><p>The if statement evaluates a condition (what&#39;s in the parenthesis). When the condition is evaluated to be truthy, the if statement will run the block of code inside its curly braces.</p><p>If the condition is evaluated to be falsy, the if statement and the contents inside its curly braces are not evaluated and JavaScript moves on with the next statement in the code after the if statement&#39;s closing curly braces..</p><pre>// The stuff inside the parenthesis is the condition that<br>// is used to determine if the contents inside the<br>// curly braces {} will run or not.<br>// The condition will either evaluate to be truthy or falsy<br>if (true) {<br>  console.log(&quot;the if statement has run&quot;);<br>}<br><br>if (false) {<br>  // this code is skipped since the condition in the if<br>  // statement is false<br>  console.log(&quot;this code will not run&quot;);<br>}</pre><h4>if…else statement:</h4><p>The else portion of the if...else statement is an addition to the if statement.</p><p>Basically, when the if statement evaluates to false, then the block of code which is part of the if statement is skipped an the code in the else block will run instead.</p><p>Since the else statement doesn&#39;t have a condition to evaluate, it will always run as long as all of the if and else if statements above it fail (i.e. their conditions evaluate to false);</p><p>Notice</p><pre>if (true) {<br>  // code in if loop will run since it evaluates to true<br>  console.log(&quot;this code will run&quot;);<br>} else {<br>  // this code will not run when the if statement runs<br>  // it will only run when the condition in the if<br>  // statement evaluates to false<br>  console.log(&quot;this code will not run&quot;);<br>}<br><br>if (false) {<br>  // code inside if statement will not run as the condition<br>  // evaluates to false<br>  console.log(&quot;this code will not run&quot;);<br>} else {<br>  // code inside else statement will run since the<br>  // the condition in the if statement is false<br>  console.log(&quot;this code will run&quot;);<br>}</pre><h4>else if statement:</h4><p>The else if statement sits in between the if and the else statement. You can have as many else if statements as you like sandwiched in between the if and else statement.</p><p>The code block for each else if statement will only run when the condition inside the else if statement evaluates to true AND any if or else if statements above if also evaluated to false.</p><p>When an else if statement runs, any additional else if and else statements below the current else if statements will not run.</p><pre>const x = 1;<br>const y = 2;<br>const z = 3;<br><br>if (x &lt; 1) {<br>  // The condition in this if statement is false,<br>  // so this if statement will not run<br>  console.log(x, &quot;&lt; 1&quot;);<br>} else if (x === y) {<br>  // The condition in this else if evaluates to false<br>  // so this else if statement will not run<br>  console.log(x + &quot;=&quot; + y);<br>} else if (x === 1) {<br>  // This is the first condition that evaluates to true<br>  // it will run<br>  console.log(&quot;x = 1&quot;);<br>} else if (y === 2) {<br>  // while the condition in this else if statement is true<br>  // the else if statement above was also true and was<br>  // evaluated first. Since there was already a statement<br>  // which evaluated to true and ran, no other statements<br>  // below it will run, including this else if statement.<br>  console.log(<br>    &quot;this code will not run because the else if block above ran first&quot;<br>  );<br>} else {<br>  console.log(<br>    &quot;this code will not run because a previous else if statement executed successfully&quot;<br>  );<br>}</pre><h4>switch Statements:</h4><p>Switch statements work a little differently than if loops. Instead of evaluating a condition to either true or false, the switch statement accepts an expression and then looks for the value of that expression in one of its case.</p><p>You can have as many case conditions as you want inside a switch statement.</p><p>When a switch statement identifies a matching case, the switch statement will run all of the contents inside that case as well as any other code below it, including other case conditions.</p><p>If a matching case is not identified, then the default case is run (assuming it is the last condition in the switch expression).</p><p>To avoid running more than one case, it is best practice to add a break statement as the last line in each of the case statements. This will cause the switch expression to exit once it runs into the break statement.</p><p>Here is the syntax used to write a switch statement, provided by <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch">MDN</a>:</p><pre>switch (expression) {<br>  case value1:<br>    //Statements executed when the<br>    //result of expression matches value1<br>    [break;]<br>  case value2:<br>    //Statements executed when the<br>    //result of expression matches value2<br>    [break;]<br>  ... // you can have as many cases as you want<br>  case valueN:<br>    //Statements executed when the<br>    //result of expression matches valueN<br>    [break;]<br>  [default:<br>    //Statements executed when none of<br>    //the values match the value of the expression<br>    [break;]]<br>}</pre><p>Here is an example of a switch statement, also provided by <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch">MDN</a>. Depending on the value of expr, there are a few different things that could happen.</p><p>If expr is Oranges:</p><ul><li>“Oranges are $0.59 a pound.” will print out to the console.</li><li>The break statement will trigger and prevent anything else below the current case from executing.</li></ul><p>If expr is Apples:</p><ul><li>“Apples are $0.32 a pound.” will print out to the console.</li><li>The break statement will trigger and prevent anything else below the current case from executing.</li></ul><p>If expr is Bananas:</p><ul><li>“Bananas are $0.48 a pound.” will print out to the console.</li><li>The break statement will trigger and prevent anything else below the current case from executing.</li></ul><p>If expr is Cherries:</p><ul><li>“Cherries are $3.00 a pound.” will print out to the console.</li><li>The break statement will trigger and prevent anything else below the current case from executing.</li></ul><p>If expr is Mangoes:</p><ul><li>The case in Mangoes will run, there actually isn&#39;t anything inside this case, however, there also isn&#39;t a break statement, so everything below the Mangoes case will also run (the Papayas case in this case)</li></ul><p>If expr is Papayas:</p><ul><li>“Mangoes and papayas are $2.79 a pound.” will print out to the console.</li><li>The break statement will trigger and prevent anything else below the current case from executing.</li></ul><p>If expr is none of these:</p><ul><li>The default case will run</li><li>‘Sorry, we are out of ‘ + expr + ‘.’ will run in the console, replacing expr to whatever you had it set to.</li></ul><pre>const expr = &quot;Apples&quot;;<br><br>switch (expr) {<br>  case &quot;Oranges&quot;:<br>    console.log(&quot;Oranges are $0.59 a pound.&quot;);<br>    break;<br>  case &quot;Apples&quot;:<br>    console.log(&quot;Apples are $0.32 a pound.&quot;);<br>    break;<br>  case &quot;Bananas&quot;:<br>    console.log(&quot;Bananas are $0.48 a pound.&quot;);<br>    break;<br>  case &quot;Cherries&quot;:<br>    console.log(&quot;Cherries are $3.00 a pound.&quot;);<br>    break;<br>  case &quot;Mangoes&quot;:<br>  case &quot;Papayas&quot;:<br>    console.log(&quot;Mangoes and papayas are $2.79 a pound.&quot;);<br>    break;<br>  default:<br>    console.log(&quot;Sorry, we are out of &quot; + expr + &quot;.&quot;);<br>}<br><br>console.log(&quot;Is there anything else you&#39;d like?&quot;);</pre><p>To see what happens for all of the cases above, I modified the above code to loop through an array that contains all of the case options.</p><pre>const expr = [<br>  &quot;Oranges&quot;,<br>  &quot;Apples&quot;,<br>  &quot;Bananas&quot;,<br>  &quot;Cherries&quot;,<br>  &quot;Mangoes&quot;,<br>  &quot;Papayas&quot;,<br>  &quot;Steak&quot;,<br>];<br><br>for (const item of expr) {<br>  switch (item) {<br>    case &quot;Oranges&quot;:<br>      console.log(&quot;Printing results of &#39;Oranges&#39; case:&quot;);<br>      console.log(&quot;Oranges are $0.59 a pound.&quot;);<br>      break;<br>    case &quot;Apples&quot;:<br>      console.log(&quot;Printing results of &#39;Apples&#39; case:&quot;);<br>      console.log(&quot;Apples are $0.32 a pound.&quot;);<br>      break;<br>    case &quot;Bananas&quot;:<br>      console.log(&quot;Printing results of &#39;Bananas&#39; case:&quot;);<br>      console.log(&quot;Bananas are $0.48 a pound.&quot;);<br>      break;<br>    case &quot;Cherries&quot;:<br>      console.log(&quot;Printing results of &#39;Cherries&#39; case:&quot;);<br>      console.log(&quot;Cherries are $3.00 a pound.&quot;);<br>      break;<br>    case &quot;Mangoes&quot;:<br>      console.log(&quot;Printing results of &#39;Mangoes&#39; case:&quot;);<br>    case &quot;Papayas&quot;:<br>      console.log(&quot;Printing results of &#39;Papayas&#39; case:&quot;);<br>      console.log(&quot;Mangoes and papayas are $2.79 a pound.&quot;);<br>      break;<br>    default:<br>      console.log(&quot;Printing results of &#39;default&#39; case:&quot;);<br>      console.log(&quot;Sorry, we are out of &quot; + item + &quot;.&quot;);<br>  }<br>}<br><br>console.log(&quot;Is there anything else you&#39;d like?&quot;);</pre><p>Here is what gets printed to the console:</p><pre>Printing results of &#39;Oranges&#39; case:<br>Oranges are $0.59 a pound.<br>Printing results of &#39;Apples&#39; case:<br>Apples are $0.32 a pound.<br>Printing results of &#39;Bananas&#39; case:<br>Bananas are $0.48 a pound.<br>Printing results of &#39;Cherries&#39; case:<br>Cherries are $3.00 a pound.<br>Printing results of &#39;Mangoes&#39; case:<br>Printing results of &#39;Papayas&#39; case:<br>Mangoes and papayas are $2.79 a pound.<br>Printing results of &#39;Papayas&#39; case:<br>Mangoes and papayas are $2.79 a pound.<br>Printing results of &#39;default&#39; case:<br>Sorry, we are out of Steak.<br>Is there anything else you&#39;d like?</pre><h4>The Conditional Operator</h4><p>The Conditional Operator is essentially a shortcut to performing an if…else loop. You will also see the conditional operator called a <em>ternary</em> operator.</p><p>Instead of writing the if else loop, what you do is write the condition to be used to evaluate the truthyness (or falsyness), then add a questions mark followed by an expression to run if the condition is true, a colon (:), and then another expression to run if the condition evaluates to false.</p><p>Below is the syntax used by the conditional operator:</p><pre>(condition) ? expressionIfTrue : expressionIfFalse</pre><p>Basically, if the condition in parenthesis (to the left of the question mark) evaluate to true, then the expression to the left of the colon is returned. If the condition evaluates to false, then the expression to the right of the colon is returned.</p><pre>let x = 1;<br>let y = 2;<br><br>let a = true ? x : y;<br>console.log(a); // 1<br><br>let b = false ? x : y;<br>console.log(b); // 2<br><br>// Logs &quot;Hi&quot; to the console<br>let c = 30 &lt; 60 ? console.log(&quot;Hi&quot;) : console.log(&quot;Goodbye&quot;);<br><br>// Logs &quot;Goodbye&quot; to the console<br>let d = 30 &gt; 60 ? console.log(&quot;Hi&quot;) : console.log(&quot;Goodbye&quot;);</pre><h4>Resources:</h4><ul><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Control_flow_and_error_handling">MDN — Control flow and error handling</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Glossary/Truthy">MDN — Truthy</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Glossary/Falsy">MDN — Falsy</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_NOT">MDN — Logical NOT (!)</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch">MDN — switch</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator">MDN — Conditional (ternary) operator</a></li><li><a href="https://en.wikipedia.org/wiki/Control_flow">Wikipedia — Control flow</a></li><li><a href="https://en.wikipedia.org/wiki/Conditional_(computer_programming)">Wikipedia — Conditional (computer programming)</a></li><li><a href="https://eloquentjavascript.net/02_program_structure.html">Eloquent JavaScript, 3rd Edition: Chapter 02, Program Structure</a></li><li><a href="https://javascript.info/logical-operators">Javascript.Info: Logical Operators</a></li><li><a href="https://javascript.info/ifelse">Javascript.Info: conditional branching: if, ‘?’</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=acfdda94c97a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/control-flow-in-javascript-conditional-statements-acfdda94c97a">Control Flow in JavaScript: Conditional Statements</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript: Differences Between Using var, let, and const Keywords for Variable Declaration]]></title>
            <link>https://medium.com/geekculture/javascript-differences-between-using-var-let-and-const-keywords-for-variable-declaration-878649adb392?source=rss-fb363d427808------2</link>
            <guid isPermaLink="false">https://medium.com/p/878649adb392</guid>
            <category><![CDATA[hoisting]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[variables]]></category>
            <dc:creator><![CDATA[Piotr Szponder]]></dc:creator>
            <pubDate>Thu, 24 Jun 2021 23:59:29 GMT</pubDate>
            <atom:updated>2021-06-25T16:55:35.575Z</atom:updated>
            <content:encoded><![CDATA[<p>The var keyword was the original keyword used to declare variables in JavaScript.</p><p>Introduced in ES2016, let and const are two new keywords used for declaring variables. This article will explain the differences between how the var, let, and const keywords work.</p><p>Before we jump into the differences between let, var and const, it&#39;s important to understand how scope and hoisting works.</p><figure><img alt="Javascript program in a vscode code editor with Dracula theme" src="https://cdn-images-1.medium.com/proxy/0*6g07UTLUY21UIe5L" /><figcaption>Photo by <a href="https://unsplash.com/@gamell?utm_source=ghost&amp;utm_medium=referral&amp;utm_campaign=api-credit">Joan Gamell</a> / <a href="https://unsplash.com/?utm_source=ghost&amp;utm_medium=referral&amp;utm_campaign=api-credit">Unsplash</a></figcaption></figure><h3>Scope</h3><p>Scope is the space where the value of a variable is defined and accessible.</p><p>There are 3 types of scope in JavaScript:</p><ul><li>Global Scope</li><li>Function Scope</li><li>Block Scope</li></ul><p>Variables defined with the var keyword have either global or function scope.</p><p>Variables defined with the let or const keyword have block scope.</p><p>For a more in-depth explanation of scope, see my other post titled <a href="https://piotr-szponder.ghost.io/scope-in-javascript/">Scope in JavaScript</a>.</p><h3>Hoisting</h3><p>When a JavaScript program runs, it will first parse the script and look for any variable declarations or function declarations. If it finds any variable or function declarations, it will “hoist” those to the top their respective scopes and process them first before proceeding to evaluate the rest of the JavaScript code. This process is called “Hoisting”</p><p>Hoisting affects variable declaration but NOT value INITIALIZATION / ASSIGNMENT.</p><p>Examples of Hoisting in JS:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ba14c9bd38dcb5812adcf96d3c375518/href">https://medium.com/media/ba14c9bd38dcb5812adcf96d3c375518/href</a></iframe><p>Remember, hoisting only applies to variable declarations, not variable initialization. The below example will return “undefined” as x is initialized and defined in the second line and therefore, it is not hoisted above the console.log() call.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7025d9c7e205fb915e0f14134bb28293/href">https://medium.com/media/7025d9c7e205fb915e0f14134bb28293/href</a></iframe><p>The code below will print 2. Since the variable y is declared on line 3, but not initialized, it will be hoisted up to the top of the program, above the y = 2 initialization. So by the time console.log(y) is actually called, a value of 2 will be defined for y.</p><pre>y = 2;<br>console.log(y); // Returns 2<br>var y;<br><br>// Same As<br>var y;<br>y = 2;<br>console.log(y);</pre><p><strong>NOTE:</strong> While hoisting applies to variables declared with var, let, or const, hoisting really only helps variables declared with var. Variables declared with the let keyword return ReferenceError if they are un-initialized (see TDZ section further down for more detail). You also cannot declare a variable with the const keyword without also initializing it&#39;s value right away. If you try to do this, you will obtain a &quot;SyntaxError: Missing initializer in const declaration&quot;.</p><h3>Differences between var, let, and const</h3><h4>var</h4><p>A variable which is declared (but not initialized) using the var keyword returns a value of undefined if it is accessed before it is initialized (see section about hoisting).</p><pre>console.log(x); // Returns undefined<br>var x = 1; // variable declaration and initialization<br>console.log(x); // Returns 1</pre><p>Variables declared with var can be either function or global scoped.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b265b1b78b877564380ee9e1dfa2037f/href">https://medium.com/media/b265b1b78b877564380ee9e1dfa2037f/href</a></iframe><p>Variables declared with var can be re-declared.</p><pre>var x = 1;<br>console.log(x); // 1<br><br>var x = 2;<br>console.log(x); // 2</pre><h4>let</h4><p>Variables declared with let are block scoped. We can only declare variables with the same name as long as they are in different block scopes using let.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0e9cb823973e96159e57164e4f022373/href">https://medium.com/media/0e9cb823973e96159e57164e4f022373/href</a></iframe><p>Unlike var, variables declared with the let keyword cannot be re-declared within the same scope</p><pre>let x = 1;<br>let x = 2; // Uncaught SyntaxError: Identifier &#39;x&#39; has already been declared</pre><p>You can however, still redefine (reassign) a variable declared with let.</p><pre>let x = 1;<br>console.log(x); // 1<br><br>x = 2; // This is ok because you are not trying to redeclare x, just redefine its value<br>console.log(x); // 2</pre><h4>The Temporal Dead Zone</h4><p>The Temporal Dead Zone (TDZ) is the area in the current scope between the start of the scope and where the variable is finally initialized. The TDZ applies to variables declared with the let keyword. A variable declared with let cannot be accessed (will return &quot;ReferenceError&quot;) within the TDZ.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/03e38b1ac7db274c896bafc247d48a34/href">https://medium.com/media/03e38b1ac7db274c896bafc247d48a34/href</a></iframe><h4>const</h4><p>Similar to variables declared with let, variables declared with the const keyword are block scoped.</p><p>Also similar to let, variables declared with const cannot be redeclared.</p><p>Unlike variables declared with let however, variables declared with const <strong>MUST</strong> be initialized right away. If not, you will end up with a &quot;SyntaxError: Missing initializer in const declaration&quot; error.</p><p>Most importantly, variables declared and initialized with the const keyword cannot have their value changed <strong>through reassignment</strong> (see note below). This is because the const keyword causes the name of the variable to be read-only, preventing write access to the value stored in memory through the assigned variable. If you think about it, it makes sense why this is. If you want to create a variable that can&#39;t be changed easily, you need to know it&#39;s value, otherwise, you would just end up with a constant variable with an &quot;undefined&quot; value.</p><p><strong>NOTE</strong>: Notice that variables initialized with the const keyword cannot have their value changed <strong>through reassignment</strong>. This does not mean that the value of a constant value cannot change, it only means you can&#39;t change it using the variable name directly. While there isn&#39;t another way to change a string or number variable other than reassignment for example, you can change the properties of an object.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dc37b4e37de31432f536af6a859a4ede/href">https://medium.com/media/dc37b4e37de31432f536af6a859a4ede/href</a></iframe><h3>Which variable declaration is best and which should I use?</h3><p>I read an article from <a href="https://wesbos.com/javascript/01-the-basics/variables-and-statements/#differences-between-var-let--const">Wes Bos</a> and I like his advice:</p><ol><li>Use the const keyword to declare variables by default unless you know that your variable will need to have its value changed (use let in that case).</li><li>Use the let keyword to declare a variable if you know its value will change (like an iterator for example).</li><li>Unless necessary for a special case, avoid using the var keyword for variable declaration.</li></ol><h3>Summary: Difference between variables declared with “var”, “let”, and “const” keywords:</h3><p><strong>var</strong></p><ul><li>Scope: Global or Function</li><li>Able to be redeclared? Yes</li><li>Able to be reinitialized? Yes</li></ul><p><strong>let</strong></p><ul><li>Scope: Global or Block</li><li>Able to be redeclared? No</li><li>Able to be reinitialized? Yes</li></ul><p><strong>const</strong></p><ul><li>Scope: Global or Block</li><li>Able to be redeclared? No</li><li>Able to be reinitialized? No</li></ul><h3>Resources</h3><ul><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var">MDN — var</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let">MDN — let</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const">MDN — const</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/block">MDN — block</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/API/Window">MDN — window</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#variable_scope">MDN — Variable Scope</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Control_flow_and_error_handling#block_statement">MDN — Block Statement</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Glossary/Hoisting">MDN — Hoisting</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#variable_hoisting">MDN — Variable Hoisting</a></li><li><a href="https://www.freecodecamp.org/news/var-let-and-const-whats-the-difference/">Var, Let, and Const — What’s the Difference?</a></li><li><a href="https://www.w3schools.com/js/js_scope.asp">W3 Schools — JavaScript Scope</a></li><li><a href="https://eloquentjavascript.net/">Eloquent JavaScript, A Modern Introduction to Programming</a></li><li><a href="https://owlcation.com/stem/JavaScript-Variable-Declaration-and-Initialization">JavaScript Variable Declaration and Initialization</a></li><li><a href="https://www.freecodecamp.org/news/what-is-the-temporal-dead-zone/">What is the Tempral Dead Zone?</a></li><li><a href="https://wesbos.com/javascript/01-the-basics/variables-and-statements/#differences-between-var-let--const">Wes Bos — Variables and Statements</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=878649adb392" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/javascript-differences-between-using-var-let-and-const-keywords-for-variable-declaration-878649adb392">JavaScript: Differences Between Using var, let, and const Keywords for Variable Declaration</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript: Declaring and Initializing Variables, How Data is Stored and Accessed in JavaScript]]></title>
            <link>https://medium.com/geekculture/javascript-declaring-and-initializing-variables-how-data-is-stored-and-accessed-in-javascript-2936f4d69ce0?source=rss-fb363d427808------2</link>
            <guid isPermaLink="false">https://medium.com/p/2936f4d69ce0</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[memory-management]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[variable-declaration]]></category>
            <category><![CDATA[variables-in-javascript]]></category>
            <dc:creator><![CDATA[Piotr Szponder]]></dc:creator>
            <pubDate>Thu, 24 Jun 2021 23:07:46 GMT</pubDate>
            <atom:updated>2021-06-28T06:45:11.599Z</atom:updated>
            <content:encoded><![CDATA[<p>Declaring and initializing variables in JavaScript are two different concepts. In order to better understand these concepts as well as what a variable actually is, let’s start with discussing how memory is used to store and access data.</p><h3>What is a Variable and How does it Work?</h3><p>A variable, also known as a “binding” connects (or binds) a piece of data in memory to a name which can later be used to retrieve the value from memory. In computer science, every location in memory has a memory address.</p><p>A few things happen when a variable is declared:</p><ol><li>A location in memory is set aside to store the future value (piece of data) assigned to the variable name.</li><li>A memory address which “points” to that location in memory is created. This allows us to access the value stored in memory at a later point.</li><li>The variable name is associated with the memory address.</li></ol><p>For example, let’s say that you create a variable <strong>x</strong> using the <strong>let</strong> keyword and set it’s value equal to the string “Hello”. You then use the <strong>console.log() </strong>function to log the value of x to the console. What is actually happening under the hood?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3913488d3b0d54f428f9cc11f16c66d6/href">https://medium.com/media/3913488d3b0d54f428f9cc11f16c66d6/href</a></iframe><p>To make this a little easier to explain and understand, we can break down the 1st line into 2 lines of code, a variable declaration and a value assignment.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/02aa0698ce31d3ffe8e4011f810d3f68/href">https://medium.com/media/02aa0698ce31d3ffe8e4011f810d3f68/href</a></iframe><p>Line 1: <strong>let x;</strong></p><ul><li>A variable is declared with a name of “x”.</li><li>A location in memory is reserved for the value of the variable “x”.</li><li>A memory address which points to the location in memory is associated with the variable name “x”.</li></ul><p>Line 2: x = <strong>“Hello”;</strong></p><ul><li>JavaScript looks up the variable named <strong>x</strong> and uses the associated memory address to access the location in memory which was reserved for the variable “x”.</li><li>Basically, the variable “points” to the memory location where the value is (or is going to be) stored.</li><li>The value of “Hello” is stored at the specified memory location.</li></ul><p>Line 3: <strong>console.log(x)</strong></p><ul><li>The <strong>console.log()</strong> function calls the variable <strong>x</strong> and uses the memory address associated with <strong>x</strong> to search for the value stored in memory which happens to be “Hello”.</li><li>The value at the specific memory address is returned by <strong>console.log()</strong>.</li></ul><p>As a quick summary, when you try to print out the value of the variable x using <strong>console.log(x)</strong>, what is actually happening is that the variable x contains the memory address where the the value “Hello” is stored. JavaScript uses that memory address to go to the specific location in memory which the memory address points to and retrieves the value, which is “Hello”.</p><p>So <strong>variables “point” to values stored in memory.</strong></p><h3>Declaring Variables in JavaScript</h3><p>To declare (create) a variable, we need to use the <strong>var</strong>, <strong>let</strong>, or <strong>const</strong> keyword, followed by the name we want to provide to the variable. The <strong>var</strong>, <strong>let</strong>, and <strong>const</strong> keywords tell JavaScript to set aside a portion of memory so that we may store a specific piece of data to it later.</p><p>The name provided to the variable can be later used to access the location in memory assigned to the variable and retrieve the data which is stored in it. To assign a value to the variable (initialize the variable with a value), use the assignment operator <strong>=</strong> to set the variable name equal to a piece of data (number, boolean, string, array, object, function, etc.)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e32258c196d6762582acbf92812528c2/href">https://medium.com/media/e32258c196d6762582acbf92812528c2/href</a></iframe><h3>Initialization</h3><p>Initializing is the term used to describe the process of assignment of a value to a variable (i.e. storing the value (piece of data) in the location in memory which the variable “points” to).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dd3498c72d0af0fdc99f6be854854dd0/href">https://medium.com/media/dd3498c72d0af0fdc99f6be854854dd0/href</a></iframe><h3>Resources</h3><ul><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var">MDN — var</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let">MDN — let</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const">MDN — const</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/block">MDN — block</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/API/Window">MDN — window</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#variable_scope">MDN — Variable Scope</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Control_flow_and_error_handling#block_statement">MDN — Block Statement</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Glossary/Hoisting">MDN — Hoisting</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#variable_hoisting">MDN — Variable Hoisting</a></li><li><a href="https://www.freecodecamp.org/news/var-let-and-const-whats-the-difference/">Var, Let, and Const — What’s the Difference?</a></li><li><a href="https://www.w3schools.com/js/js_scope.asp">W3 Schools — JavaScript Scope</a></li><li><a href="https://eloquentjavascript.net/">Eloquent JavaScript, A Modern Introduction to Programming</a></li><li><a href="https://owlcation.com/stem/JavaScript-Variable-Declaration-and-Initialization">JavaScript Variable Declaration and Initialization</a></li><li><a href="https://www.freecodecamp.org/news/what-is-the-temporal-dead-zone/">What is the Temporal Dead Zone?</a></li><li><a href="https://wesbos.com/javascript/01-the-basics/variables-and-statements/#differences-between-var-let--const">Wes Bos — Variables and Statements</a></li><li><a href="https://www.youtube.com/watch?v=NKTfNv2T0FE">CS50 2020 — Lecture 4 — Memory</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2936f4d69ce0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/javascript-declaring-and-initializing-variables-how-data-is-stored-and-accessed-in-javascript-2936f4d69ce0">JavaScript: Declaring and Initializing Variables, How Data is Stored and Accessed in JavaScript</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scope in JavaScript]]></title>
            <link>https://medium.com/geekculture/scope-in-javascript-559b8ce416c1?source=rss-fb363d427808------2</link>
            <guid isPermaLink="false">https://medium.com/p/559b8ce416c1</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript-development]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Piotr Szponder]]></dc:creator>
            <pubDate>Sun, 20 Jun 2021 03:44:11 GMT</pubDate>
            <atom:updated>2021-06-25T07:22:40.480Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eoAUZDb0V-X3qGwA" /><figcaption>Photo by <a href="https://unsplash.com/@clark_fransa?utm_source=medium&amp;utm_medium=referral">Arnold Francisca</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>What is Scope?</h3><p>Scope is the area of code where a variable (or function) exists and is accessible. There are a few different types of scopes in JavaScript: Global Scope, Function Scope and Block Scope.</p><h3>Global Scope</h3><p>Variables declared outside of functions or blocks (curly braces { }) are considered to have global scope meaning that they can be accessed anywhere in the JavaScript program</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a7af4580a4e111d746f998cc6cd5b6c5/href">https://medium.com/media/a7af4580a4e111d746f998cc6cd5b6c5/href</a></iframe><p><strong>NOTE</strong>: When defining variables using the <em>var</em> keyword outside of a function (hence globally scoping it), the variable becomes attached to the <em>window</em> object. Variables defined with <em>let</em> or <em>const</em> do not get attached to the <em>window</em> object. This is because <em>var</em> was designed to be either function or global scoped. <em>let</em> and <em>const</em> are actually created to be block scoped</p><p>The <em>window</em> object represents the browser’s window and contains all global functions, objects and variables.</p><p>So technically, when you declare a variable using <em>let</em> and <em>const</em> outside of a code block in a javascript program, they are only globally scoped to the javascript program, but they are not in the global scope of the <em>window</em> object.</p><h3>Function Scope</h3><p>A variable declared within a function is considered to be part of the function’s scope. This scope is referred to as <em>function scope</em>. You will sometimes see <em>function scope</em> also referred to as <em>local</em> <em>scope</em>.</p><p>Variables declared inside a function scope can be accessed from within the function but not outside of it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a434f43d02c42ade32d6889a6bbf50d3/href">https://medium.com/media/a434f43d02c42ade32d6889a6bbf50d3/href</a></iframe><p><strong>NOTE: </strong>Variables declared with the <em>var</em> keyword have function (a.k.a. local) scope when defined inside a function. Variables declared with <em>let</em> and <em>const </em>technically have block scope (inside curly braces) when declared inside a function (i.e. the variable’s scope is bound to the curly braces, and not to the function itself). Since the function uses curly braces to encapsulate the function body, the function scope and the block scope for the function body are essentially the same thing.</p><p>The below example demonstrates the differences between function scoping when using <em>var</em> and <em>let</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2fa01322970bc87146048ca2b748ff53/href">https://medium.com/media/2fa01322970bc87146048ca2b748ff53/href</a></iframe><h3>Block Scope</h3><p>Block scope was introduced in ES2016 along with the <em>let</em> and <em>const</em> variable declaration keywords. Block scope only applies to variables created with either the <em>let</em> or <em>const</em> keywords.</p><p>Block scope is the scope defined within a set of curly brackets { }. The curly brackets define a “block” of code, hence the name, “block scope”.</p><p>A block scoped variable cannot be accessed outside of the block that it was defined in.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8c28427d870732506ac1d6a768307e85/href">https://medium.com/media/8c28427d870732506ac1d6a768307e85/href</a></iframe><p><strong>NOTE</strong>: Variables declared with the <em>var</em> keyword do <strong>NOT</strong> have block scope, only variables declared with <em>let</em> or <em>const</em> have block scope. Variables declared with <em>var</em> will ignore block scoping rules.</p><p>See the example below of how variables declared with the <em>var</em> keyword do not follow block scoping:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1fe81881d93d563634f8f553478f2621/href">https://medium.com/media/1fe81881d93d563634f8f553478f2621/href</a></iframe><h3>Lexical Scope</h3><p>JavaScript is a lexically scoped language (as opposed to a dynamically scoped language). You will also see Lexical Scoping defined as Static Scoping. So what does lexical scoping mean?</p><p>Lexical scoping means that the scope is defined at the location where the variable and function is defined (as opposed to where they are run).</p><p>See the example below of how Lexical Scoping works:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e20a584f5dc7a2a5fe564e4c7547b72b/href">https://medium.com/media/e20a584f5dc7a2a5fe564e4c7547b72b/href</a></iframe><p>Let’s break down the code snippet above.</p><p>1. When the <em>logVariable( )</em> function is called, it creates a local variable x and sets its value equal to 50.</p><p>2. In the next line, the <em>myFunc( )</em> function is called, let’s go up to where the <em>myFunc( )</em> function is defined.</p><p>3. <em>myFunc( )</em> calls the <em>console.log( )</em> function on the <em>x</em> variable however, <em>x </em>is not defined in the <em>myFunc( )</em> scope. We therefore need to go up one scope to the global scope to get the value of <em>x</em> which is 1. (see section below on scope chaining).</p><p>Notice that we never accessed the value of <em>x = 50</em>, even though it appears right above the <em>myFunc( )</em> call in the <em>logVariable( )</em> function. Again, this is because lexical scoping requires us to go to where the functions are defined, and not where they are run. If JavaScript were a dynamically scoped language, calling <em>logVariable( )</em> would result in the value of 50 being logged to the console instead of 1.</p><h3>Scope Chaining</h3><p>It is very helpful to understand how JavaScript accesses variables using scope chaining. Understanding the concept of scope chaining will help you understand how to determine the scope of variables / functions.</p><p>When a function or method needs to access a variable in JavaScript which is not initialized with a value in the current scope, JavaScript will go up by one scope level to look for the variable’s value. It will keep going up scope levels until it finds the function declaration.</p><p><strong>NOTE:</strong> Notice that scope chaining does not go <em>DOWN</em> scope levels, it will always only go up to look for a variable declaration in the next larger scope</p><p>Example of how scope chaining works:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7314c5ddf0a41fd7251d439283f0837e/href">https://medium.com/media/7314c5ddf0a41fd7251d439283f0837e/href</a></iframe><h3>References</h3><p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/block">MDN — block</a></p><p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#variable_scope">MDN — variable scope</a></p><p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Control_flow_and_error_handling#block_statement">MDN — block statement</a></p><p><a href="https://www.w3schools.com/js/js_scope.asp">W3 Schools JavaScript Scope</a></p><p><a href="https://www.w3schools.com/js/js_window.asp">W3 Schools JavaScript Window — The Browser Object Model</a></p><p><a href="https://wesbos.com/javascript/03-the-tricky-bits/scope">Wes Bos — Scope</a></p><p><a href="https://blog.bitsrc.io/understanding-scope-and-scope-chain-in-javascript-f6637978cf53">Understanding Scope and Scope Chain in JavaScript</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=559b8ce416c1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/scope-in-javascript-559b8ce416c1">Scope in JavaScript</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>