How do you add a new element to an array in JavaScript?

In JavaScript, adding a new element to an array is a common operation. There are several ways to add an element to an array, including using the push() method, the unshift() method, or the splice() method.

  1. Push method

    The push() method adds one or more elements to the end of an array. To add a single element to the end of an array, you can use the push() method with the value you want to add as an argument:

    const arr = [1, 2, 3];
    arr.push(4);
    console.log(arr); // Output: [1, 2, 3, 4]

    In this example, the push() method adds the value 4 to the end of the arr array.

  2. Unshift method

    The unshift() method adds one or more elements to the beginning of an array. To add a single element to the beginning of an array, you can use the unshift() method with the value you want to add as an argument:

    const arr = [2, 3];
    arr.unshift(1);
    console.log(arr); // Output: [1, 2, 3]

    In this example, the unshift() method adds the value 1 to the beginning of the arr array.

  3. Splice method

    The splice() method can add elements to an array at a specific index. The splice() method takes three arguments: the index where you want to start adding or removing elements, the number of elements you want to remove (0 if you only want to add elements), and the elements you want to add:

    const arr = [1, 2, 4, 5];
    arr.splice(2, 0, 3);
    console.log(arr); // Output: [1, 2, 3, 4, 5]

    In this example, the splice() method adds the value 3 to the arr array at index 2. The first argument (2) specifies the index at which to begin adding or removing elements. The second argument (0) specifies how many elements to remove. The third argument (3) specifies the element(s) to add.

Thank you for reading, and let’s have conversation with each other

Thank you for reading my article. Let’s have conversation on Twitter and LinkedIn by connecting.

Read more: