JavaScript Array push
Method (Live Playground)
The push
method in JavaScript allows you to add one or more elements to the end of an array.
Here's a simple example:
let fruits = ['apple', 'banana', 'mango'];
fruits.push('kiwi');
console.log(fruits);
// Expected output: ["apple", "banana", "mango", "kiwi"]
In this example, the push
method adds "kiwi" to the end of the fruits
array. The new length of the array is returned by the push
method.
The push
method can also accept multiple arguments to add multiple elements:
let fruits = ['apple', 'banana', 'mango'];
fruits.push('kiwi', 'orange');
console.log(fruits);
// Expected output: ["apple", "banana", "mango", "kiwi", "orange"]
Here, "kiwi" and "orange" are added to the end of the fruits
array. Remember, the push
method modifies the original array.
To summarize, the push
method in JavaScript is a very useful method for adding elements to the end of an array. By using push
, you can dynamically increase the size of an array, making it a powerful tool in your JavaScript arsenal.
Remember to practice using push
with different arrays and arguments to better understand how it works!