tutorial

How to Convert a Map to an Object in JavaScript

In this article, we’ll be looking at some ways to easily convert a Map to an object in JavaScript.

1. Object.fromEntries()

To convert a Map to an object, we can use the Object.fromEntries() method, passing the Map as an argument. For example:

const map = new Map([
  ['user1', 'John'],
  ['user2', 'Kate'],
  ['user3', 'Peter'],
]);

const obj = Object.fromEntries(map);

// { user1: 'John', user2: 'Kate', user3: 'Peter' }
console.log(obj);

Note: Object.fromEntries() can transform any list of key-value pairs into an object. For example, it can directly transform the array of key-value pairs that we passed to the Map() constructor:

const arr = [
  ['user1', 'John'],
  ['user2', 'Kate'],
  ['user3', 'Peter'],
];
const obj = Object.fromEntries(arr);

// { user1: 'John', user2: 'Kate', user3: 'Peter' }
console.log(obj);

2. Iterate over Map and Create Keys in Object

Another way to convert a Map to an object is iterate over the entries of the Map and create a new key on the object for each of them. For each entry, we set the key name and value to the entry name and value respectively. For example:

const map = new Map([
  ['user1', 'John'],
  ['user2', 'Kate'],
  ['user3', 'Peter'],
]);

const obj = {};
map.forEach((value, key) => {
  obj[key] = value;
});

// { user1: 'John', user2: 'Kate', user3: 'Peter' }
console.log(obj);

Note: We can also iterate over the Map with the for...of loop:

const map = new Map([
  ['user1', 'John'],
  ['user2', 'Kate'],
  ['user3', 'Peter'],
]);

const obj = {};
for (const [key, value] of map) {
  obj[key] = value;
}

// { user1: 'John', user2: 'Kate', user3: 'Peter' }
console.log(obj);

How to Use the Vuetify Parallax Component

Parallax scrolling is a visual effect used on web pages where the background content moves at a slower rate than the foreground content. In this article, we’re going to learn how to use the parallax component from Vuetify to create the parallax scrolling effect with background images.

The Vuetify Parallax Component (v-parallax)

We use v-parallax to create a parallax component. It has a src prop for specifying the URL of the image to use for the background.

<template>
  <v-app>
    <div style="height: 1200px">
      <v-parallax
        src="https://picsum.photos/1920/1080?random"
      >
      </v-parallax>
    </div>
  </v-app>
</template>
Using the Vuetify parallax component.

Parallax Content

We can include content in a parallax by making it a child of the v-parallax. This is useful for creating a hero image. For example:

<template>
  <v-app>
    <div style="height: 1200px">
      <v-parallax
        src="https://picsum.photos/1920/1080?random"
      >
        <div class="white black--text pa-4">
          Lorem ipsum dolor sit amet consectetur adipisicing
          elit. Quasi repellendus optio doloremque illo
          fugiat iure possimus dolorem aspernatur, officiis
          laudantium iste debitis officia asperiores
          voluptas, architecto molestias minima velit
          nesciunt?
        </div>
      </v-parallax>
    </div>
  </v-app>
</template>
Including content in the parallax component.

Parallax Height

We can customize the height of the parallax component with the height prop. For example:

<template>
  <v-app>
    <div style="height: 1200px">
      <v-parallax
        src="https://picsum.photos/1920/1080?random"
        height="400"
      >
        <div class="white black--text pa-4">
          Lorem ipsum dolor sit amet consectetur adipisicing
          elit. Quasi repellendus optio doloremque illo
          fugiat iure possimus dolorem aspernatur, officiis
          laudantium iste debitis officia asperiores
          voluptas, architecto molestias minima velit
          nesciunt?
        </div>
      </v-parallax>
    </div>
  </v-app>
</template>
Customizing the height of the Vuetify parallax component.

How to Convert a String to a Boolean in JavaScript

Let’s look at some ways to convert a string to a boolean in JavaScript.

1. Compare String with true

To convert a string to a boolean, we can use the strict equality operator to compare the string with the true string. For example:

const str1 = 'true';
const str2 = 'false';

const bool1 = str1 === 'true';
const bool2 = str2 === 'true';

console.log(bool1); // true
console.log(bool2); // false

Note: Use toLowerCase() to ignore the casing of the string before the conversion:

const str1 = 'TRUE';

const bool1 = str1.toLowerCase() === 'true';

console.log(bool1); // true

Note: Using the Boolean constructor to convert the string will result in true if the string is not falsy. Empty strings are the only falsy strings. All other strings are truthy.

const str1 = 'true';
const str2 = 'false';
const str3 = '';
const str4 = 'a';

const bool1 = Boolean(str1);
const bool2 = Boolean(str2);
const bool3 = Boolean(str3);
const bool4 = Boolean(str4);

