JavaScript Array push()
The push()
method is a built-in JavaScript method used to add one or more elements to the end of an array.
Syntax
array.push(element1, ..., elementN);
array
: The array to which elements will be added.element1, ..., elementN
: Elements to add to the end of the array.
Example
let fruits = ['apple', 'banana', 'orange'];
fruits.push('grape', 'kiwi');
console.log(fruits);
Output
['apple', 'banana', 'orange', 'grape', 'kiwi']
Explanation
- The
push()
method appends new elements to the end of the array. - In the example, 'grape' and 'kiwi' are added to the
fruits
array.
Use
The push()
method is commonly used when you want to add one or more elements to the end of an array dynamically. It's useful for building arrays dynamically based on user input, API responses, or any other data source.
Important Points
- The
push()
method modifies the original array and returns the new length of the array. - You can push multiple elements in a single call, separated by commas.
- The order of elements pushed to the array is maintained.
let numbers = [1, 2, 3];
let moreNumbers = [4, 5, 6];
numbers.push(...moreNumbers);
console.log(numbers); // [1, 2, 3, 4, 5, 6]
Summary
The push()
method is a convenient way to add elements to the end of an array in JavaScript. It provides a simple and efficient means of dynamically updating arrays, making it a fundamental method when working with arrays in JavaScript. Keep in mind its behavior of modifying the original array when using it in your code.