Information about cookies on this page

Our website uses cookies to ensure the functionality of the website, to collect and analyze information about the performance and usage of the website. Privacy Policy

  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in
  
  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in

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

  1. 1

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

  2. 2

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

Back

6/11

  1. 1. Introduction to Arrays
  2. 2. Creating Arrays
  3. 3. Accessing Array Elements
  4. 4. Changing Array Elements
  5. 5. Length and the Last Element
  6. 6. Adding Elements: push()
  7. 7. Removing Elements: pop()
  8. 8. Searching an Array
  9. 9. Nested Arrays
  10. 10. Characters of a Text
  11. 11. Summary
Next

Try it yourself

Do this exercise right here in your browser. No account needed.