{"componentChunkName":"component---src-templates-search-template-search-template-js","path":"/search","result":{"data":{"allMarkdownRemark":{"edges":[{"node":{"fields":{"slug":"how-to-check-for-an-empty-object","dateSlug":"2021-09-07","postID":"how-to-check-for-an-empty-object-2021-09-07"},"frontmatter":{"category":"objects","tags":["javascript","objects"],"date":"September 7, 2021","format":"image","title":"How to Check for an Empty Object","author":{"name":"Stephen Sun"},"image":{"childImageSharp":{"fluid":{"base64":"data:image/jpeg;base64,/9j/2wBDABALDA4MChAODQ4SERATGCgaGBYWGDEjJR0oOjM9PDkzODdASFxOQERXRTc4UG1RV19iZ2hnPk1xeXBkeFxlZ2P/2wBDARESEhgVGC8aGi9jQjhCY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2P/wgARCAANABQDASIAAhEBAxEB/8QAGAAAAgMAAAAAAAAAAAAAAAAAAAIBAwX/xAAVAQEBAAAAAAAAAAAAAAAAAAAAAf/aAAwDAQACEAMQAAAB11hIsEF//8QAFhAAAwAAAAAAAAAAAAAAAAAAABEg/9oACAEBAAEFApZ//8QAFREBAQAAAAAAAAAAAAAAAAAAABH/2gAIAQMBAT8BiP/EABURAQEAAAAAAAAAAAAAAAAAAAAR/9oACAECAQE/Aar/xAAUEAEAAAAAAAAAAAAAAAAAAAAg/9oACAEBAAY/Al//xAAZEAEAAwEBAAAAAAAAAAAAAAABABExEEH/2gAIAQEAAT8hclbxWoKey0//2gAMAwEAAgADAAAAEO8P/8QAFREBAQAAAAAAAAAAAAAAAAAAABH/2gAIAQMBAT8QpT//xAAVEQEBAAAAAAAAAAAAAAAAAAAAEf/aAAgBAgEBPxCEP//EABsQAAMAAgMAAAAAAAAAAAAAAAABESExgZGh/9oACAEBAAE/EEUMUcBPAtF8KEqqZElbXR//2Q==","aspectRatio":1.5,"src":"/static/68af39ecdd996872cd60f58f3fa2a5eb/3866d/how-to-check-for-an-empty-object.jpg","srcSet":"/static/68af39ecdd996872cd60f58f3fa2a5eb/d1bff/how-to-check-for-an-empty-object.jpg 6w,\n/static/68af39ecdd996872cd60f58f3fa2a5eb/3866d/how-to-check-for-an-empty-object.jpg 510w,\n/static/68af39ecdd996872cd60f58f3fa2a5eb/f7bf2/how-to-check-for-an-empty-object.jpg 1920w","srcWebp":"/static/68af39ecdd996872cd60f58f3fa2a5eb/47cfc/how-to-check-for-an-empty-object.webp","srcSetWebp":"/static/68af39ecdd996872cd60f58f3fa2a5eb/ab631/how-to-check-for-an-empty-object.webp 6w,\n/static/68af39ecdd996872cd60f58f3fa2a5eb/47cfc/how-to-check-for-an-empty-object.webp 510w,\n/static/68af39ecdd996872cd60f58f3fa2a5eb/2532a/how-to-check-for-an-empty-object.webp 1920w","sizes":"(max-width: 510px) 100vw, 510px","presentationWidth":510,"presentationHeight":350}}}},"excerpt":"Link to code snippet: GitHub Working with objects always feels slightly less fluid when compared to arrays. With arrays, we can simply validate the length of the ar…","html":"<p><strong>Link to code snippet: <a href=\"https://github.com/javascriptfullstack/javascript-snippets/blob/master/how-to-check-for-an-empty-object/index.js\">GitHub</a></strong></p>\n<p>Working with objects always feels slightly less fluid when compared to arrays. With arrays, we can simply validate the length of the array (if it's equal to zero). For objects, we can do something similar thanks to the built-in <code>Object.keys()</code> method, but even then we need to add an extra validation. Let's take a closer look at two different ways to check for empty objects.</p>\n<h4>Set the Scene</h4>\n<p>Let's create two test objects that we'll use to perform our validations. The first object will have three properties and the second object will have none.</p>\n<pre><code class=\"language-js\">const object1 = { a: 5, b: 8, c: 10 }\nconst object2 = {}\n</code></pre>\n<h4>Method 1: Object.keys()</h4>\n<p>The first method we'll use involves a combination of <code>Object.keys()</code> and checking whether the constructor is an extension of the Object class. The latter is important because in JavaScript, we can create new object instances in many different ways. For example, <code>new Date()</code> and <code>new Array()</code> would both pass the <code>Object.keys()</code> validation, but we want to make sure that we're actually testing objects and not primitives or wrapper instances.</p>\n<pre><code class=\"language-js\">const isObject1Empty =\n  Object.keys(object1).length === 0 &#x26;&#x26; object1.constructor === Object\nconsole.log(isObject1Empty) // false\n\nconst isObject2Empty =\n  Object.keys(object2).length === 0 &#x26;&#x26; object2.constructor === Object\nconsole.log(isObject2Empty) // true\n</code></pre>\n<h4>Method 2: for...in loop</h4>\n<p>The second method is the old-fashioned way: a for...in loop. This method loops over each object property and calls <code>hasOwnProperty()</code> to verify whether the specified property is a direct property of the object. If the object has a property, the result of the function will false (meaning not empty).</p>\n<pre><code class=\"language-js\">const isEmpty = object => {\n  for (let prop in object) {\n    if (object.hasOwnProperty(prop)) {\n      return false\n    }\n  }\n\n  return true\n}\n\nconsole.log(isEmpty(object1)) // false\nconsole.log(isEmpty(object2)) // true\n</code></pre>\n<h4>Method 3: JSON.stringify()</h4>\n<p>The final method we can use to validate empty objects is a rather interesting approach. We can use <code>JSON.stringify()</code> to convert JavaScript objects into JSON strings. If we do this for our two objects and compare each of them to an empty object (after converting to a JSON string), we can see that the first object is not empty and the second one is.</p>\n<pre><code class=\"language-js\">console.log(JSON.stringify(object1) === JSON.stringify({})) // false\nconsole.log(JSON.stringify(object2) === JSON.stringify({})) // true\n</code></pre>\n<p>As always, it's a good practice to create helper utility functions that can be easily reused throughout your application. This is a prime example of a use case you will run into fairly often. There are also utility libraries (e.g. Lodash) that can be used as well.</p>"}},{"node":{"fields":{"slug":"chaining-array-methods","dateSlug":"2021-08-15","postID":"chaining-array-methods-2021-08-15"},"frontmatter":{"category":"arrays","tags":["javascript","es6","arrays"],"date":"August 15, 2021","format":"image","title":"Chaining Array Methods","author":{"name":"Stephen Sun"},"image":{"childImageSharp":{"fluid":{"base64":"data:image/jpeg;base64,/9j/2wBDABALDA4MChAODQ4SERATGCgaGBYWGDEjJR0oOjM9PDkzODdASFxOQERXRTc4UG1RV19iZ2hnPk1xeXBkeFxlZ2P/2wBDARESEhgVGC8aGi9jQjhCY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2P/wgARCAANABQDASIAAhEBAxEB/8QAFwABAQEBAAAAAAAAAAAAAAAAAwABAv/EABUBAQEAAAAAAAAAAAAAAAAAAAEC/9oADAMBAAIQAxAAAAEeDGXI5P/EABkQAAIDAQAAAAAAAAAAAAAAAAACARESMv/aAAgBAQABBQK1Heo3I75Oh4pv/8QAFhEAAwAAAAAAAAAAAAAAAAAAARAh/9oACAEDAQE/ARV//8QAFBEBAAAAAAAAAAAAAAAAAAAAEP/aAAgBAgEBPwE//8QAGRABAQADAQAAAAAAAAAAAAAAAQARIjEh/9oACAEBAAY/AnUtfLNzkDJf/8QAGxABAAMAAwEAAAAAAAAAAAAAAQARITFRYYH/2gAIAQEAAT8hXaYfJRI6VcVcc7EDhVQy/eeYPWT/2gAMAwEAAgADAAAAEPgf/8QAFxEBAQEBAAAAAAAAAAAAAAAAAQARMf/aAAgBAwEBPxA4Ukx7f//EABYRAQEBAAAAAAAAAAAAAAAAAAAhAf/aAAgBAgEBPxDYj//EABwQAQEAAgMBAQAAAAAAAAAAAAERADEhUWFB8P/aAAgBAQABPxBjXIqPDR1+uJQFaJnu8vkc+DDfWSJBUaPe8W2PssH4Yaajl7z/2Q==","aspectRatio":1.5,"src":"/static/1cbb6705ee34b01df491a5e950e809bb/3866d/chaining-array-methods.jpg","srcSet":"/static/1cbb6705ee34b01df491a5e950e809bb/d1bff/chaining-array-methods.jpg 6w,\n/static/1cbb6705ee34b01df491a5e950e809bb/3866d/chaining-array-methods.jpg 510w,\n/static/1cbb6705ee34b01df491a5e950e809bb/f7bf2/chaining-array-methods.jpg 1920w","srcWebp":"/static/1cbb6705ee34b01df491a5e950e809bb/47cfc/chaining-array-methods.webp","srcSetWebp":"/static/1cbb6705ee34b01df491a5e950e809bb/ab631/chaining-array-methods.webp 6w,\n/static/1cbb6705ee34b01df491a5e950e809bb/47cfc/chaining-array-methods.webp 510w,\n/static/1cbb6705ee34b01df491a5e950e809bb/2532a/chaining-array-methods.webp 1920w","sizes":"(max-width: 510px) 100vw, 510px","presentationWidth":510,"presentationHeight":350}}}},"excerpt":"Link to code snippet: GitHub One of the greatest things about JavaScript is how easy it is to work with arrays. The various array methods (map, filter, reduce, etc.…","html":"<p><strong>Link to code snippet: <a href=\"https://github.com/javascriptfullstack/javascript-snippets/blob/master/how-to-chain-array-methods/index.js\">GitHub</a></strong></p>\n<p>One of the greatest things about JavaScript is how easy it is to work with arrays. The various array methods (map, filter, reduce, etc.) can be combined with arrow function expressions to create succinct code.</p>\n<p>In addition, we're able to combine or chain these specific array methods to perform different operations sequentially.</p>\n<h4>Set the Scene</h4>\n<p>Let's start with an array of different vehicles. Each vehicle will have a type, brand, color, and a price.</p>\n<pre><code class=\"language-js\">const vehicles = [\n  { type: 'car', brand: 'Tesla', color: 'red', price: 50000 },\n  { type: 'car', brand: 'Toyota', color: 'blue', price: 20000 },\n  { type: 'truck', brand: 'Ford', color: 'green', price: 40000 },\n  { type: 'SUV', brand: 'Nissan', color: 'beige', price: 35000 },\n  { type: 'car', brand: 'Tesla', color: 'gray', price: 80000 }\n]\n</code></pre>\n<p>Now, let's say we want to find out which cars cost more than $20,000 from least to greatest in price. Breaking the requirements down into steps, we would get the following:</p>\n<ol>\n<li>Filter vehicles by type <code>car</code></li>\n<li>Filter cars by prices higher than $20,000</li>\n<li>Sort cars from least to greatest</li>\n<li>Print out each car and its corresponding price</li>\n</ol>\n<h4>Filter, Sort, and Map</h4>\n<p>For the first step, we'll need to get just the vehicles that are cars. We can combine this with our price requirement using one <code>Array.filter()</code> method.</p>\n<p>If we had stopped here, we would get the two Tesla cars, but they may not be in the correct order. To ensure that the cars are ordered from least to greatest by price, we need to apply the <code>Array.sort()</code> method.</p>\n<p>This can be done through chaining. Because <code>Array.filter()</code> returns an array, we can chain the sort method, which will be applied to the result of the previous filter method.</p>\n<pre><code class=\"language-js\">vehicles\n  .filter(vehicle => vehicle.type === 'car' &#x26;&#x26; vehicle.price > 20000)\n  .sort((vehicle1, vehicle2) => vehicle1.price - vehicle2.price)\n  .map(vehicle =>\n    console.log(\n      `${vehicle.color} ${vehicle.brand} ${\n        vehicle.type\n      } is $${vehicle.price.toFixed(2)}`\n    )\n  )\n</code></pre>\n<p>Now that we have the desired outcome that we were looking for, it's time to print the result to the console. We can conveniently print out each element in our final array using <code>Array.map()</code>.</p>\n<pre><code class=\"language-js\">// red Tesla car is $50000.00\n// gray Tesla car is $80000.00\n</code></pre>\n<p>Template literals can be used to format the text as we choose, using property values from the elements in the array.</p>"}},{"node":{"fields":{"slug":"how-to-add-or-remove-an-element-at-the-end-of-an-array","dateSlug":"2021-08-08","postID":"how-to-add-or-remove-an-element-at-the-end-of-an-array-2021-08-08"},"frontmatter":{"category":"arrays","tags":["javascript","es6","arrays"],"date":"August 8, 2021","format":"image","title":"How to add or remove an element at the end of an array","author":{"name":"Stephen Sun"},"image":{"childImageSharp":{"fluid":{"base64":"data:image/jpeg;base64,/9j/2wBDABALDA4MChAODQ4SERATGCgaGBYWGDEjJR0oOjM9PDkzODdASFxOQERXRTc4UG1RV19iZ2hnPk1xeXBkeFxlZ2P/2wBDARESEhgVGC8aGi9jQjhCY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2P/wgARCAANABQDASIAAhEBAxEB/8QAFwAAAwEAAAAAAAAAAAAAAAAAAAEEAv/EABQBAQAAAAAAAAAAAAAAAAAAAAD/2gAMAwEAAhADEAAAAaidGRB//8QAGhABAQACAwAAAAAAAAAAAAAAAQACERIhIv/aAAgBAQABBQI6tE5Is5eeV//EABcRAQADAAAAAAAAAAAAAAAAAAABETH/2gAIAQMBAT8BjFv/xAAUEQEAAAAAAAAAAAAAAAAAAAAQ/9oACAECAQE/AT//xAAXEAEAAwAAAAAAAAAAAAAAAAAQATJh/9oACAEBAAY/AipGn//EABoQAQADAQEBAAAAAAAAAAAAAAEAESExQaH/2gAIAQEAAT8hAr4ToB5KABl3LyIVQYM+z//aAAwDAQACAAMAAAAQ88//xAAWEQEBAQAAAAAAAAAAAAAAAAABEBH/2gAIAQMBAT8QAaY//8QAFhEBAQEAAAAAAAAAAAAAAAAAEQAB/9oACAECAQE/ENUi/8QAGhABAAMBAQEAAAAAAAAAAAAAAQARITFBUf/aAAgBAQABPxBwA6NMXGN6TOx8SF1yOy4AKfS6qHKQt7pKbr5H/9k=","aspectRatio":1.5,"src":"/static/beaf25d428c6b154a246d4c6be1d7e49/3866d/how-to-add-or-remove-an-element-at-the-end-of-an-array.jpg","srcSet":"/static/beaf25d428c6b154a246d4c6be1d7e49/d1bff/how-to-add-or-remove-an-element-at-the-end-of-an-array.jpg 6w,\n/static/beaf25d428c6b154a246d4c6be1d7e49/3866d/how-to-add-or-remove-an-element-at-the-end-of-an-array.jpg 510w,\n/static/beaf25d428c6b154a246d4c6be1d7e49/f7bf2/how-to-add-or-remove-an-element-at-the-end-of-an-array.jpg 1920w","srcWebp":"/static/beaf25d428c6b154a246d4c6be1d7e49/47cfc/how-to-add-or-remove-an-element-at-the-end-of-an-array.webp","srcSetWebp":"/static/beaf25d428c6b154a246d4c6be1d7e49/ab631/how-to-add-or-remove-an-element-at-the-end-of-an-array.webp 6w,\n/static/beaf25d428c6b154a246d4c6be1d7e49/47cfc/how-to-add-or-remove-an-element-at-the-end-of-an-array.webp 510w,\n/static/beaf25d428c6b154a246d4c6be1d7e49/2532a/how-to-add-or-remove-an-element-at-the-end-of-an-array.webp 1920w","sizes":"(max-width: 510px) 100vw, 510px","presentationWidth":510,"presentationHeight":350}}}},"excerpt":"Link to code snippet: GitHub Let's begin with an array of colors: We can add the color yellow to the end of our array: Now, our array contains four different colors…","html":"<p><strong>Link to code snippet: <a href=\"https://github.com/javascriptfullstack/javascript-snippets/blob/master/how-to-add-or-remove-an-element-at-the-end-of-an-array/index.js\">GitHub</a></strong></p>\n<p>Let's begin with an array of colors:</p>\n<pre><code class=\"language-js\">const colors = ['red', 'blue', 'green']\n</code></pre>\n<p>We can add the color <code>yellow</code> to the end of our array:</p>\n<pre><code class=\"language-js\">colors.push('yellow')\n</code></pre>\n<p>Now, our array contains four different colors:</p>\n<pre><code class=\"language-js\">console.log(colors) // 4\n</code></pre>\n<p>We can also push multiple elements at the same time:</p>\n<pre><code class=\"language-js\">colors.push('orange', 'gray', 'black')\n</code></pre>\n<p>Now, we have a total of seven colors in our array:</p>\n<pre><code class=\"language-js\">console.log(colors) // 7\n</code></pre>\n<p>If we want to remove elements from the end of the array, we can use the <code>Array.pop()</code> method:</p>\n<pre><code class=\"language-js\">colors.pop()\n</code></pre>\n<p>Finally, we're left with an array containing only six elements:</p>\n<pre><code class=\"language-js\">console.log(colors) // [ 'red', 'blue', 'green', 'yellow', 'orange', 'gray' ]\n</code></pre>"}},{"node":{"fields":{"slug":"how-to-add-dynamically-named-properties-to-objects","dateSlug":"2021-08-01","postID":"how-to-add-dynamically-named-properties-to-objects-2021-08-01"},"frontmatter":{"category":"objects","tags":["javascript","objects","es6","template literals"],"date":"August 1, 2021","format":"image","title":"How to add dynamically named properties to objects","author":{"name":"Stephen Sun"},"image":{"childImageSharp":{"fluid":{"base64":"data:image/jpeg;base64,/9j/2wBDABALDA4MChAODQ4SERATGCgaGBYWGDEjJR0oOjM9PDkzODdASFxOQERXRTc4UG1RV19iZ2hnPk1xeXBkeFxlZ2P/2wBDARESEhgVGC8aGi9jQjhCY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2P/wgARCAANABQDASIAAhEBAxEB/8QAFwAAAwEAAAAAAAAAAAAAAAAAAAQFAv/EABYBAQEBAAAAAAAAAAAAAAAAAAEAAv/aAAwDAQACEAMQAAABzSmtZWBYb//EABoQAAEFAQAAAAAAAAAAAAAAAAEAAgMREiH/2gAIAQEAAQUCidlB9jQUPTaeaP8A/8QAFBEBAAAAAAAAAAAAAAAAAAAAEP/aAAgBAwEBPwE//8QAFREBAQAAAAAAAAAAAAAAAAAAEBH/2gAIAQIBAT8Bp//EABkQAAMAAwAAAAAAAAAAAAAAAAABECExgf/aAAgBAQAGPwLQmZnZ/8QAGhABAAIDAQAAAAAAAAAAAAAAAQARIVFxof/aAAgBAQABPyEXfmFS4Y9U30rUEUxh6J//2gAMAwEAAgADAAAAEJ/v/8QAFhEBAQEAAAAAAAAAAAAAAAAAAAER/9oACAEDAQE/ELGP/8QAFhEBAQEAAAAAAAAAAAAAAAAAAAER/9oACAECAQE/EIa//8QAGhABAAMBAQEAAAAAAAAAAAAAAQARITFBYf/aAAgBAQABPxACha0A1ouBgeK/YBoAPEgVsnJjs0C+Ni0UKyyf/9k=","aspectRatio":1.5,"src":"/static/fc6d8e6f0d34b8322b07b10bf3014041/3866d/how-to-add-dynamically-named-properties-to-objects.jpg","srcSet":"/static/fc6d8e6f0d34b8322b07b10bf3014041/d1bff/how-to-add-dynamically-named-properties-to-objects.jpg 6w,\n/static/fc6d8e6f0d34b8322b07b10bf3014041/3866d/how-to-add-dynamically-named-properties-to-objects.jpg 510w,\n/static/fc6d8e6f0d34b8322b07b10bf3014041/f7bf2/how-to-add-dynamically-named-properties-to-objects.jpg 1920w","srcWebp":"/static/fc6d8e6f0d34b8322b07b10bf3014041/47cfc/how-to-add-dynamically-named-properties-to-objects.webp","srcSetWebp":"/static/fc6d8e6f0d34b8322b07b10bf3014041/ab631/how-to-add-dynamically-named-properties-to-objects.webp 6w,\n/static/fc6d8e6f0d34b8322b07b10bf3014041/47cfc/how-to-add-dynamically-named-properties-to-objects.webp 510w,\n/static/fc6d8e6f0d34b8322b07b10bf3014041/2532a/how-to-add-dynamically-named-properties-to-objects.webp 1920w","sizes":"(max-width: 510px) 100vw, 510px","presentationWidth":510,"presentationHeight":350}}}},"excerpt":"Link to code snippet: GitHub One of the great features of ES6 is computed property names. Let's say we have the following properties: And a person object: As long a…","html":"<p><strong>Link to code snippet: <a href=\"https://github.com/javascriptfullstack/javascript-snippets/blob/master/how-to-add-dynamically-named-properties-to-objects/index.js\">GitHub</a></strong></p>\n<p>One of the great features of ES6 is computed property names.</p>\n<p>Let's say we have the following properties:</p>\n<pre><code class=\"language-js\">const a = 'age'\nconst j = 'j'\n</code></pre>\n<p>And a <code>person</code> object:</p>\n<pre><code class=\"language-js\">const person = {\n  firstName: 'John',\n  lastName: 'Doe',\n  [a]: 25,\n  [`${j}ob`]: 'Software Developer'\n}\n</code></pre>\n<p>As long as we have brackets around our expressions, these expressions will be dynamically translated into the string used as the key.</p>\n<p>This includes template literals and string concatenation.</p>\n<p>If we now log the <code>person</code> object, we would get the following result:</p>\n<pre><code class=\"language-js\">{\n  firstName: 'John',\n  lastName: 'Doe',\n  age: 25,\n  job: 'Software Developer'\n}\n</code></pre>\n<p>This method can also be used in functions without the need of creating an object! Passing in the two properties into our <code>createPerson</code> function gives the same result:</p>\n<pre><code class=\"language-js\">const createPerson = (a, j) => {\n  return {\n    firstName: 'John',\n    lastName: 'Doe',\n    [a]: 25,\n    [`${j}ob`]: 'Software Developer'\n  }\n}\n</code></pre>"}},{"node":{"fields":{"slug":"how-to-add-days-to-a-date-object","dateSlug":"2021-06-14","postID":"how-to-add-days-to-a-date-object-2021-06-14"},"frontmatter":{"category":"dates","tags":["javascript","dates"],"date":"June 14, 2021","format":"image","title":"How to add days to a date object","author":{"name":"Stephen Sun"},"image":{"childImageSharp":{"fluid":{"base64":"data:image/jpeg;base64,/9j/2wBDABALDA4MChAODQ4SERATGCgaGBYWGDEjJR0oOjM9PDkzODdASFxOQERXRTc4UG1RV19iZ2hnPk1xeXBkeFxlZ2P/2wBDARESEhgVGC8aGi9jQjhCY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2P/wgARCAANABQDASIAAhEBAxEB/8QAGAAAAgMAAAAAAAAAAAAAAAAAAAUBAgP/xAAVAQEBAAAAAAAAAAAAAAAAAAABAP/aAAwDAQACEAMQAAABa6o3ZWIE/8QAGBABAAMBAAAAAAAAAAAAAAAAAQACAxH/2gAIAQEAAQUCtrWqPSYttNg4T//EABURAQEAAAAAAAAAAAAAAAAAAAEQ/9oACAEDAQE/AWf/xAAUEQEAAAAAAAAAAAAAAAAAAAAQ/9oACAECAQE/AT//xAAZEAACAwEAAAAAAAAAAAAAAAAAEQECECH/2gAIAQEABj8C6OMU2Fn/xAAbEAACAwADAAAAAAAAAAAAAAABEQAQMSFBkf/aAAgBAQABPyFCfyCFgaflzvcEpX//2gAMAwEAAgADAAAAEP8A3//EABURAQEAAAAAAAAAAAAAAAAAAAEQ/9oACAEDAQE/EAE//8QAFhEBAQEAAAAAAAAAAAAAAAAAARAR/9oACAECAQE/EB2f/8QAGxABAAICAwAAAAAAAAAAAAAAAREhABAxUZH/2gAIAQEAAT8QbMYBUke4vEhJoDBhsFC6GjDcsHfOv//Z","aspectRatio":1.5,"src":"/static/00fdda278f7b47977f22dc7c77c8dfa1/3866d/how-to-add-days-to-a-date-object.jpg","srcSet":"/static/00fdda278f7b47977f22dc7c77c8dfa1/d1bff/how-to-add-days-to-a-date-object.jpg 6w,\n/static/00fdda278f7b47977f22dc7c77c8dfa1/3866d/how-to-add-days-to-a-date-object.jpg 510w,\n/static/00fdda278f7b47977f22dc7c77c8dfa1/f7bf2/how-to-add-days-to-a-date-object.jpg 1920w","srcWebp":"/static/00fdda278f7b47977f22dc7c77c8dfa1/47cfc/how-to-add-days-to-a-date-object.webp","srcSetWebp":"/static/00fdda278f7b47977f22dc7c77c8dfa1/ab631/how-to-add-days-to-a-date-object.webp 6w,\n/static/00fdda278f7b47977f22dc7c77c8dfa1/47cfc/how-to-add-days-to-a-date-object.webp 510w,\n/static/00fdda278f7b47977f22dc7c77c8dfa1/2532a/how-to-add-days-to-a-date-object.webp 1920w","sizes":"(max-width: 510px) 100vw, 510px","presentationWidth":510,"presentationHeight":350}}}},"excerpt":"Link to code snippet: GitHub Dates can be a bit tricky in JavaScript. Oftentimes, we may need to add a given number of days to a date object. Date objects have getD…","html":"<p><strong>Link to code snippet: <a href=\"https://github.com/javascriptfullstack/javascript-snippets/blob/master/how-to-add-days-to-a-date-object/index.js\">GitHub</a></strong></p>\n<p>Dates can be a bit tricky in JavaScript.</p>\n<p>Oftentimes, we may need to add a given number of days to a date object.</p>\n<p>Date objects have <code>getDate()</code> and <code>setDate()</code> methods that can be used to get and set dates.</p>\n<p>Let's first create a function named <code>addDays</code>. This function will need to take in two arguments: a date and the number of days to be added to this date.</p>\n<pre><code class=\"language-js\">const addDays = (date, days) => {\n  const newDate = new Date(date)\n  newDate.setDate(newDate.getDate() + days)\n  return newDate\n}\n</code></pre>\n<p>If we directly call the <code>setDate()</code> method on our date object, then the date would be mutated. This could potentially cause issues, especially if we're using this date elsewhere.</p>\n<p>Instead, we should create a new date instance, perform the operation and return this new date.</p>\n<p>Calling <code>getDate()</code> on our new date object gets us the day of the month according to local time. We can then add the number of days to this value.</p>\n<p>Last but not least, we will need to call <code>setDate()</code> on our new date object to set the calculated date.</p>\n<p>What if we wanted to add three days to today's date? Let's try it out.</p>\n<pre><code class=\"language-js\">const date = new Date()\nconst newDate = addDays(date, 3)\nconsole.log(newDate) // Thu Jun 17 2021 21:33:05 GMT-0500 (Central Daylight Time)\n</code></pre>\n<p>Creating a new date instance will give use the current date. We can use our <code>addDays()</code> function and pass our date instance and a value of three for the second argument.</p>\n<p>Logging this result gives us <code>Thu Jun 17 2021 21:33:05 GMT-0500 (Central Daylight Time)</code>.</p>\n<p>(It is currently June 14, 2021 as I'm typing this).</p>"}},{"node":{"fields":{"slug":"how-to-add-key-value-pairs-to-an-object","dateSlug":"2021-03-08","postID":"how-to-add-key-value-pairs-to-an-object-2021-03-08"},"frontmatter":{"category":"objects","tags":["javascript","es6","objects"],"date":"March 8, 2021","format":"image","title":"How to add key value pairs to an object","author":{"name":"Stephen Sun"},"image":{"childImageSharp":{"fluid":{"base64":"data:image/jpeg;base64,/9j/2wBDABALDA4MChAODQ4SERATGCgaGBYWGDEjJR0oOjM9PDkzODdASFxOQERXRTc4UG1RV19iZ2hnPk1xeXBkeFxlZ2P/2wBDARESEhgVGC8aGi9jQjhCY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2P/wgARCAANABQDASIAAhEBAxEB/8QAFwABAQEBAAAAAAAAAAAAAAAAAAMBBf/EABUBAQEAAAAAAAAAAAAAAAAAAAAB/9oADAMBAAIQAxAAAAHgWkjBX//EABcQAAMBAAAAAAAAAAAAAAAAAAIQEQD/2gAIAQEAAQUCxDHV/8QAFBEBAAAAAAAAAAAAAAAAAAAAEP/aAAgBAwEBPwE//8QAFBEBAAAAAAAAAAAAAAAAAAAAEP/aAAgBAgEBPwE//8QAFBABAAAAAAAAAAAAAAAAAAAAIP/aAAgBAQAGPwJf/8QAGRABAQEAAwAAAAAAAAAAAAAAAQAREDFx/9oACAEBAAE/ISbuj48Dlq2//9oADAMBAAIAAwAAABCcz//EABYRAAMAAAAAAAAAAAAAAAAAABARIf/aAAgBAwEBPxCIf//EABURAQEAAAAAAAAAAAAAAAAAABAh/9oACAECAQE/EKf/xAAbEAEAAgIDAAAAAAAAAAAAAAABACExURARQf/aAAgBAQABPxAqgZYCCBTYDrhcKinuZ23P/9k=","aspectRatio":1.5,"src":"/static/29f9bf9ed69cb4803d874ea179067e09/3866d/how-to-add-key-value-pairs-to-an-object.jpg","srcSet":"/static/29f9bf9ed69cb4803d874ea179067e09/d1bff/how-to-add-key-value-pairs-to-an-object.jpg 6w,\n/static/29f9bf9ed69cb4803d874ea179067e09/3866d/how-to-add-key-value-pairs-to-an-object.jpg 510w,\n/static/29f9bf9ed69cb4803d874ea179067e09/f7bf2/how-to-add-key-value-pairs-to-an-object.jpg 1920w","srcWebp":"/static/29f9bf9ed69cb4803d874ea179067e09/47cfc/how-to-add-key-value-pairs-to-an-object.webp","srcSetWebp":"/static/29f9bf9ed69cb4803d874ea179067e09/ab631/how-to-add-key-value-pairs-to-an-object.webp 6w,\n/static/29f9bf9ed69cb4803d874ea179067e09/47cfc/how-to-add-key-value-pairs-to-an-object.webp 510w,\n/static/29f9bf9ed69cb4803d874ea179067e09/2532a/how-to-add-key-value-pairs-to-an-object.webp 1920w","sizes":"(max-width: 510px) 100vw, 510px","presentationWidth":510,"presentationHeight":350}}}},"excerpt":"Link to code snippet: GitHub Let's go over a few different methods of adding key/value pairs to an object! Let's begin with an object named orange and give it two p…","html":"<p><strong>Link to code snippet: <a href=\"https://github.com/javascriptfullstack/javascript-snippets/blob/master/how-to-add-a-key-value-pair-to-an-object/index.js\">GitHub</a></strong></p>\n<p>Let's go over a few different methods of adding key/value pairs to an object!</p>\n<p>Let's begin with an object named <code>orange</code> and give it two properties: <code>type</code> and <code>fruit</code>.</p>\n<pre><code class=\"language-js\">const orange = {\n  type: 'fruit',\n  color: 'orange',\n}\n</code></pre>\n<h4>Method 1: Dot Notation</h4>\n<p>The first method is dot notation. We can access properties on an object by calling <code>object.property</code>. In our example, <code>orange</code> is our object and <code>type</code> is a property of <code>orange</code>.</p>\n<p>Logging <code>orange.type</code> will give us the value <code>fruit</code>.</p>\n<pre><code class=\"language-js\">console.log(orange.type) // fruit\n</code></pre>\n<p>Adding new properties can be done in a similar fashion. Even though our <code>orange</code> object doesn't have a property named <code>shape</code>, we can add the key/value pair for this property using dot notation.</p>\n<pre><code class=\"language-js\">orange.shape = 'circle'\nconsole.log(orange.shape) // circle\n</code></pre>\n<p>After setting the <code>shape</code> property to <code>circle</code>, our <code>orange</code> object is now modified to include this key/value pair.</p>\n<h4>Method 2: Bracket Notation</h4>\n<p>Bracket notation is another way of accessing properties on an object, but with a different syntax, <code>object[property]</code>.</p>\n<p>Logging <code>orange['type']</code> will again give us the value <code>fruit</code>.</p>\n<pre><code class=\"language-js\">console.log(orange['type']) // fruit\n</code></pre>\n<p>To add on to our example, let's add a new property called <code>weight</code> and give it a value of <code>1</code>.</p>\n<pre><code class=\"language-js\">orange['weight'] = 1\nconsole.log(orange['weight']) // 1\n</code></pre>\n<p>Now, our <code>orange</code> object has a total of four properties: <code>type, color, shape and weight</code>.</p>\n<h4>Method 3: Object.assign()</h4>\n<p>The <code>Object.assign()</code> method allows us to copy all the properties from one object to another object.</p>\n<p>Let's create an object containing the properties we want to add to our <code>orange</code> object. We'll call this object <code>extraProps</code>.</p>\n<pre><code class=\"language-js\">const extraProps = {\n  length: 4,\n  width: 4,\n}\n</code></pre>\n<p>Now, let's add the key/value pairs from our <code>extraProps</code> object and add them to our <code>orange</code> object. We'll call the new object <code>newOrange</code>.</p>\n<pre><code class=\"language-js\">const newOrange = Object.assign(orange, extraProps)\n</code></pre>\n<p><code>newOrange</code> now contains the properties previously added, as well as <code>length</code> and <code>width</code> from our <code>extraProps</code> object.</p>\n<h4>Method 4: Object Spread Operator</h4>\n<p>The object spread operator is similar to the <code>Object.assign()</code> method but provides a shorter syntax.</p>\n<p>Let's create an object to highlight how this method works. We'll call this object <code>price</code>.</p>\n<pre><code class=\"language-js\">const price = { cost: 0.99 }\n</code></pre>\n<p>If we wanted to clone our <code>orange</code> object, we can do so.</p>\n<pre><code class=\"language-js\">const anotherOrange = { ...orange }\n</code></pre>\n<p>Our <code>anotherOrange</code> object will contain all the properties that the <code>orange</code> object has.</p>\n<p>Now, let's add a <code>cost</code> property to our <code>anotherOrange</code> object.</p>\n<p>We can do this simply by taking advantage of the spread syntax. We'll call the new object that's created, <code>orangeForSale</code>.</p>\n<pre><code class=\"language-js\">const orangeForSale = { ...anotherOrange, ...price }\n</code></pre>\n<p>Our <code>orangeForSale</code> object contains all the properties from the previous examples, with an addition of a <code>cost</code> property.</p>"}},{"node":{"fields":{"slug":"beginners-guide-to-git","dateSlug":"2021-03-03","postID":"beginners-guide-to-git-2021-03-03"},"frontmatter":{"category":"git","tags":["git","source control"],"date":"March 3, 2021","format":"image","title":"Beginner's Guide to Git","author":{"name":"Stephen Sun"},"image":{"childImageSharp":{"fluid":{"base64":"data:image/jpeg;base64,/9j/2wBDABALDA4MChAODQ4SERATGCgaGBYWGDEjJR0oOjM9PDkzODdASFxOQERXRTc4UG1RV19iZ2hnPk1xeXBkeFxlZ2P/2wBDARESEhgVGC8aGi9jQjhCY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2P/wgARCAANABQDASIAAhEBAxEB/8QAFwABAQEBAAAAAAAAAAAAAAAAAAIBBf/EABYBAQEBAAAAAAAAAAAAAAAAAAABAv/aAAwDAQACEAMQAAAB5mzWpIP/xAAUEAEAAAAAAAAAAAAAAAAAAAAg/9oACAEBAAEFAl//xAAUEQEAAAAAAAAAAAAAAAAAAAAQ/9oACAEDAQE/AT//xAAUEQEAAAAAAAAAAAAAAAAAAAAQ/9oACAECAQE/AT//xAAUEAEAAAAAAAAAAAAAAAAAAAAg/9oACAEBAAY/Al//xAAZEAACAwEAAAAAAAAAAAAAAAABEAAxQXH/2gAIAQEAAT8hFw8eL//aAAwDAQACAAMAAAAQaB//xAAUEQEAAAAAAAAAAAAAAAAAAAAQ/9oACAEDAQE/ED//xAAUEQEAAAAAAAAAAAAAAAAAAAAQ/9oACAECAQE/ED//xAAaEAEBAQADAQAAAAAAAAAAAAABABEhMVFB/9oACAEBAAE/EFlPqkfMvg26J4e2/9k=","aspectRatio":1.5,"src":"/static/82d3ef752c36817ca811b5bf88636e99/3866d/beginners-guide-to-git.jpg","srcSet":"/static/82d3ef752c36817ca811b5bf88636e99/d1bff/beginners-guide-to-git.jpg 6w,\n/static/82d3ef752c36817ca811b5bf88636e99/3866d/beginners-guide-to-git.jpg 510w,\n/static/82d3ef752c36817ca811b5bf88636e99/f7bf2/beginners-guide-to-git.jpg 1920w","srcWebp":"/static/82d3ef752c36817ca811b5bf88636e99/47cfc/beginners-guide-to-git.webp","srcSetWebp":"/static/82d3ef752c36817ca811b5bf88636e99/ab631/beginners-guide-to-git.webp 6w,\n/static/82d3ef752c36817ca811b5bf88636e99/47cfc/beginners-guide-to-git.webp 510w,\n/static/82d3ef752c36817ca811b5bf88636e99/2532a/beginners-guide-to-git.webp 1920w","sizes":"(max-width: 510px) 100vw, 510px","presentationWidth":510,"presentationHeight":350}}}},"excerpt":"What is Git Git, in a nutshell, is a system that allows us to properly and effectively track code changes. It allows multiple developers to work together at the sam…","html":"<h3>What is Git</h3>\n<p>Git, in a nutshell, is a system that allows us to properly and effectively track code changes. It allows multiple developers to work together at the same time, while also maintaining a history of all the changes in a repository. Git also provides many usefuls features such as branching and merging to allow developers to work on specific features independently.</p>\n<h3>Install Git</h3>\n<p>Download Git: <a href=\"https://git-scm.com/book/en/v2/Getting-Started-Installing-Git\">Getting started installing Git</a></p>\n<h3>Essential Git Commands</h3>\n<p><code>git init</code></p>\n<p><code>git clone &#x3C;path/url></code></p>\n<p><code>git add &#x3C;filename></code></p>\n<p><code>git commit -m \"&#x3C;commit message>\"</code></p>\n<p><code>git push origin &#x3C;branch name></code></p>\n<p><code>git pull</code></p>\n<p><code>git status</code></p>\n<p><code>git merge &#x3C;branch name></code></p>\n<p><code>git checkout -b &#x3C;branch name></code></p>\n<p><code>git checkout master</code></p>\n<p><code>git branch -d &#x3C;branch name></code></p>\n<p><code>git remote add origin &#x3C;server></code></p>\n<h3>Git Walkthrough</h3>\n<h4>Step 1: Create local Git repository</h4>\n<p>Find a good location where you would like to store your repositories and create a folder for your new project. For this example, let's use <code>my-first-project</code>.</p>\n<p>Since this is a brand new repository, we need to initialize it with <code>git init</code>. This tells Git to track code changes for your project.</p>\n<pre><code>mkdir my-first-project\ncd my-first-project\ngit init\n</code></pre>\n<p>Next, let's create a file called <code>index.js</code> using the touch command in the terminal.</p>\n<pre><code>touch index.js\n</code></pre>\n<h4>Step 2: Add a new file to the staging area</h4>\n<p>To include this change in our upcoming git commit, we will need to add this file to the staging area. We can think of this staging area as git's way of grouping our pre-commit changes together. This can be done with the add command.</p>\n<pre><code>git add index.js\n</code></pre>\n<p>Now, what if we wanted to add more than one file at a time? All we have to do is list out all the file names at the end. It would look something like this:</p>\n<pre><code>git add index.js file1.js file2.js file3.js\n</code></pre>\n<p>Also, if we wanted to simply add all the files in our project, we can use the shortcut:</p>\n<pre><code>git add .\n</code></pre>\n<p>All changes, staged or unstaged, can be checked at any time with the status command.</p>\n<pre><code>git status\n</code></pre>\n<h4>Step 3: Create a new commit</h4>\n<p>Once we're satisfied with our staged changes, it's time to create our first commit with the commit command. We should always add a message to our commit, describing our code changes.</p>\n<pre><code>git commit -m \"Created index.js file\"\n</code></pre>\n<h4>Step 4: Push our commit to the remote repository</h4>\n<p>The commit is now ready to be pushed from our machine to our remote repository (GitHub, Gitlab, Bitbucket, etc). We will use the push command to do so. The <code>origin</code> keyword is a shorthand name for our remote repository and <code>master</code> refers to the branch we want to push our commit to. If we wanted to push to a different branch, we can specify another branch name (e.g. development).</p>\n<pre><code>git push origin master\n</code></pre>"}},{"node":{"fields":{"slug":"how-to-add-or-remove-an-element-at-the-beginning-of-an-array","dateSlug":"2020-07-30","postID":"how-to-add-or-remove-an-element-at-the-beginning-of-an-array-2020-07-30"},"frontmatter":{"category":"arrays","tags":["javascript","es6","arrays"],"date":"July 30, 2020","format":"image","title":"How to add or remove an element at the beginning of an array","author":{"name":"Stephen Sun"},"image":{"childImageSharp":{"fluid":{"base64":"data:image/jpeg;base64,/9j/2wBDABALDA4MChAODQ4SERATGCgaGBYWGDEjJR0oOjM9PDkzODdASFxOQERXRTc4UG1RV19iZ2hnPk1xeXBkeFxlZ2P/2wBDARESEhgVGC8aGi9jQjhCY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2P/wgARCAANABQDASIAAhEBAxEB/8QAFwABAQEBAAAAAAAAAAAAAAAAAAMBBf/EABUBAQEAAAAAAAAAAAAAAAAAAAAB/9oADAMBAAIQAxAAAAHn6oVQR//EABwQAAEDBQAAAAAAAAAAAAAAAAECAxIQESEiMf/aAAgBAQABBQIHaWEPNxT29P/EABQRAQAAAAAAAAAAAAAAAAAAABD/2gAIAQMBAT8BP//EABQRAQAAAAAAAAAAAAAAAAAAABD/2gAIAQIBAT8BP//EABkQAAIDAQAAAAAAAAAAAAAAAAARAQIhIP/aAAgBAQAGPwJD3CHRzx//xAAcEAEAAgIDAQAAAAAAAAAAAAABABEhMUFRYXH/2gAIAQEAAT8hoNfZkwZMkAXeLU0l8yxYfH2O5//aAAwDAQACAAMAAAAQJz//xAAUEQEAAAAAAAAAAAAAAAAAAAAQ/9oACAEDAQE/ED//xAAVEQEBAAAAAAAAAAAAAAAAAAABEP/aAAgBAgEBPxBCf//EABsQAQEAAgMBAAAAAAAAAAAAAAERACExQVFh/9oACAEBAAE/EK4nx0mBExLwfmBSEeQVV3TLRIUbuS6BQepe8dbou4XWf//Z","aspectRatio":1.5,"src":"/static/e3fa28eee3a9ef47e4d23b55090e1271/3866d/how-to-add-or-remove-an-element-at-the-beginning-of-an-array.jpg","srcSet":"/static/e3fa28eee3a9ef47e4d23b55090e1271/d1bff/how-to-add-or-remove-an-element-at-the-beginning-of-an-array.jpg 6w,\n/static/e3fa28eee3a9ef47e4d23b55090e1271/3866d/how-to-add-or-remove-an-element-at-the-beginning-of-an-array.jpg 510w,\n/static/e3fa28eee3a9ef47e4d23b55090e1271/f7bf2/how-to-add-or-remove-an-element-at-the-beginning-of-an-array.jpg 1920w","srcWebp":"/static/e3fa28eee3a9ef47e4d23b55090e1271/47cfc/how-to-add-or-remove-an-element-at-the-beginning-of-an-array.webp","srcSetWebp":"/static/e3fa28eee3a9ef47e4d23b55090e1271/ab631/how-to-add-or-remove-an-element-at-the-beginning-of-an-array.webp 6w,\n/static/e3fa28eee3a9ef47e4d23b55090e1271/47cfc/how-to-add-or-remove-an-element-at-the-beginning-of-an-array.webp 510w,\n/static/e3fa28eee3a9ef47e4d23b55090e1271/2532a/how-to-add-or-remove-an-element-at-the-beginning-of-an-array.webp 1920w","sizes":"(max-width: 510px) 100vw, 510px","presentationWidth":510,"presentationHeight":350}}}},"excerpt":"Using the push() method, we can add elements to the end of an array. But what if our goal is to add elements to the beginning of an array? JavaScript has another me…","html":"<p>Using the push() method, we can add elements to the end of an array.</p>\n<p>But what if our goal is to add elements to the beginning of an array?</p>\n<p>JavaScript has another method called unshift() that can do just that.</p>\n<p>Let's say we have an array of colors:</p>\n<pre><code class=\"language-js\">const colors = ['red', 'blue', 'green']\n</code></pre>\n<p>And we want to add the color yellow to the beginning of our array:</p>\n<pre><code class=\"language-js\">console.log(colors.unshift('yellow')) // 4\nconsole.log(colors) // ['yellow', 'red', 'blue', 'green']\n</code></pre>\n<p>We can also add more than one color at a time.</p>\n<p>Let's take our colors array (including yellow) and add some more colors:</p>\n<pre><code class=\"language-js\">console.log(colors.unshift('orange', 'gray', 'black')) // 7\nconsole.log(colors) // ['orange', 'gray', 'black', 'yellow', 'red', 'blue', 'green]\n</code></pre>\n<p>What if we want to remove an element from the beginning of the array instead?</p>\n<p>Similar to the pop() method which removes the last element of an array, we have the shift() method!</p>\n<p>Let's take our colors array that now has seven colors and remove the first element:</p>\n<pre><code class=\"language-js\">console.log(colors.shift()) // orange\nconsole.log(colors) // ['gray', 'black', 'yellow', 'red', 'blue', 'green]\n</code></pre>\n<p>If we want to remove multiple colors, then we would need to use the shift() method in a loop.</p>\n<p>The downside to using unshift() and shift() is that these methods mutate the original array.</p>\n<p>If we want to avoid mutations, we can use concat() or the spread operator, which will return a new array.</p>"}},{"node":{"fields":{"slug":"how-to-check-if-a-key-exists-in-a-javascript-object","dateSlug":"2020-07-27","postID":"how-to-check-if-a-key-exists-in-a-javascript-object-2020-07-27"},"frontmatter":{"category":"objects","tags":["javascript","es6","objects"],"date":"July 27, 2020","format":"image","title":"How to check if a key exists in a JavaScript object","author":{"name":"Stephen Sun"},"image":{"childImageSharp":{"fluid":{"base64":"data:image/jpeg;base64,/9j/2wBDABALDA4MChAODQ4SERATGCgaGBYWGDEjJR0oOjM9PDkzODdASFxOQERXRTc4UG1RV19iZ2hnPk1xeXBkeFxlZ2P/2wBDARESEhgVGC8aGi9jQjhCY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2P/wgARCAANABQDASIAAhEBAxEB/8QAFwAAAwEAAAAAAAAAAAAAAAAAAAMEBf/EABQBAQAAAAAAAAAAAAAAAAAAAAL/2gAMAwEAAhADEAAAAbFzLKDQEf/EABsQAAMAAgMAAAAAAAAAAAAAAAECEQADBBND/9oACAEBAAEFAgxyiOvbgev68ZLp/8QAFREBAQAAAAAAAAAAAAAAAAAAARD/2gAIAQMBAT8BJ//EABQRAQAAAAAAAAAAAAAAAAAAABD/2gAIAQIBAT8BP//EABwQAAICAgMAAAAAAAAAAAAAAAABAhESYSExQf/aAAgBAQAGPwJeI7FLRjVcEnoTP//EABoQAQEAAwEBAAAAAAAAAAAAAAERADFRIWH/2gAIAQEAAT8h1MgSvM3wt1v3LeoMnAj67g+uyiYbDtc//9oADAMBAAIAAwAAABALD//EABYRAQEBAAAAAAAAAAAAAAAAACEBEP/aAAgBAwEBPxCgz//EABcRAAMBAAAAAAAAAAAAAAAAAAABEVH/2gAIAQIBAT8Qa0p//8QAHBABAAMAAgMAAAAAAAAAAAAAAQARITGxQYHh/9oACAEBAAE/EAYhC4BR19dRvESo6Lh76qZ5MhGpsUlKW8wneCFqgoN+RGosquNn/9k=","aspectRatio":1.5,"src":"/static/be279c7c72812cf79c0d5da3613c120f/3866d/how-to-check-if-a-key-exists-in-a-javascript-object.jpg","srcSet":"/static/be279c7c72812cf79c0d5da3613c120f/d1bff/how-to-check-if-a-key-exists-in-a-javascript-object.jpg 6w,\n/static/be279c7c72812cf79c0d5da3613c120f/3866d/how-to-check-if-a-key-exists-in-a-javascript-object.jpg 510w,\n/static/be279c7c72812cf79c0d5da3613c120f/f7bf2/how-to-check-if-a-key-exists-in-a-javascript-object.jpg 1920w","srcWebp":"/static/be279c7c72812cf79c0d5da3613c120f/47cfc/how-to-check-if-a-key-exists-in-a-javascript-object.webp","srcSetWebp":"/static/be279c7c72812cf79c0d5da3613c120f/ab631/how-to-check-if-a-key-exists-in-a-javascript-object.webp 6w,\n/static/be279c7c72812cf79c0d5da3613c120f/47cfc/how-to-check-if-a-key-exists-in-a-javascript-object.webp 510w,\n/static/be279c7c72812cf79c0d5da3613c120f/2532a/how-to-check-if-a-key-exists-in-a-javascript-object.webp 1920w","sizes":"(max-width: 510px) 100vw, 510px","presentationWidth":510,"presentationHeight":350}}}},"excerpt":"When working with objects, we may need to check if a certain key exists or has a certain value. Let’s say we have a dog object: And we want to validate whether or n…","html":"<p>When working with objects, we may need to check if a certain key exists or has a certain value.</p>\n<p>Let’s say we have a dog object:</p>\n<pre><code class=\"language-js\">const dog = {\n  name: 'Jack',\n  color: 'white',\n  age: 5,\n}\n</code></pre>\n<p>And we want to validate whether or not this dog object has the key <strong>age</strong>.</p>\n<p>We can use the hasOwnProperty() method on the object, and see whether this returns true or false.</p>\n<pre><code class=\"language-js\">console.log(dog.hasOwnProperty(age)) // evaluates to true\n</code></pre>\n<p>Another option we have is to use the in operator.</p>\n<p>The in operator will return true if the key exists in our dog object.</p>\n<p>The syntax is as follows: <strong>prop</strong> in <strong>object</strong></p>\n<p>In our example, our property or key is <strong>age</strong>, and our object is <strong>dog</strong>.</p>\n<pre><code class=\"language-js\">console.log('age' in dog) // evaluates to true\n</code></pre>\n<p>A common practice is to always use a fallback to account for undefined values:</p>\n<pre><code class=\"language-js\">dog.age || 5 // evaluates to 5\n</code></pre>\n<p>This will set a default value of <strong>5</strong> in the case that <strong>age</strong> doesn’t exist.</p>"}},{"node":{"fields":{"slug":"how-to-check-if-array-contains-duplicate-values","dateSlug":"2020-07-23","postID":"how-to-check-if-array-contains-duplicate-values-2020-07-23"},"frontmatter":{"category":"arrays","tags":["javascript","es6","arrays"],"date":"July 23, 2020","format":"image","title":"How to check if array contains duplicate values","author":{"name":"Stephen Sun"},"image":{"childImageSharp":{"fluid":{"base64":"data:image/jpeg;base64,/9j/2wBDABALDA4MChAODQ4SERATGCgaGBYWGDEjJR0oOjM9PDkzODdASFxOQERXRTc4UG1RV19iZ2hnPk1xeXBkeFxlZ2P/2wBDARESEhgVGC8aGi9jQjhCY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2P/wgARCAANABQDASIAAhEBAxEB/8QAFwABAQEBAAAAAAAAAAAAAAAAAAIBBP/EABUBAQEAAAAAAAAAAAAAAAAAAAID/9oADAMBAAIQAxAAAAHq26mwR//EABoQAAICAwAAAAAAAAAAAAAAAAECACEDERL/2gAIAQEAAQUCD22UKFPSiVNz/8QAFxEAAwEAAAAAAAAAAAAAAAAAARARQf/aAAgBAwEBPwETV//EABURAQEAAAAAAAAAAAAAAAAAABAh/9oACAECAQE/Aaf/xAAXEAEAAwAAAAAAAAAAAAAAAAABABAx/9oACAEBAAY/AkmQayv/xAAZEAADAQEBAAAAAAAAAAAAAAAAARExECH/2gAIAQEAAT8hV5MKBuKkyonYqNNqcf/aAAwDAQACAAMAAAAQt9//xAAYEQADAQEAAAAAAAAAAAAAAAAAATERIf/aAAgBAwEBPxBljR3h/8QAFxEBAAMAAAAAAAAAAAAAAAAAERAhMf/aAAgBAgEBPxAW1H//xAAaEAEAAwEBAQAAAAAAAAAAAAABABEhMUFR/9oACAEBAAE/EAtBzf3LghC/IJelT5Cm+TtbHbQpWksYFB4T/9k=","aspectRatio":1.5,"src":"/static/c1502065e4dff2cef2193214782d8f91/3866d/how-to-check-if-array-contains-duplicate-values.jpg","srcSet":"/static/c1502065e4dff2cef2193214782d8f91/d1bff/how-to-check-if-array-contains-duplicate-values.jpg 6w,\n/static/c1502065e4dff2cef2193214782d8f91/3866d/how-to-check-if-array-contains-duplicate-values.jpg 510w,\n/static/c1502065e4dff2cef2193214782d8f91/f7bf2/how-to-check-if-array-contains-duplicate-values.jpg 1920w","srcWebp":"/static/c1502065e4dff2cef2193214782d8f91/47cfc/how-to-check-if-array-contains-duplicate-values.webp","srcSetWebp":"/static/c1502065e4dff2cef2193214782d8f91/ab631/how-to-check-if-array-contains-duplicate-values.webp 6w,\n/static/c1502065e4dff2cef2193214782d8f91/47cfc/how-to-check-if-array-contains-duplicate-values.webp 510w,\n/static/c1502065e4dff2cef2193214782d8f91/2532a/how-to-check-if-array-contains-duplicate-values.webp 1920w","sizes":"(max-width: 510px) 100vw, 510px","presentationWidth":510,"presentationHeight":350}}}},"excerpt":"Knowing how to check for duplicates in an array can be useful in many different situations. Here are two ways to accomplish this: Combination of some() and indexOf(…","html":"<p>Knowing how to check for duplicates in an array can be useful in many different situations. Here are two ways to accomplish this:</p>\n<ol>\n<li>Combination of some() and indexOf()</li>\n<li>Set()</li>\n</ol>\n<h4>Some Plus IndexOf</h4>\n<p>The some() method can be used to check if each element in an array passes a function.</p>\n<p>We'll be passing a callback with two arguments: the element of the array and the index of the element.</p>\n<p>In order to check whether a value already exists in an array (a duplicate), we'll use the indexOf() method and pass in each value from our colors array.</p>\n<p>The indexOf() method will return the index of the first occurence of the value.</p>\n<p>Remember how our callback in the some() method also contains the index (i)?</p>\n<p>This will be our verification!</p>\n<p>If this condition passes and there are equal index values, that means there are duplicates.</p>\n<p>In our example, we have two values of \"blue\" and two values of \"red\".</p>\n<p>This will satisfy our index comparison, and return true.</p>\n<pre><code class=\"language-js\">const colorsArray = ['red', 'blue', 'green', 'blue', 'red']\n\nconst doesArrayHaveDuplicates = colorsArray.some(\n  (val, i) => colorsArray.indexOf(val) !== i\n)\n\nconsole.log(doesArrayHaveDuplicates) // true\n</code></pre>\n<iframe\n  src=\"https://codesandbox.io/embed/using-some-and-indexof-to-check-if-array-elements-are-unique-l4cpt?fontsize=14&hidenavigation=1&theme=dark\"\n  style=\"width:100%; height:500px; border:0; border-radius: 4px; overflow:hidden;\"\n  title=\"Using Some and IndexOf to check if array elements are unique\"\n  allow=\"accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking\"\n  sandbox=\"allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts\"\n></iframe>\n<h4>Set</h4>\n<p>Set is one of the great features that came with ES6.</p>\n<p>You can think of Set as an object with a collection of values.</p>\n<p>The only catch is that each value in the Set must be unique, which makes it perfect for finding duplicates!</p>\n<p>If a value already exists in the Set, it won't be added to the collection.</p>\n<p>In our example, we create a new Set object with our colors array as our collection of values.</p>\n<p>Set internally will check for unique values, and since there are two values of \"red\", the size of our Set will only by 3 (instead of 4).</p>\n<p>The length of our colors array is 4, so our validation will return true, meaning duplicates exist.</p>\n<pre><code class=\"language-js\">const doesArrayHaveDuplicates = array => {\n  return array.length !== new Set(array).size\n}\n\nconst colorsArray = ['red', 'blue', 'green', 'red']\nconsole.log(doesArrayHaveDuplicates(colorsArray)) // fal\n</code></pre>\n<iframe\n  src=\"https://codesandbox.io/embed/using-set-to-check-if-array-elements-are-unique-1m519?fontsize=14&hidenavigation=1&theme=dark\"\n  style=\"width:100%; height:500px; border:0; border-radius: 4px; overflow:hidden;\"\n  title=\"Using Set to check if array elements are unique\"\n  allow=\"accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking\"\n  sandbox=\"allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts\"\n></iframe>"}},{"node":{"fields":{"slug":"how-to-combine-arrays-in-javascript","dateSlug":"2020-07-20","postID":"how-to-combine-arrays-in-javascript-2020-07-20"},"frontmatter":{"category":"arrays","tags":["javascript","es6","arrays"],"date":"July 20, 2020","format":"image","title":"How to combine arrays in JavaScript","author":{"name":"Stephen Sun"},"image":{"childImageSharp":{"fluid":{"base64":"data:image/jpeg;base64,/9j/2wBDABALDA4MChAODQ4SERATGCgaGBYWGDEjJR0oOjM9PDkzODdASFxOQERXRTc4UG1RV19iZ2hnPk1xeXBkeFxlZ2P/2wBDARESEhgVGC8aGi9jQjhCY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2P/wgARCAANABQDASIAAhEBAxEB/8QAGAAAAgMAAAAAAAAAAAAAAAAAAAMBAgT/xAAVAQEBAAAAAAAAAAAAAAAAAAABAP/aAAwDAQACEAMQAAABzuW8aEkf/8QAGRAAAwEBAQAAAAAAAAAAAAAAAAECERMi/9oACAEBAAEFAoSxnORFeTdP/8QAFhEBAQEAAAAAAAAAAAAAAAAAAAFR/9oACAEDAQE/AdR//8QAFBEBAAAAAAAAAAAAAAAAAAAAEP/aAAgBAgEBPwE//8QAGBAAAgMAAAAAAAAAAAAAAAAAAAEgITH/2gAIAQEABj8CRjLUP//EABsQAAIDAQEBAAAAAAAAAAAAAAAhARExQVFh/9oACAEBAAE/IUKMsePTHImNKZG6fT7Wjph//9oADAMBAAIAAwAAABC/H//EABcRAQEBAQAAAAAAAAAAAAAAAAEAETH/2gAIAQMBAT8QewGF/8QAFhEBAQEAAAAAAAAAAAAAAAAAAQBB/9oACAECAQE/ENJW/8QAHRABAAMBAAIDAAAAAAAAAAAAAQARMSFBUWFx0f/aAAgBAQABPxB9rYT1F7zGUZagltPq4+tLTsfUUhvtwN/kCclyeYwD8n//2Q==","aspectRatio":1.5,"src":"/static/69e6f46f43fa76184037cb5a2a6d7205/3866d/how-to-combine-arrays-in-javascript.jpg","srcSet":"/static/69e6f46f43fa76184037cb5a2a6d7205/d1bff/how-to-combine-arrays-in-javascript.jpg 6w,\n/static/69e6f46f43fa76184037cb5a2a6d7205/3866d/how-to-combine-arrays-in-javascript.jpg 510w,\n/static/69e6f46f43fa76184037cb5a2a6d7205/f7bf2/how-to-combine-arrays-in-javascript.jpg 1920w","srcWebp":"/static/69e6f46f43fa76184037cb5a2a6d7205/47cfc/how-to-combine-arrays-in-javascript.webp","srcSetWebp":"/static/69e6f46f43fa76184037cb5a2a6d7205/ab631/how-to-combine-arrays-in-javascript.webp 6w,\n/static/69e6f46f43fa76184037cb5a2a6d7205/47cfc/how-to-combine-arrays-in-javascript.webp 510w,\n/static/69e6f46f43fa76184037cb5a2a6d7205/2532a/how-to-combine-arrays-in-javascript.webp 1920w","sizes":"(max-width: 510px) 100vw, 510px","presentationWidth":510,"presentationHeight":350}}}},"excerpt":"Let's go over a few ways to combine arrays in Javascript! Concatenate We have two arrays, an array of numbers and an array of colors. We can use [].concat syntax to…","html":"<p>Let's go over a few ways to combine arrays in Javascript!</p>\n<h4>Concatenate</h4>\n<p>We have two arrays, an array of numbers and an array of colors.</p>\n<pre><code class=\"language-js\">const numbers = [1, 2, 3]\nconst colors = ['red', 'blue', 'green']\nconst newArray = [].concat(numbers, colors) // method 1\nconst mutatedArray = numbers.concat(colors) // method 2\ndocument.write(newArray)\n</code></pre>\n<iframe\n  src=\"https://codesandbox.io/embed/concat-arrays-q6vpe?fontsize=14&hidenavigation=1&theme=dark\"\n  style=\"width:100%; height:500px; border:0; border-radius: 4px; overflow:hidden;\"\n  title=\"Concat Arrays\"\n  allow=\"accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking\"\n  sandbox=\"allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts\"\n></iframe>\n<p>We can use [].concat syntax to create a new empty array, and then add all the elements from our number and color arrays.</p>\n<p>Since we're creating a new array, we are preserving immutability.</p>\n<p>The second way of concatenation is to take an array and add the elements from the second array.</p>\n<p>In our example, we would take our numbers array and add the elements from the colors array.</p>\n<p>The result may look the same, but the second method actually mutates our numbers array.</p>\n<p>If we wish to use our numbers array elsewhere, it won't have the same values that we started with.</p>\n<p>Be careful!</p>\n<h4>Spread Operator</h4>\n<p>ES6 gave us a new method of combining arrays: the spread operator.</p>\n<p>This specific syntax allows elements in an array to be expanded and accessed in a clean way.</p>\n<pre><code class=\"language-js\">const numbers = [1, 2, 3]\nconst colors = ['red', 'blue', 'green']\nconst newArray = [...numbers, ...colors]\ndocument.write(newArray)\n</code></pre>\n<iframe\n  src=\"https://codesandbox.io/embed/spread-operator-to-combine-arrays-8b13x?fontsize=14&hidenavigation=1&theme=dark\"\n  style=\"width:100%; height:500px; border:0; border-radius: 4px; overflow:hidden;\"\n  title=\"Spread Operator to Combine Arrays\"\n  allow=\"accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking\"\n  sandbox=\"allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts\"\n></iframe>\n<p>Instead of using concat(), we can simplify things by:</p>\n<ol>\n<li>Instantiating a new array</li>\n<li>Destructure and unpack elements from our numbers and colors array into our new array</li>\n</ol>\n<h4>Reduce</h4>\n<p>Another way to combine arrays is to use the reduce() method.</p>\n<p>It is particularly useful when you want to perform a specific operation on each element in an array.</p>\n<pre><code class=\"language-js\">const numbers = [1, 2, 3]\nconst colors = ['red', 'blue', 'green']\nconst arrays = [numbers, colors]\nconst newArray = arrays =>\n  arrays.reduce((accumulator, next) => [...accumulator, next])\ndocument.write(newArray(arrays))\n</code></pre>\n<iframe\n  src=\"https://codesandbox.io/embed/keen-wood-kpqp4?fontsize=14&hidenavigation=1&theme=dark\"\n  style=\"width:100%; height:500px; border:0; border-radius: 4px; overflow:hidden;\"\n  title=\"Combine Arrays with Reduce\"\n  allow=\"accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking\"\n  sandbox=\"allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts\"\n></iframe>\n<p>In this case, we want to loop through all the elements of both of our numbers and colors array, and add them into our new array.</p>\n<p>First, we create an array with both our numbers array and colors array.</p>\n<p>Next, we pass this array to our reduce method, which returns a new array with the elements from the accumulator and the next item.</p>\n<p>This happens to be our numbers array (accumulator) and colors array (next).</p>\n<h4>Flat</h4>\n<p>With ES2019, we now have access to the flat() method.</p>\n<p>This new method creates a new array that recursively concatenates sub-array elements.</p>\n<p>What does that mean?</p>\n<p>Let's take a look at an example!</p>\n<pre><code class=\"language-js\">const numbers = [1, 2, 3]\nconst colors = ['red', 'blue', 'green']\nconst arrays = [numbers, colors]\nconst newArray = arrays.flat(arrays)\ndocument.write(newArray)\n</code></pre>\n<iframe\n  src=\"https://codesandbox.io/embed/inspiring-yalow-n754d?fontsize=14&hidenavigation=1&theme=dark\"\n  style=\"width:100%; height:500px; border:0; border-radius: 4px; overflow:hidden;\"\n  title=\"Combine Arrays with Flat\"\n  allow=\"accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking\"\n  sandbox=\"allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts\"\n></iframe>\n<p>Let's create an array, with our numbers array and colors array as elements.</p>\n<p>Now, we have two different arrays inside an array.</p>\n<p>We can use the flat() method to flatten the two inside arrays and return one array instead.</p>\n<p>How convenient!</p>\n<p>This is extremely useful, when you have nested arrays and arrays of different sizes.</p>"}},{"node":{"fields":{"slug":"how-to-use-async-await-in-loops","dateSlug":"2020-07-16","postID":"how-to-use-async-await-in-loops-2020-07-16"},"frontmatter":{"category":"loops","tags":["javascript","es6","asynchronous","loops"],"date":"July 16, 2020","format":"image","title":"How to use async await in loops","author":{"name":"Stephen Sun"},"image":{"childImageSharp":{"fluid":{"base64":"data:image/jpeg;base64,/9j/2wBDABALDA4MChAODQ4SERATGCgaGBYWGDEjJR0oOjM9PDkzODdASFxOQERXRTc4UG1RV19iZ2hnPk1xeXBkeFxlZ2P/2wBDARESEhgVGC8aGi9jQjhCY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2NjY2P/wgARCAANABQDASIAAhEBAxEB/8QAFwAAAwEAAAAAAAAAAAAAAAAAAAMFAv/EABYBAQEBAAAAAAAAAAAAAAAAAAABAv/aAAwDAQACEAMQAAABUmhrNgloP//EABoQAAMAAwEAAAAAAAAAAAAAAAABAgMREhP/2gAIAQEAAQUCwzSMirvTJW24TPM//8QAFBEBAAAAAAAAAAAAAAAAAAAAEP/aAAgBAwEBPwE//8QAFREBAQAAAAAAAAAAAAAAAAAAARD/2gAIAQIBAT8BJ//EAB4QAAEBCQAAAAAAAAAAAAAAAAABAhARISIxMkFh/9oACAEBAAY/ApslKQTrrmzJT//EABsQAQACAwEBAAAAAAAAAAAAAAEAESExUUFh/9oACAEBAAE/IVbdxqZL4ULPsbbDktbbduLl/9oADAMBAAIAAwAAABCDL//EABURAQEAAAAAAAAAAAAAAAAAAAAh/9oACAEDAQE/EIj/xAAWEQEBAQAAAAAAAAAAAAAAAAABEQD/2gAIAQIBAT8QFLo7/8QAHBABAAICAwEAAAAAAAAAAAAAAQARITFRgcHh/9oACAEBAAE/EKG0VhM+wSYghZv7caWNI0SlzvbCMOTpyRDw8g+T/9k=","aspectRatio":1.5,"src":"/static/c9d830e2fa4303b3b97f44cfc3b1058d/3866d/how-to-use-async-await-in-loops.jpg","srcSet":"/static/c9d830e2fa4303b3b97f44cfc3b1058d/d1bff/how-to-use-async-await-in-loops.jpg 6w,\n/static/c9d830e2fa4303b3b97f44cfc3b1058d/3866d/how-to-use-async-await-in-loops.jpg 510w,\n/static/c9d830e2fa4303b3b97f44cfc3b1058d/f7bf2/how-to-use-async-await-in-loops.jpg 1920w","srcWebp":"/static/c9d830e2fa4303b3b97f44cfc3b1058d/47cfc/how-to-use-async-await-in-loops.webp","srcSetWebp":"/static/c9d830e2fa4303b3b97f44cfc3b1058d/ab631/how-to-use-async-await-in-loops.webp 6w,\n/static/c9d830e2fa4303b3b97f44cfc3b1058d/47cfc/how-to-use-async-await-in-loops.webp 510w,\n/static/c9d830e2fa4303b3b97f44cfc3b1058d/2532a/how-to-use-async-await-in-loops.webp 1920w","sizes":"(max-width: 510px) 100vw, 510px","presentationWidth":510,"presentationHeight":350}}}},"excerpt":"As developers, we frequently find ourselves needing to perform certain asynchronous tasks. What if we want to do this in a loop? Let's dive into a few examples of c…","html":"<p>As developers, we frequently find ourselves needing to perform certain asynchronous tasks.</p>\n<p>What if we want to do this in a loop?</p>\n<p>Let's dive into a few examples of common loops in JavaScript and see how async/await behaves in each scenario.</p>\n<p>We'll be using the public Dog API for all of our examples: <strong><a href=\"https://dog.ceo/dog-api/\" title=\"Dog API\">Dog API</a></strong></p>\n<h4>ForEach Loop</h4>\n<p>Let's start off with an example of a forEach loop.</p>\n<pre><code class=\"language-js\">const dogUrls = [\n  'https://dog.ceo/api/breeds/image/random',\n  'https://dog.ceo/api/breed/hound/images/random',\n  'https://dog.ceo/api/breed/hound/afghan/images/random',\n]\n\nconst getDogImage = async url => {\n  const res = await fetch(url)\n  const data = await res.json()\n  document.write(`&#x3C;img src=${data.message} />`)\n  console.log('displaying dog image')\n}\n\nconst fetchDogs = () => {\n  dogUrls.forEach(async url => await getDogImage(url))\n  console.log('Done!')\n}\n\nfetchDogs()\n</code></pre>\n<iframe\n  src=\"https://codesandbox.io/embed/asyncawait-in-foreach-loop-92jx1?fontsize=14&hidenavigation=1&theme=dark\"\n  style=\"width:100%; height:500px; margin-top: 15px; margin-bottom: 15px; border:0; border-radius: 4px; overflow:hidden;\"\n  title=\"Async/Await in ForEach Loop\"\n  allow=\"accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking\"\n  sandbox=\"allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts\"\n></iframe>\n<p><strong>Let's break down the different parts of our example:</strong></p>\n<ol>\n<li>dogUrls is an array of urls from the Dog Api (<a href=\"https://dog.ceo/dog-api/documentation/\">https://dog.ceo/dog-api/documentation/</a>)</li>\n<li>getDogImage() is our asynchronous function that takes in a url, fetches our dog image, and displays it on our webpage</li>\n<li>Once the image is displayed, we'll print \"displaying dog image\" to the console to indicate the end of an iteration</li>\n<li>fetchDogs() is our main function that uses a forEach loop that calls our asynchronous getDogImage() function</li>\n<li>Once the forEach loop completes, we'll print \"Done!\" to the console to indicate the end of all tasks</li>\n</ol>\n<p><strong>What we expect to happen is the following order:</strong></p>\n<ol>\n<li>For each iteration, we should take a url from the array and fetch the image from the Dog API</li>\n<li>Display the dog image in the webpage</li>\n<li>Print \"displaying dog image\" to the console</li>\n<li>Iterate three times</li>\n<li>print \"Done!\" to the console</li>\n</ol>\n<p>But what we see is that the \"Done!\" message is being printed to the console before all the tasks in our forEach loop.</p>\n<p>This is because forEach loops are synchronous by design, and won't wait for promises to resolve/complete.</p>\n<p>As a result, it is not possible to perform asynchronous tasks inside forEach loops, and we should only use this loop when dealing with synchronous tasks.</p>\n<h4>For-Of Loop</h4>\n<p>Now, let's take our previous example and use a for-of loop instead.</p>\n<pre><code class=\"language-js\">const dogUrls = [\n  'https://dog.ceo/api/breeds/image/random',\n  'https://dog.ceo/api/breed/hound/images/random',\n  'https://dog.ceo/api/breed/hound/afghan/images/random',\n]\n\nconst getDogImage = async url => {\n  const res = await fetch(url)\n  const data = await res.json()\n  document.write(`&#x3C;img src=${data.message} />`)\n  console.log('displaying dog image')\n}\n\nconst fetchDogs = async () => {\n  for (const url of dogUrls) {\n    await getDogImage(url)\n  }\n  console.log('Done!')\n}\n\nfetchDogs()\n</code></pre>\n<iframe\n  src=\"https://codesandbox.io/embed/asyncawait-in-for-of-loop-kvumb?fontsize=14&hidenavigation=1&theme=dark\"\n  style=\"width:100%; height:500px; margin-top: 15px; margin-bottom: 15px;border:0; border-radius: 4px; overflow:hidden;\"\n  title=\"Async/Await in For-Of Loop\"\n  allow=\"accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking\"\n  sandbox=\"allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts\"\n></iframe>\n<p>As we can see, all of the tasks execute in the order that we expected in the forEach example.</p>\n<p>Whenever we await getDogImage(), the for loop waits for all of the tasks in getDogImage() to complete before moving on to the next iteration.</p>\n<p>Also, the \"Done\" message is printed to the console only after all the iterations of the for loop completes.</p>\n<p>As a result, we should use for-of loops when we need to perform asynchronous tasks in a specific order.</p>\n<h4>Map Method</h4>\n<p>What if we don't care about the order that our asynchronous tasks execute?</p>\n<p>Also, what if we care about performance, and we want to fetch/display our dog images as fast as possible?</p>\n<pre><code class=\"language-js\">const dogUrls = [\n  'https://dog.ceo/api/breeds/image/random',\n  'https://dog.ceo/api/breed/hound/images/random',\n  'https://dog.ceo/api/breed/hound/afghan/images/random',\n]\n\nconst getDogImage = async url => {\n  const res = await fetch(url)\n  const data = await res.json()\n  document.write(`&#x3C;img src=${data.message} />`)\n  console.log('displaying dog image')\n}\n\nconst fetchDogs = async () => {\n  const promises = dogUrls.map(async url => await getDogImage(url))\n  await Promise.all(promises)\n  console.log('Done!')\n}\n\nfetchDogs()\n</code></pre>\n<iframe\n  src=\"https://codesandbox.io/embed/asyncawait-with-map-hhcx6?fontsize=14&hidenavigation=1&theme=dark\"\n  style=\"width:100%; height:500px; margin-top: 15px; margin-bottom: 15px;border:0; border-radius: 4px; overflow:hidden;\"\n  title=\"Async/Await with Map\"\n  allow=\"accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking\"\n  sandbox=\"allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts\"\n></iframe>\n<p>Instead of waiting for each iteration to complete before the next, we can create an array of promises and fire all of them off at the same time.</p>\n<p>The map method always returns an array, and in our case, an array of promises that call our getDogImage() function.</p>\n<p>We then pass our array of promises to Promise.all, which will execute all of the promises at once.</p>\n<p>Again, if your asynchronous tasks need to be executed in a specific order, then a for-of loop should be used.</p>\n<h4>Reduce Method</h4>\n<p>What if we want both order and speed?</p>\n<pre><code class=\"language-js\">const dogUrls = [\n  'https://dog.ceo/api/breeds/image/random',\n  'https://dog.ceo/api/breed/hound/images/random',\n  'https://dog.ceo/api/breed/hound/afghan/images/random',\n]\n\nconst getDogImage = async url => {\n  const res = await fetch(url)\n  const data = await res.json()\n  document.write(`&#x3C;img src=${data.message} />`)\n  console.log('displaying dog image')\n}\n\nconst fetchDogs = async () => {\n  await dogUrls.reduce(async (promise, url) => {\n    await getDogImage(url)\n    await promise\n  }, Promise.resolve())\n  console.log('Done!')\n}\n\nfetchDogs()\n</code></pre>\n<iframe\n  src=\"https://codesandbox.io/embed/asyncawait-with-reduce-geoqp?fontsize=14&hidenavigation=1&theme=dark\"\n  style=\"width:100%; height:500px; margin-top: 15px; margin-bottom: 15px;border:0; border-radius: 4px; overflow:hidden;\"\n  title=\"Async/Await with Reduce\"\n  allow=\"accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking\"\n  sandbox=\"allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts\"\n></iframe>\n<p>Reduce to the rescue!</p>\n<p>The reduce method is commonly used when we want tasks to happen in a specific order, and each task depends on the result of the previous task.</p>\n<p>In our example, we start our reduce method with Promise.resolve(), which is an already resolved Promise object.</p>\n<p>We then await our getDogImage() function first, before we await our accumulator (promise).</p>\n<p>This makes our reduce method performant, while executing our tasks sequentially.</p>"}}]}},"pageContext":{}},"staticQueryHashes":["1112540427","1408454471","2347443422","2404490943","2661970575","3904292974","399170485","648301173","850277546"]}