The push()
method in JavaScript is used to add one or more elements to the end of an array. This method modifies the original array and returns the new length of the array.
Example
Suppose you have the following array:
let fruits = ['apple', 'banana', 'orange'];
Now, you want to add a new element, 'kiwi', to the array. You can achieve this using the push()
method. Here's how you do it:
fruits.push('kiwi'); console.log(fruits);
Output
The array will now look like this:
['apple', 'banana', 'orange', 'kiwi']
Explanation
- Declare the array: We start with an array named
fruits
containing three elements: 'apple', 'banana', and 'orange'. - Use the
push()
method: We callfruits.push('kiwi')
to add'kiwi'
to the end of the array. - Log the updated array: Using
console.log(fruits)
, we print the updated array to the console.
The push()
method is simple yet powerful, allowing you to easily add new elements to your arrays in JavaScript.
No comments:
Post a Comment