Javascript Array and its Methods

Javascript Array and its Methods

Table of contents

No heading

No headings in the article.

Array :

  • JavaScript array is a single variable that is used to store different elements. It is often used when we want to store a list of elements and access them by a single variable.

  • In the javascript array, we can store elements with different data types.

  • eg. let arr=["Fruits", 100, true, "Flower", 40]

  • We can declare an array in the javascript using the following methods,

  • let arr = ["Banana", "Orange", "Apple", "Grapes"];

  • let arr = new array("Banana", "Orange", "Apple", "Grapes");

Array Methods :

  • Push :

    The Push() method adds an element at the end of an array.

    %[codepen.io/rohan1797/pen/WNKeyQQ]

  • Pop :

    The pop() method removes an element from the end of an array.

    %[codepen.io/rohan1797/pen/gOjYKPN]

  • Shift :

    The shift() method removes an element from the start of an array(i.e removes the first array element).

    %[codepen.io/rohan1797/pen/BaPBVZN]

  • Unshift :

    The unshift() method adds an element at the start of an array(i.e. adds an element at the beginning of an array).

    %[codepen.io/rohan1797/pen/NWBKzYR]

  • Length :

    The length property gives the length of an array. We can also set the length of an array.

    %[codepen.io/rohan1797/pen/abjoKja]

  • Concat :

    The concat() method adds one array to another array. (i.e it merges two arrays).

    %[codepen.io/rohan1797/pen/KKBPeGv]

  • Slice :

    • The slice() method slices out elements of an array into a new array.

    • This method creates a new array. This method does not remove any elements from the source array.

    • This method can take two arguments like slice(1, 3).

    • The method then selects elements from the start argument, and up to (but not including) the end argument.

  • Splice :

    • The splice() method is used to add new elements to an array.

    • const fruits = ["Banana", "Orange", "Apple", "Mango"];

    • fruits.splice(2, 0, "Lemon", "Kiwi");

    • The first parameter (2) defines the position where new elements should be added.

    • The second parameter (0) defines how many elements should be removed.

    • The rest of the parameters ("Lemon", "Kiwi") define the new elements to be added.

    • If we omit the add element parameter then it only removes elements from an array.

%[https://codepen.io/rohan1797/pen/xxJKBYK]