JavaScript Array Methods
Learn how and when to use push(), pop(), unshift() & shift()
Overview:
JavaScript arrays are comparably more versatile than arrays in other programming languages. That is because JavaScript arrays support dynamic memory by default which allows us to not worry about memory allocation. Furthermore, JavaScript arrays can be used as user-defined data structures like stacks and queues. In practice, what this means is that JavaScript arrays come with methods that allow us to insert and remove elements from either end of an array. In this article, we will discuss these methods and when best to use them.
Push():
The push
method adds elements to the end of an array.
let sodas = ['coke']sodas.push('sprite') // ['coke', 'sprite']sodas.push('fanta', 'mr pibb') //['coke', 'sprite', 'fanta', 'mr pibb']
The push
method also returns the new length of the array.
Pop():
The pop
method removes elements from the end of an array.
let sodas = ['coke', 'sprite', 'fanta', 'mr pibb']sodas.pop() // ['coke', 'sprite', 'fanta']