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.

let newArray = [1, 2, 3, 4, 5].push(6)
// [1, 2, 3, 4, 5, 6]
// 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.

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.

const names = ['Johnny', 'Pete', 'Sammy']
// output: 4

The .push() method mutates the old array.

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

// Add a number to the end

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

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

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

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

// Output updated todo list
// [{"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 which was acquired.


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