console.log(bool1); // true
console.log(bool2); // true
console.log(bool3); // false
console.log(bool4); // true

2. JSON.parse()

We can also convert a string to a boolean in JavaScript with the JSON.parse() method. For example:

const str1 = 'true';
const str2 = 'false';

const bool1 = JSON.parse(str1);
const bool2 = JSON.parse(str2);

console.log(bool1); // true
console.log(bool2); // false

Note: Attempting to parse the true or false string, when it is not all lowercase, will cause an error:

const str1 = 'TRUe';

const bool1 = JSON.parse(str1); // throws SyntaxError

How to Convert a Map to an Array in JavaScript

In this article, we’ll be learning different ways to convert a Map object to an array of objects in JavaScript.

1. Array from() Method

To convert a Map to an array, we can use the static Array.from() method, passing the Map as the first argument, and a map function to transform the Map entries as a second argument.

const map = new Map();
map.set('user1', 'John');
map.set('user2', 'Kate');
map.set('user3', 'Peter');

const arr = Array.from(map, function (entry) {
  return { key: entry[0], value: entry[1] };
});

/**
  [
    { key: 'user1', value: 'John' },
    { key: 'user2', value: 'Kate' },
    { key: 'user3', value: 'Peter' }
  ]
*/
console.log(arr);

Note: We can use array destructuring and an arrow function to shorten the code above:

const arr = Array.from(map, ([key, value]) => ({
  key,
  value,
}));

Note: To convert the Map to an array of key-value objects:

const arr = Array.from(map, ([key, value]) => ({
  [key]: value,
}));

// [ { user1: 'John' }, { user2: 'Kate' }, { user3: 'Peter' } ]
console.log(arr);

Note: If we don’t pass the map function as an argument, Array.from() will return an array of key-value pairs, one pair for each Map entry. For example:

const map = new Map();
map.set('user1', 'John');
map.set('user2', 'Kate');
map.set('user3', 'Peter');

const arr = Array.from(map);

// [ [ 'user1', 'John' ], [ 'user2', 'Kate' ], [ 'user3', 'Peter' ] ]
console.log(arr);

This means we can use the Array map() method to transform this array into an array of objects:

const map = new Map();
map.set('user1', 'John');
map.set('user2', 'Kate');
map.set('user3', 'Peter');

const arr = Array.from(map).map(([key, value]) => ({
  key,
  value,
}));

/**
  [
    { key: 'user1', value: 'John' },
    { key: 'user2', value: 'Kate' },
    { key: 'user3', value: 'Peter' }
  ]
*/
console.log(arr);

2. Spread Operator and Array map()

Using the JavaScript spread operator (...) on a Map will unpack its entries into an array of key-value pairs, just like Array.from() does when it doesn’t receive a callback. For example:

const map = new Map();
map.set('user1', 'John');
map.set('user2', 'Kate');
map.set('user3', 'Peter');

const arr = [...map];

// [ [ 'user1', 'John' ], [ 'user2', 'Kate' ], [ 'user3', 'Peter' ] ]
console.log(arr);

This means we can also convert a Map to an array of objects by combining the spread operator with the Array map() method:

const map = new Map();
map.set('user1', 'John');
map.set('user2', 'Kate');
map.set('user3', 'Peter');

const arr = [...map].map(([key, value]) => ({
  key,
  value,
}));

/**
  [
    { key: 'user1', value: 'John' },
    { key: 'user2', value: 'Kate' },
    { key: 'user3', value: 'Peter' }
  ]
*/
console.log(arr);

3. Iterating over Map and Adding Elements to Array

Another way to convert a Map to an array is to iterate over each Map entry, create an object with the entry, and add the object to the resulting array. For example, we can iterate over the Map with the Map forEach() method, and add array elements with the Array push() method.

const map = new Map();
map.set('user1', 'John');
map.set('user2', 'Kate');
map.set('user3', 'Peter');

const arr = [];
map.forEach((value, key) => arr.push({ key, value }));

/**
  [
    { key: 'user1', value: 'John' },
    { key: 'user2', value: 'Kate' },
    { key: 'user3', value: 'Peter' }
  ]
*/
console.log(arr);

Alternatively, we can use the for...of loop to iterate over the Map:

const map = new Map();
map.set('user1', 'John');
map.set('user2', 'Kate');
map.set('user3', 'Peter');

const arr = [];
for (const [key, value] of map) {
  arr.push({ key, value });
}

/**
  [
    { key: 'user1', value: 'John' },
    { key: 'user2', value: 'Kate' },
    { key: 'user3', value: 'Peter' }
  ]
*/
console.log(arr);

How to Convert an Array to a Map in JavaScript

In this article, we’ll be looking at two ways to quickly convert an array of objects to a Map object in JavaScript.

1. Map() Constructor and Array map()

