Categories
JavaScript Answers

How to short circuit Array.forEach like calling break with JavaScript?

To short circuit Array.forEach like calling break with JavaScript, we use a for-of loop.

For instance, we write

const arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
for (const el of arr) {
  console.log(el);
  if (el === 5) {
    break;
  }
}

to use a for-of loop to loop through the arr array.

And we use break to stop the loop when el is 5.

el is the element we’re looping through.

Categories
JavaScript Answers

How to add new array elements at the beginning of an array in JavaScript?

To add new array elements at the beginning of an array in JavaScript, we use the unshift method.

For instance, we write

const a = [23, 45, 12, 67];
a.unshift(11);
console.log(a);

to call a.unshift with 11 to prepend 11 to the a array.

Categories
JavaScript Answers

How to empty an array in JavaScript?

To empty an array in JavaScript, we set it to an empty array.

For instance, we write

let arr1 = ["a", "b", "c", "d", "e", "f"];
arr1 = [];

to assign the arr1 array to an empty array to empty the array.

Categories
JavaScript Answers

How to get all unique values in a JavaScript array?

To get all unique values in a JavaScript array, we can convert it to a set and back.

For instance, we write

const myArray = ["a", 1, "a", 2, "1"];
const unique = [...new Set(myArray)];
console.log(unique);

to convert the myArray array to a set with the Set constructor.

Then we convert the set back to an array without duplicate values with the spread operator.

Categories
JavaScript Answers

How to append something to an array with JavaScript?

To append something to an array with JavaScript, we call the array push method.

For instance, we write

const arr = ["Hi", "Hello", "Bonjour"];
arr.push("Hola");

console.log(arr);

to call arr.push to append 'Hola' as the last entry of arr in place.