javascript

How to Convert an Array to a String Without Commas in JavaScript

To convert an array to a string without commas in JavaScript, call the join() method on the array, passing an empty string ('') as an argument:

const arr = ['coffee', 'milk', 'tea'];

const withoutCommas = arr.join('');
console.log(withoutCommas); // coffeemilktea

The Array join() method returns a string containing each array element concatenated with the specified separator. If no separator is passed as an argument, it will join the array elements with commas:

const arr = ['coffee', 'milk', 'tea'];

const str = arr.join();
console.log(str); // coffee,milk,tea

We can specify other separators apart from an empty string, like hyphens and slashes:

const arr = ['coffee', 'milk', 'tea'];

const withHypens = arr.join('-');
console.log(withHypens); // coffee-milk-tea

const withSlashes = arr.join('/');
console.log(withSlashes); // coffee/milk/tea

const withSpaces = arr.join(' ');
console.log(withSpaces); // coffee milk tea

A separator can also contain multiple characters:

const arr = ['coffee', 'milk', 'tea'];

const withAnd = arr.join(' and ');
console.log(withAnd); // coffee and milk and tea

const withOr = arr.join(' or ');
console.log(withOr); // coffee or milk or tea

If an element in the array is undefined, null, or an empty array ([]), it will be converted to an empty string ('') before concatenation with the separator. For example:

const arr = ['coffee', null, 'milk', []];

const withComma = arr.join(',');
console.log(withComma); // coffee,,milk,

const withHyphen = arr.join('-');
console.log(withHyphen); // coffee--milk-

How to Convert a Set to a String in JavaScript

To convert a set to a string in JavaScript, call the Array.from() method with the Set as an argument, then call the join() method on the resulting array. For example:

const set = new Set(['x', 'y', 'z']);

const str1 = Array.from(set).join(' ');
console.log(str1); // x y z

const str2 = Array.from(set).join(',');
console.log(str2); // x,y,z

The Array.from() method converts an array-like object like a Set into an array:

const set = new Set(['x', 'y', 'z']);

console.log(Array.from(set)); // [ 'x', 'y', 'z' ]

After the conversion, we can call the join() method on the array. join() returns a string containing the elements of an array concatenated with the specified separator:

console.log(['x', 'y', 'z'].join('-')); // x-y-z

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

Note: We can also use the spread syntax (...) to convert a Set to an array:

const set = new Set(['x', 'y', 'z']);

const str1 = [...set].join(' ');
console.log(str1); // x y z

const str2 = [...set].join(',');
console.log(str2); // x,y,z

The spread syntax unpacks the values of the Set into a new array that we call join() on to get the string.

How to Rename an Object Key in JavaScript

To rename an object key in JavaScript, assign the value of the old key property to a new property with the new key, then delete the old key property.

const obj = { oldKey: 'value' };

obj['newKey'] = obj['oldKey'];
delete obj['oldKey'];

console.log(obj); // { newKey: 'value' }

In this example, we create the new property by direct assignment to the object indexed with the new key. We delete the old key property with the delete operator.

Note: We can also use the Object.assign() method to create a new property in the object:

const obj = { oldKey: 'value' };

Object.assign(obj, { newKey: obj.oldKey })['oldKey'];
delete obj['oldKey'];

console.log(obj); // { newKey: 'value' }

This allows us to rename the object key in a single statement:

const obj = { oldKey: 'value' };

delete Object.assign(obj, { newKey: obj.oldKey })['oldKey'];

console.log(obj); // { newKey: 'value' }

The first argument passed to Object.assign() is the target object that the properties of the sources are applied to. The rest arguments are one or more source objects that contain the properties to apply to the target.

Note: To ensure that the new key property behaves identically to the old key property, use Object.defineProperty() and Object.getOwnPropertyDescriptor() to create the new property with the same descriptor as the old key property before deleting it. For example:

const obj = { oldKey: 'value' };

Object.defineProperty(
  obj,
  'newKey',
  Object.getOwnPropertyDescriptor(obj, 'oldKey')
);
delete obj['oldKey'];

console.log(obj); // { newKey: 'value' }

Now the new key property will retain certain characteristics of the old key property, such as enumerability and writability.

How to Convert an Object to a Map in JavaScript

Let’s look at some ways to quickly convert an object to a Map in JavaScript.

1. Object.entries() in Map() Constructor

To convert an object to a Map, we can call the Object.entries() method with the object as an argument, and pass the result to the Map() constructor to create the Map object. For example:

const obj = {
  user1: 'John',
  user2: 'Kate',
  user3: 'Peter',
};

const map = new Map(Object.entries(obj));

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

Note: Object.entries() transforms an object into an array of key-value pairs that the Map() constructor uses to create the Map elements.

const obj = {
  user1: 'John',
  user2: 'Kate',
  user3: 'Peter',
};

const entries = Object.entries(obj);

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

We can generate the array without using Object.entries(), like this:

const obj = {
  user1: 'John',
  user2: 'Kate',
  user3: 'Peter',
};

const entries = Object.keys(obj).map((key) => [
  key,
  obj[key],
]);

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

2. Iterate over Object Keys and Add Elements to Map

We can also convert an object to a Map by iterating through the object keys, using the Map set() method to add an element to the resulting Map for each key. We can obtain the keys with the Object.keys() method and loop through them with the forEach() method. For example:

const obj = {
  user1: 'John',
  user2: 'Kate',
  user3: 'Peter',
};

const map = new Map();
Object.keys(obj).forEach((key) => {
  map.set(key, obj[key]);
});

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

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');