To convert an array of objects to a map, we can use the Array map() method to create an array of key-value pairs, and then pass the resulting array to a Map() constructor to create a Map object.

const arr = [
  { key: 'user1', value: 'John' },
  { key: 'user2', value: 'Kate' },
  { key: 'user3', value: 'Peter' },
];
const map = new Map(arr.map((obj) => [obj.key, obj.value]));

// Map(3) { 'user1' => 'John', 'user2' => 'Kate', 'user3' => 'Peter' }
console.log(map);

In the callback passed to the map() method, we return an array containing the key and the value for each object. This will result in an array of key-value pairs:

// [ [ 'user1', 'John' ], [ 'user2', 'Kate' ], [ 'user3', 'Peter' ] ]
console.log(arr.map((obj) => [obj.key, obj.value]));

The Map constructor can take an array of this form as an argument to create a Map object.

2. Map set() and Array forEach()

Another way to convert an array of objects to a map is with the Array forEach() method. First, we create a new Map object. Then, we add entries for all the array elements to the Map, by calling the Map set() method in the callback passed to forEach(). Here’s an example:

const arr = [
  { key: 'user1', value: 'John' },
  { key: 'user2', value: 'Kate' },
  { key: 'user3', value: 'Peter' },
];

const map = new Map();
arr.forEach((obj) => {
  map.set(obj.key, obj.value);
});

// Map(3) { 'user1' => 'John', 'user2' => 'Kate', 'user3' => 'Peter' }
console.log(map);

What Does Double Negation (!!) Do in JavaScript?

You might have seen the double negation operator (!!) used in some JavaScript code. What is its function?

Double negation converts truthy values to the true Boolean and falsy values to the false Boolean. It is not a distinct JavaScript operator, but really just a sequence of two negations. Apply the first negation results in false for a truthy value, and true for a falsy value. The second negation will then operate on the normal Boolean value that results.

Here is an example:

!!2; // -> true
!!''; // -> false
!!NaN; // -> false
!!'word'; // -> true
!!undefined; // -> false

Note: If you need to convert a value to a Boolean, it’s better to be explicit and use the Boolean constructor instead of double negation. We could have more clearly written the above example as:

Boolean(2); // -> true
Boolean(''); // -> false
Boolean(NaN); // -> false
Boolean('word'); // -> true
Boolean(undefined); // -> false

Note: We don’t need to convert a value to a Boolean to check if it is truthy or falsy in ternary operators or if statements. We can use the value directly:

if (2) console.log('executed');
if ('') console.log('NOT executed');
if (NaN) console.log('NOT executed');
if ('word') console.log('executed');
if (undefined) console.log('NOT executed');

How to Reverse an Array without Modifying in JavaScript

Let’s look at some ways to reverse the order of an array without mutating the original in JavaScript.

1. slice() and reverse()

To reverse an array without modifying the original, we can clone the array with the slice() method and reverse the clone with the reverse() method.

For example:

const arr = [1, 2, 3];
const reversed = arr.slice().reverse();

console.log(reversed); // [ 3, 2, 1 ]
console.log(arr); // [ 1, 2, 3 ]

The reverse() method reverses an array in place, so we call the slice() method on the array with no arguments, to return a copy of it.

2. Spread Operator and reverse()

In ES6+, we could also clone the array by using the spread syntax to unpack its elements into a new array, before calling reverse():

const arr = [1, 2, 3];
const reversed = [...arr].reverse();

console.log(reversed); // [ 3, 2, 1 ]
console.log(arr); // [ 1, 2, 3 ]

3. Reverse for loop

We can also reverse an array without modifying it by creating a reverse for loop, and in each iteration, adding the array element whose index is the current value of the loop counter to a new array. The new array will contain all the elements reversed at the end of the loop.

const arr = [1, 2, 3];
const reversed = [];
for (let i = arr.length - 1; i >= 0; i--) {
  reversed.push(arr[i]);
}

console.log(arr); // [ 1, 2, 3 ]
console.log(reversed); // [ 3, 2, 1]

How to Get the Length of an Object in JavaScript

Let’s look at some ways to quickly get the length of an object in JavaScript.

1. The Object.keys() Method

To get the length of an object, we can pass the object to the static Object keys() method, and access the length property of the resulting array. For example:

const obj = {
  color: 'red',
  topSpeed: 120,
  age: 2,
};

const objectLength = Object.keys(obj).length;
console.log(objectLength); // 3

Note: Object.keys() only returns the enumerable properties found directly on the object. If you want to include non-enumerable properties in the count, use Object.getOwnPropertyNames() instead:

const obj = {
  color: 'red',
  topSpeed: 120,
  age: 2,
};
Object.defineProperty(obj, 'acceleration', {
  enumerable: false,
  value: 5,
});

console.log(Object.keys(obj).length); // 3
console.log(Object.getOwnPropertyNames(obj).length); // 4

