Code Highlights logo

Learn

Arrays

The .push() Method

What is the .push() Method? The .push() method allows us to easily add elements to the end of an array. It modifies the original array and returns the updated length of the array.

Syntax

1array.push(element1, element2, ..., elementN)
  • The .push() method adds elements to the end of an array.
  • It can accept multiple elements separated by commas.
  • The original array is modified and the new length is returned.

Examples

Let's take a look at a few examples to better understand how the .push() method works:

1const fruits = ['apple', 'banana', 'orange'];
2
3// Add a single element
4fruits.push('grape');
5// fruits is now ['apple', 'banana', 'orange', 'grape']
6
7// Add multiple elements
8fruits.push('kiwi', 'pear');
9// fruits is now ['apple', 'banana', 'orange', 'grape', 'kiwi', 'pear']

Instructions

1.

Create a variable called newNumber and assign it a value of 4.

2.

Use the .push() method to add the value of newNumber to the numbers array.

3.

Print the updated numbers array to the console.

Sign up to start coding

Already have an account?

Sign In

Course content