Appending Elements to an Array
Now we will start looking at commands that make working with arrays easier.
We will start with the push()
command, which adds an element to the end of an array.
We will show how it is used with an example and then explain the notation:
const carBrands = ["Mercedes", "Cadillac"];
carBrands.push("Volvo");
console.log(carBrands);
// Prints: Mercedes,Cadillac,Volvo
The push()
command uses dot notation. Where before the dot, we have the array to which we want to add a new element. After the dot follows the push()
command, which adds the value in the parentheses to the end of the array. And in the parentheses is the value "Volvo"
, which we add to the end of the array.
It sounds complicated, but as you can see, the code is relatively simple.
Instructions
Add a new coworker "Ava"
to the coworkers
array using the push()
method.
Print the value of the variable coworkers
.
Start programming for free
6/10