DEV Community

manulangat1
manulangat1

Posted on

Manipulating arrays in javascript.

Hi guys,
Today we are going to see ways in which arrays can be manipulated in javascript. We are going to focus on 4 main ways of doing that.

  1. PUSH . The push function appends data at the end of an array. Take an example.
  var myArray = [] 
  myArray.push(1)
  console.log(myArray)
Enter fullscreen mode Exit fullscreen mode

We can also use the push() function to append more than one element into an array.

  var myArray = [] 
  myArray.push(1,2,3)
  console.log(myArray)
Enter fullscreen mode Exit fullscreen mode

2 . Pop function.
The pop function is used to remove the last element of an array and return the removed element.

    var myArray = [1,2,3,4]
    var removedArray = myArray.pop()
    console.log(removedArray)
Enter fullscreen mode Exit fullscreen mode

3 . Shift function.
The shift function is used to remove the first element of an array and returns the removed element.

    var myArray = [1,2,3,4]
    var removedArray = myArray.shift()
    console.log(removedArray)
Enter fullscreen mode Exit fullscreen mode

4 . Unshift function.
The unshift function is used to add elements at the beginning of an array.

    var myArray = [1,2,3,4]
    myArray.unshift(0)
    console.log(myArray)
Enter fullscreen mode Exit fullscreen mode

That's all for today guys and I hope this short guide will help you understand the manipulation of arrays in javascript.

Top comments (0)