JavaScript Glossary - Lesson #13

JavaScript Array .push() Method

This methods appends one or more value to the last position of an array. This method mutates the array returning the new length of the array.

js
let newArray = [1, 2, 3, 4, 5].push(6)
// [1, 2, 3, 4, 5, 6]
js
// List of students in an array
let students = ['mike', 'will', 'shawn', 'bill']

// Add a new name to list
let newList = students.push('liz')

// Return the length of the array
console.log(newList) // 5

The push method:

  • Takes a value or values as arguments.
  • Adds the value(s) to the end of the array.
  • Returns the new length of the array.
js
array.push(element)

element This is the element to be added to the array

The method will return the new length of the array. If the array is empty, it returns 0.

js
const names = ['Johnny', 'Pete', 'Sammy']
console.log(names.push('Larry'));
// output: 4

The .push() method mutates the old array.

js
// List of numbers
const numbers = [1, 2, 3, 4, 5];

// Add a number to the end
numbers.push(6);

// Output result
console.log(numbers); // [1,2,3,4,5,6]

This is used in situations like adding todo items to a todo list.

js
// List of todos
const todos = [{name: 'Clean room', complete: false}];

// Add todo item
todos.push({name: 'Cook food', complete: true})

// Output updated todo list
console.log(todos)
// [{"name":"Clean room","complete":false},{"name":"Cook food","complete":true}]

Want to improve your coding and design skills?

I'm continually researching the best practices and tools for coding.
Join 50,000+ developers looking to make cool stuff.

We value your privacy. 1-click unsubscribe.

Chris Sev

Chris Sev

Chris Sev is the co-founder of Better Dev. Coding better every day. Previously he created Scotch.io which was acquired.

Comments

What did you think of the article? Let us know!
(these comments are powered by GitHub issues and use 0 trackers)