Array.of: Consistent Array Creation
The Array constructor in JavaScript can behave unexpectedly based on the number of arguments passed:
// Inconsistent behavior of Array constructor
const arr1 = Array(3); // [ , , ]
const arr2 = Array(); // []
const arr3 = Array(undefined); // [undefined]
const arr4 = Array(1, 2, 3); // [1, 2, 3]
This inconsistency can lead to confusion. The Array.of method provides a more predictable way to create arrays:
// Consistent behavior with Array.of
const arr1 = Array.of(3); // [3]
const arr2 = Array.of(); // []
const arr3 = Array.of(undefined); // [undefined]
const arr4 = Array.of(1, 2, 3); // [1, 2, 3]
Array.from: Converting Array-like Objects
Array.from is a versatile method that converts array-like objects, arguments, and NodeLists into actual arrays:
Converting Array-like Objects
const arrayLike = {
0: 'developer',
1: 'javascript',
length: 2
};
// Traditional way
const arr1 = [].slice.call(arrayLike); // ['developer', 'javascript']
// Using Array.from
const arr2 = Array.from(arrayLike); // ['developer', 'javascript']
Converting NodeLists
const domNodes = document.querySelectorAll('p');
const domArray = Array.from(domNodes); // [p, p, p, ...]
Converting Arguments
function logData() {
console.log('arguments', arguments);
console.log('Array.from arguments', Array.from(arguments));
}
logData('developer', 2023);
logData('javascript');
Using Mapping Function
const numbers = [1, 2, 3];
const doubled1 = numbers.map(num => num * 2); // [2, 4, 6]
const doubled2 = Array.from(numbers, num => num * 2); // [2, 4, 6]
includes: Simplified Value Checkign
Instead of complex conditional checks:
const value = 3;
if (value === 1 || value === 2 || value === 3 || value === 4) {
console.log(value); // 3
}
You can use includes for cleaner code:
const values = [1, 2, 3, 4];
const value = 3;
if (values.includes(value)) {
console.log(value); // 3
}
at(): Accessing Array Elements by Index
Traditionally, accessing the last element requires calculating the length:
const arr = [10, 20, 30, 40, 50];
const last = arr[arr.length - 1]; // 50
The at() method provides a more intuitive approach:
const arr = [10, 20, 30, 40, 50];
const last = arr.at(-1); // 50
const first = arr.at(0); // 10
flat(): Flattening Nested Arrays
The flat() method creates a new array with all sub-array eelments concatenated recursively:
const nested = [1, [2, [3, [4, [5]]]]];
const flat1 = nested.flat(); // [1, 2, [3, [4, [5]]]]
const flat2 = nested.flat(2); // [1, 2, 3, [4, [5]]]
const completelyFlat = nested.flat(Infinity); // [1, 2, 3, 4, 5]
findIndex(): Finding Element Position
findIndex returns the index of the first element that satisfies the testing function:
const data = [-5, 0, 15, 15, 30, 150];
const firstNegative = data.findIndex(num => num < 0); // 0
const firstPositive = data.findIndex(num => num >= 15); // 2