The push() method allows you to add one or more elements to the end of an array. Here’s an example:
let fruits = ['apple', 'banana', 'orange']; fruits.push('grape');
After executing this code, the
fruits array will contain ‘grape’ as a new element.
The unshift() method adds one or more elements to the beginning of an array. Consider this example:
let fruits = ['apple', 'banana', 'orange']; fruits.unshift('kiwi');
Now, the fruits array will have ‘kiwi’ at the beginning.
Removing Elements from an Array
In addition to adding elements, you can also remove elements from an array using various methods:
The pop() method removes the last element from an array and returns it. Here’s how you can use it:
let fruits = ['apple', 'banana', 'orange']; let removedFruit = fruits.pop();
After executing this code,
removedFruit will contain ‘orange,’ and the
fruits array will no longer have ‘orange’ as an element.
The shift() method removes the first element from an array and returns it. For example:
let fruits = ['apple', 'banana', 'orange']; let removedFruit = fruits.shift();
After running this code,
removedFruit will contain ‘apple,’ and ‘apple’ will be removed from the
let fruits = ['apple', 'banana']; let vegetables = ['carrot', 'broccoli']; let combined = fruits.concat(vegetables);
In this example, the combined array will contain all elements from both fruits and vegetables.
Modifying Array Elements
You can access array elements using their indices. Remember that array indices start from 0. For instance:
let fruits = ['apple', 'banana', 'orange']; let secondFruit = fruits; // 'banana'
secondFruit will contain ‘banana,’ which is the element at index 1.
To update an element at a specific index, simply assign a new value to it. For example:
let fruits = ['apple', 'banana', 'orange']; fruits = 'cherry'; // Updates 'banana' to 'cherry'
fruits array will contain ‘cherry’ instead of ‘banana’ at index 1.
The push() method adds elements to the end of an array, while unshift() adds elements to the beginning.
You can use methods like splice() or filter the array based on your criteria to remove specific elements.