Array.push() & Array.pop()

Array.push() & Array.pop()

ยท

3 min read

Hello everyone! Welcome to the first article of the series called Array Methods. In this series, I will going through the array methods in JavaScript with code examples. Would love it if you join me on this journey. ๐Ÿ™๐Ÿ™๐Ÿ™

Introduction

Arrays according to MDN official Docs are list-like objects whose prototype has methods to perform traversal and mutation operations. The JavaScript Array object is a global object that is used in the construction of arrays. It is a special type of variable that allows you to store multiple values in a single variable. The length of a JavaScript array is not fixed and can change at any time. Arrays cannot use string as element indexes but integers.

Declaration

 let food = ['Rice', 1, 2, 'hashnode', true]

Arrays are declared within an opening and closing square brackets. It can accept values like Strings, integers, and boolean values and stored in variables named with whatever name you like. Array indexes start from 0 and not 1 (meaning that from the above code snippet, Rice is the 0 index).

When you need to manage first and last elements in the array, the push(), pop(), shift(), and unshift() methods are your go-to. And for this series, I'm starting with the Array.push() and pop() methods

Array.push()

The JavaScript array.push() method is used to add values to the end of an array. With this method, you can increase an array length as new values are added. There is no limit to new values you can add therefore it solely depends on you to know the number of new values to be inserted. Let me show you an example

 let food = ['Rice', 1, 2, 'hashnode', true]

 food.push('hashnodeSeries', 10, 20)

 //returns   ['Rice', 1, 2, 'hashnode', true,'hashnodeSeries', 10, 20]

Array.pop()

The JavaScript array.pop() method as the name sounds is used to pop out something. This method removes the last element in an array. It returns the removed element and decreases the length of the array. It does not pass any argument so if the array is empty, it returns undefined. It is the opposite of the array.push() method. Let's have a look at the syntax

 let food = ['Rice', 1, 2, 'hashnode', true]

  food.pop()

 //returns   ['Rice', 1, 2, 'hashnode']

Resources

MDN Docs: Do well to check out the MDN docs to read more on Arrays and practice on them with related examples.

Remember that the best way to learn is to practice them. And if you've got any questions, feel free to drop them.