DEV Community

Cover image for Manipulating Arrays
Sai Pavan
Sai Pavan

Posted on • Edited on

Manipulating Arrays

🎯 With push()

The push() function is used to add data to the end of an array.

It can take one or more parameters as shown with an example:

{
    var arr1 = [1,2,3];
    arr1.push(4);
    var arr2 = [Stimpson, j ,cat];
    arr1.push([happy , joy]);
}
Enter fullscreen mode Exit fullscreen mode

🎯 With pop()

The pop() function is the opposite of push() , which removes data from the end of an array.

Any type of data can be popped off from the array with an example:

{
    var threeArr = [1,4,6];
    var oneDown = threeArr.pop();
    console.log(oneDown);
    console.log(threeArr);
}
Enter fullscreen mode Exit fullscreen mode

🎯 With unshift()

The unshift() function can unshift elements from either the end or the beginning of the array

Example:

{
    var arr = [Stimpson, j ,cat];
    arr.shift();
    arr.unshift(happy);
    after shift, arr will have value [j ,cat], after unshift() the arr would have [happy, j ,cat]
}
Enter fullscreen mode Exit fullscreen mode

🎯 With shift()

The shift() function can shift elements from either the end or the beginning of the array

Example:

{
    var arr = [Stimpson, j ,cat];
    var removedFromarr = arr.shift();
    after shift, arr will have value [j ,cat], after shift() the arr would have [happy, j ,cat]
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)