To add elements of an array

Asked 2 years ago, Updated 2 years ago, 41 views

How do I add elements to an array in JavaScript?

array javascript

2022-09-21 18:19

1 Answers

Call the .push() method.

// Initialize array 
var arr = [
    "Hi",
    "Hello",
    "Bonjour"
];

// Adding a New Element to an Array 
arr.push("Hola");

// When adding multiple elements to an array 
arr.push("Salut", "Hey");

// Output all elements of an array 
for (var i = 0; i < arr.length; i++) {
    console.log(arr[i]);
}
Hi
Hello
Bonjour
Hola 
Salut
Hey

If you did the same, it would print out like this.


2022-09-21 18:19

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.