. Advertisement .
. Advertisement .
After discussing the reason for adding multiple values to an array, Let’s come to the methods that can help us do this
Using Array.push() Method
As its name suggests, it pushes multiple values to an array with the ‘arr.push’. with the
push() method, we can add one or more values to the end of an array. Moreover, it takes one or more arguments along with adding the values to an array’s end. Have look at the code
const programming_language = ['Python', 'C++']; programming_language.push('Java', 'Ruby', 'PHP'); console.log(programming_language);
['Python', 'C++', 'Java', 'Ruby', 'PHP']
The content of the original array has changed and it returned the new length of an array.
Using Spread Syntax
This is another method to push multiple values to an array. The syntax is ‘
birds = […birds , ‘Owl’, ‘Falcon’, ‘Pigeon’];’. With the spread syntax method, you can unpack the value of an original array no matter how many values it has. Let’s see an example
let birds = ['Eagle', 'Swan']; birds = [...birds, 'Owl', 'Falcon', 'Pigeon']; console.log(birds);
['Eagle', 'Swan', 'Owl', 'Falcon', 'Pigeon']
Here, the ‘let’ keyword is used so that you can declare the ‘birds’ variable. If a variable is declared using ‘const’, it didn’t allow you to reassign it.
Using splice() Method
This one is also used to push multiple values to an array. With the
splice() method, we are allowed to add the values to the end of an array. This is how you can code
const animals = ['Buffalo', 'Tiger', 'Lion']; animals.splice(animals.length, 0, 'Baboon', 'Hyena', 'Elephant'); console.log(animals);
['Buffalo', 'Tiger', 'Lion', 'Baboon', 'Hyena', 'Elephant']
As we want to add the element at the end, we pass the length of an array as the start index.
This method gives the same result as the above-mentioned methods.
Drop a message if you need assistance. Your feedback is appreciated!
Leave a comment