The easiest way to add a new element to an array is using the push()
method:
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Lemon"); // adds a new element (Lemon) to fruits
fruits.push("Lemon"); // adds a new element (Lemon) to fruits
New element can also be added to an array using the length
property:
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits[fruits.length] = "Lemon"; // adds a new element (Lemon) to fruits
fruits[fruits.length] = "Lemon"; // adds a new element (Lemon) to fruits
Example
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits[6] = "Lemon"; // adds a new element (Lemon) to fruits
fruits[6] = "Lemon"; // adds a new element (Lemon) to fruits
Practice Excercise Practice now