Arrays and objects are two of the most important data types in JavaScript, and they have their own unique set of methods that can be used to manipulate and interact with them. In this article, we will explore some of the most commonly used array and object methods in JavaScript, and provide code examples to demonstrate their usage.
Array Methods:
- push() – The push() method adds one or more elements to the end of an array.
const arr = [1, 2, 3];
arr.push(4, 5);
console.log(arr); // Output: [1, 2, 3, 4, 5]
- pop() – The pop() method removes the last element from an array.
const arr = [1, 2, 3];
arr.pop();
console.log(arr); // Output: [1, 2]
- shift() – The shift() method removes the first element from an array.
const arr = [1, 2, 3];
arr.shift();
console.log(arr); // Output: [2, 3]
- unshift() – The unshift() method adds one or more elements to the beginning of an array.
const arr = [1, 2, 3];
arr.unshift(0);
console.log(arr); // Output: [0, 1, 2, 3]
- slice() – The slice() method returns a shallow copy of a portion of an array into a new array.
const arr = [1, 2, 3, 4, 5];
const newArr = arr.slice(2, 4);
console.log(newArr); // Output: [3, 4]
Object Methods:
- Object.keys() – The Object.keys() method returns an array of a given object’s own property names.
const obj = {name: 'John', age: 30, city: 'New York'};
const keys = Object.keys(obj);
console.log(keys); // Output: ['name', 'age', 'city']
- Object.values() – The Object.values() method returns an array of a given object’s own enumerable property values.
const obj = {name: 'John', age: 30, city: 'New York'};
const values = Object.values(obj);
console.log(values); // Output: ['John', 30, 'New York']
- Object.entries() – The Object.entries() method returns an array of a given object’s own enumerable property key-value pairs.
const obj = {name: 'John', age: 30, city: 'New York'};
const entries = Object.entries(obj);
console.log(entries); // Output: [['name', 'John'], ['age', 30], ['city', 'New York']]
- Object.assign() – The Object.assign() method copies the values of all enumerable properties from one or more source objects to a target object.
const obj1 = {name: 'John', age: 30};
const obj2 = {city: 'New York'};
const newObj = Object.assign(obj1, obj2);
console.log(newObj); // Output: {name: 'John', age: 30, city: 'New York'}
In conclusion, JavaScript provides a wide range of array and object methods that can be used to manipulate and interact with data. By understanding the different types of methods and how they can be used, you can write more efficient and effective code. for more array methods you can visit this page link.