. Advertisement .
..3..
. Advertisement .
..4..
An array plays an important role when it comes to JavaScript programming. None of the programmers can work on projects without using an array. Whether you are a beginner or trying to work on it, you are here to know the process to push multiple values to an array in JavaScript. It is a type of project that you may need help with. JavaScript is a vast language with multiple projects that can be tried if you are a beginner to learn the language fast.
An array is known as the ordered element’s collection. When working with an array, we often have to push multiple values to an array to reduce the long codes short as adding separate values to an array makes the coding not only long but also confusing. So, we use code to push multiple values to an array in JavaScript to have short and quick work.
Check out how can you push multiple values to an array in JavaScript
How to push multiple values to an array in JavaScript
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);
Output:
['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);
Output:
['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);
Output:
['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.
Conclusion
With the best solutions discussed to push multiple values to an array in JavaScript, I hope you can code well.
Drop a message if you need assistance. Your feedback is appreciated!
Leave a comment