Which of the following methods can be used to add elements to the end ...
The 'push()' method is used to add elements to the end of an array.
View all questions of this test
Which of the following methods can be used to add elements to the end ...
push() method in JavaScript
The push() method in JavaScript is used to add one or more elements to the end of an array. It modifies the original array and returns the new length of the array.
How to use push() method:
- To add a single element:
```
let arr = [1, 2, 3];
arr.push(4);
// arr is now [1, 2, 3, 4]
```
- To add multiple elements:
```
let arr = [1, 2, 3];
arr.push(4, 5);
// arr is now [1, 2, 3, 4, 5]
```
Benefits of using push() method:
- It is a simple and straightforward method to add elements to the end of an array.
- It can be used to add one or multiple elements at once, making it versatile.
Example:
```
let arr = [1, 2, 3];
arr.push(4);
console.log(arr); // Output: [1, 2, 3, 4]
```
Using the push() method is a common practice in JavaScript when you need to append elements to an existing array without altering the existing elements' positions.