Key properties of Arrays and Objects in JavaScript That You May Not Be Aware Of
Javascript is a widely used programming language for building dynamic web applications. Arrays and objects are fundamental data structures in JavaScript that enable developers to manipulate and organize data more efficiently. In this post, we will uncover key properties of arrays and objects in Javascript that you may not be familiar with.
Arrays
Array.from():
TheArray.from()
method creates a new, shallow-copied array from an array-like or iterable object. This can be useful when you need to convert a collection of values into an array.
const str = 'hello hashnode';
const arr = Array.from(str); // ["h", "e", "l", "l", "o", " ", "h", "a", "s", "h", "n", "o", "d", "e"]
Array.of():
TheArray.of()
method creates a new array with a variable number of arguments passed to it. This can be useful when you need to create an array with a specific set of values.
Example:
const arr = Array.of(1, 2, 3); // [1, 2, 3]
Array.fill()
The Array.fill() method fills all the elements of an array with a static value. This can be useful when you need to initialize an array with a default value.
Example:
const arr = new Array(3).fill(0); // [0, 0, 0]
Array.prototype.filter():
The filter() method creates a new array with all elements that pass the test implemented by the provided function. This method does not modify the original array.
Example:
const arr = [1, 2, 3];
const filteredArr = arr.filter(num => num % 2 === 0); // Output: [2]
Array.flat():
The Array.flat() method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth. This can be useful when you need to flatten a nested array.
Example:
const arr = [1, 2, [3, 4, [5, 6]]];
const flattenedArr = arr.flat(2); // [1, 2, 3, 4, 5, 6]
- Spread:
The spread syntax allows you to expand an array into individual elements. This syntax is denoted by three dots (...), and it can be used in various scenarios such as combining arrays, passing arguments to functions, and creating copies of arrays.
Example:
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const combinedArr = [...arr1, ...arr2]; // Output: [1, 2, 3, 4, 5, 6]
Array.prototype.flatMap():
The flatMap() method is similar to map(), but it also flattens the result into a new array. This method can be useful when you want to map an array of values to an array of arrays and then flatten the resulting array.
Example:
const arr = [1, 2, 3];
const flatMappedArr = arr.flatMap(num => [num, num * 2]); // Output: [1, 2, 2, 4, 3, 6]
Array.prototype.reduce():
The reduce() method applies a function to each element of an array and reduces it to a single value. This method takes two parameters: a callback function and an optional initial value.
Example:
const arr = [1, 2, 3];
const sum = arr.reduce((acc, curr) => acc + curr, 0); // Output: 6
Array.prototype.findIndex():
The findIndex() method returns the index of the first element in an array that satisfies a given condition. This method takes a callback function as a parameter that tests each element in the array.
Example:
const arr = [1, 2, 3];
const index = arr.findIndex(num => num === 2); // Output: 1
Array.prototype.some():
The some() method tests whether at least one element in an array passes the test implemented by the provided function. This method returns a boolean value.
Example:
const arr = [1, 2, 3];
const hasEven = arr.some(num => num % 2 === 0); // Output: true
Objects
Object.entries():
It is a method in JavaScript that is used to extract the key-value pairs from an object and returns them as an array of arrays. Each sub-array contains two items: the key as the first element, and the value as the second element.
Example:
const obj = { foo: 'bar', baz: 42 };
const entries = Object.entries(obj); // [['foo', 'bar'], ['baz', 42]]
Object.keys():
It is a built-in method in JavaScript that is used to extract all the keys or property names from an object and return them in the form of an array.
Example:
const obj = { foo: 'bar', baz: 42 };
const keys = Object.keys(obj); // ['foo', 'baz']
Object.values():
It is a built-in method that allows you to extract all the values of an object and return them in an array.
Example:
const obj = { foo: 'bar', baz: 42 };
const values = Object.values(obj); // ['bar', 42]
Object.assign():
It is a method in JavaScript that is used to copy properties from one or more source objects to a target object. In simpler terms, it allows you to combine the properties of multiple objects into a single object.
Example:
const obj1 = { foo: 'bar' };
const obj2 = { baz: 42 };
const mergedObj = Object.assign({}, obj1, obj2); // { foo: 'bar', baz: 42 }
Object.getOwnPropertyDescriptors():
It is a method in JavaScript that allows you to get all the properties of an object and their descriptors.In simpler terms, it gives you a detailed report of an object's properties, such as whether they are writable, enumerable, or configurable.
Example:
const person = {
name: "Nitesh",
age: 30,
get fullName() {
return `${this.name} Singh`;
}
};
const descriptors = Object.getOwnPropertyDescriptors(person);
console.log(descriptors);
// Output:
{
name: {value: "Nitesh", writable: true, enumerable: true, configurable: true},
age: {value: 30, writable: true, enumerable: true, configurable: true},
fullName: {
get: [Function: get fullName],
set: undefined,
enumerable: true,
configurable: true
}
}
- Object destructuring:
is a feature in JavaScript that allows you to extract values from an object and assign them to variables in a more concise way. Instead of accessing each property of an object one by one, you can use object destructuring to create variables with the same names as the object's properties, and assign the values of those properties to those variables in a single line of code.
Example:
const person = { name: 'John', age: 30 };
const { name, age } = person;
console.log(name); // Output: John
Object.freeze():
It is a method that prevents an object from being modified. Once an object is frozen using this method, its properties cannot be added, removed or modified. Essentially, the object becomes immutable or read-only.
Example:
const obj = { foo: 'bar' };
Object.freeze(obj);
obj.foo = 'baz'; // This will not modify the object
console.log(obj.foo); // 'bar'
Object.seal():
It is a method that allows you to "seal" an object, preventing any new properties from being added to it, and marking all of its existing properties as non-configurable, which means they cannot be deleted or reconfigured. However, the values of the properties can still be modified.
Example:
const obj = { foo: 'bar' };
Object.seal(obj);
obj.baz = 42; // This will not add a new property
obj.foo = 'baz'; // This will modify an existing property
delete obj.foo; // This will not delete the property
console.log(obj); // { foo: 'baz' }
You can connect with me on LinkedIn and check out some of my work at GitHub