Adding Elements: push()

Arrays come with handy tools for common tasks, called methods. A method is a command that belongs to a value. To use it, you write the value, a dot, the method's name and parentheses. Using a method is called calling it. You've been calling one method since the start of the course: console.log() is the method log that belongs to the console.

The method push() adds an element to the end of an array. You write the new element in the parentheses:

const carBrands = ["Mercedes", "Cadillac"];
carBrands.push("Volvo");
console.log(carBrands);
console.log(carBrands.length);

This prints:

["Mercedes", "Cadillac", "Volvo"]
3

Read carBrands.push("Volvo") from left to right: for the array carBrands, call the method push(), which adds "Volvo" to its end. The array changes, and so does its .length. You can add elements even to an array created with const: it's still the same array, just with one more element.

This way, you can also build a list step by step, starting from an empty array:

const todo = [];
todo.push("Buy milk");
todo.push("Walk the dog");
console.log(todo);

This prints:

["Buy milk", "Walk the dog"]

Method names are case-sensitive, just like variable names. If you write carBrands.Push("Volvo"), the program stops with TypeError: carBrands.Push is not a function: JavaScript can't find anything called Push that it could call. (A function is the general name for something you can call; you'll learn about functions in a later lesson.) You get a similar error with carBrands.length(): length is a property, a value, not a method, so it has no parentheses.

Instructions

Ava has joined the team. Add "Ava" to the end of coworkers with the method push().

Print coworkers. The console should show ["Josh", "Daniel", "Emily", "Ava"].

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

Back

6/11

Next