Last time, we saw how to change existing items in an array using their index, like colors[1] = "yellow";
.
But what if you want to add a new item to the array without replacing an existing one.
Engagement Message
How might you add to the collection?
JavaScript arrays have a special built-in function (called a method) just for this: .push()
.
This method adds the specified item to the very end of the array. The array grows longer.
Engagement Message
With me so far?
Here's how you use it: arrayName.push(newItem)
.
If we have let tasks = ["review code"];
, and we run tasks.push("write tests")
, the array changes.
Engagement Message
How long do you think the tasks
array will be after this operation?
After running that command, the tasks
array becomes ["review code", "write tests"]
. The new item "write tests"
is added to the end!
You can push items of any data type (strings, numbers, booleans) to an array.