Note: Object.keys() and Object.getOwnPropertyNames() don’t work for symbolic properties. To count symbolic properties, use Object.getOwnPropertySymbols():

const obj = {
  color: 'red',
  speed: 120,
  age: 2,
  [Symbol('acceleration')]: 5,
  [Symbol('weight')]: 1000,
};

console.log(Object.keys(obj).length); // 3
console.log(Object.getOwnPropertyNames(obj).length); // 3
console.log(Object.getOwnPropertySymbols(obj).length); // 2

2. for..in Loop and hasOwnProperty()

Another method to get the length of an object is to use the JavaScript for...in loop to iterate over the properties of the object and increment a variable in each iteration. The variable will contain the object length after the loop.

const obj = {
  color: 'red',
  topSpeed: 120,
  age: 2,
};

let objectLength = 0;
for (let key in obj) {
  if (obj.hasOwnProperty(key)) objectLength++;
}
console.log(objectLength); // 3

Because the for...in loop also iterates over the inherited properties of the object, we use the hasOwnProperty() method to ensure that the property exists directly on the object before incrementing the variable.

How to Concatenate Strings with a Separator in JavaScript

In this article, we’ll be learning how to concatenate a bunch of strings in JavaScript with a separator of our choice, like a comma or hyphen.

The Array join() Method

To concatenate strings with a separator, we can create an array containing the strings and call the join() method, passing the separator as an argument. The join() method will return a string containing the array elements joined with the separator. For example:

const str1 = 'html';
const str2 = 'css';
const str3 = 'javascript';

const spaceSeparated = [str1, str2, str3].join(' ');
console.log(spaceSeparated); // html css javascript

const commaSeparated = [str1, str2, str3].join(',');
console.log(commaSeparated); // html,css,javascript

Multi-Character Separator

The separator doesn’t have to be a single character, we can pass strings with multiple characters, like words:

const str1 = 'html';
const str2 = 'css';
const str3 = 'javascript';

const andSeparated = [str1, str2, str3].join(' and ');
console.log(andSeparated); // html and css and javascript

If we call the join() method on the string array without passing arguments, the strings will be separated with a comma:

const str1 = 'html';
const str2 = 'css';
const str3 = 'javascript';

const withoutSeparator = [str1, str2, str3].join();
console.log(withoutSeparator); // html,css,javascript

While this works, it’s better to be explicit by passing the comma as an argument if you need comma separation, as not everyone is aware of the default behaviour.

Note: The join() method will return an empty string if we call it on an empty array. For example:

console.log([].join(',')); // ''

Note: Elements like undefined, null, or empty array values get converted to an empty string during the join:

const joined = [null, 'html', undefined, 'css', []].join();
console.log(joined); // ,html,,css,

Event target vs currentTarget in JavaScript: The Important Difference

Summary: target is the innermost element in the DOM that triggered the event, while currentTarget is the element that the event listener is attached to.

We use the HTML DOM Event object to get more information about an event and carry out certain actions related to it. Events like click, mousedown, and keyup all have different types of Events associated with them. Two key Event properties are target and currentTarget. These properties are somewhat similar and sometimes return the same object, but it’s important that we understand the difference between them so we know which one is better suited for different cases.

An event that occurs on a DOM element bubbles if it is triggered for every single ancestor of the element in the DOM tree up until the root element. When accessing an Event in an event listener, the target property returns the innermost element in the DOM that triggered the event (from which bubbling starts). The currentTarget property, however, will return the element to which the event listener is attached.

Let’s use a simple example to illustrate this. We’ll have three nested div elements that all listen for the click event with the same handler function.

<!DOCTYPE html>
<html>
  <head>
    <style>
      #div1 {
        height: 200px;
        width: 200px;
        background-color: red;
      }
      #div2 {
        height: 150px;
        width: 150px;
        background-color: green;
      }
      #div3 {
        height: 100px;
        width: 100px;
        background-color: blue;
      }
    </style>
  </head>
  <body>
    <div id="div1" onclick="handleClick(event)">
      <div id="div2" onclick="handleClick(event)">
        <div id="div3" onclick="handleClick(event)"></div>
      </div>
    </div>
    <script>
      function handleClick(event) {
        console.log(
          `target: ${event.target.id}, currentTarget: ${event.currentTarget.id}`
        );
      }
    </script>
  </body>
</html>
Nested HTML div elements.

Well, what happens when you click the blue and innermost div? You get this output in your console:

target: div3, currentTarget: div3
target: div3, currentTarget: div2
target: div3, currentTarget: div1

Clicking the div triggered the event which invoke the handler for div3. The click event bubbles, so it was propagated to the two outer divs. As expected, the target stayed the same in all the listeners but currentTarget was different in each listener as they were attached to elements at different levels of the DOM hierarchy.