How do you add an element to an array in javascript?

Jun 18, 2021

JavaScript arrays have 3 methods for adding an element to an array:

  • push() adds to the end of the array
  • unshift() adds to the beginning of the array
  • splice() adds to the middle of the array

Below are examples of using push(), unshift(), and splice().

const arr = ['a', 'b', 'c'];

arr.push('d');
arr; // ['a', 'b', 'c', 'd']

arr.push('e', 'f');
arr; // ['a', 'b', 'c', 'd', 'e', 'f']
const arr = ['d', 'e', 'f'];

arr.unshift('c');
arr; // ['c', 'd', 'e', 'f']

arr.unshift('a', 'b');
arr; // ['a', 'b', 'c', 'd', 'e', 'f']
const arr = ['a', 'b', 'd'];

let start = 2;
let deleteCount = 0;
arr.splice(start, deleteCount, 'c');

arr; // ['a', 'b', 'c', 'd'];

These methods modify the array in place, which means they modify arr rather than creating a copy of arr. You can also use the spread operator and other immutable methods that create a new array and leave arr unmodified.

let arr = ['c'];

arr = arr.concat(['d', 'e']);
arr; // ['c', 'd', 'e']

// You can also use `concat()` to add to the beginning of
// the array, just make sure you call `concat()` on an array
// containing the elements you want to add to the beginning.
arr = ['a', 'b'].concat(arr);
arr; // ['a', 'b', 'c', 'd', 'e']

Setting an Index Directly

If you're adding an element to the end of the array, you don't necessarily have to use push(). You can just set the array index, and JavaScript will update the array's length for you.

let arr = ['a', 'b'];

arr[2] = 'c';

arr.length; // 3
arr; // ['a', 'b', 'c']

JavaScript does not throw an error if you set an out of bounds array index. For example, if your array has length 3 and you set index 4, JavaScript will just grow your array by adding a hole in the array.

const arr = ['a', 'b', 'c'];

arr[4] = 'e';

arr.length; // 5
arr; // [ 'a', 'b', 'c', <1 empty item>, 'e' ]

arr[3]; // undefined

In the above example, arr[3] is a hole in the array. That means arr[3] === undefined, so be careful if you're setting out of bounds array indexes.

Avoiding Duplicates

The easiest way to avoid adding duplicates to an array is to check if the array contains the given value before adding it.

const arr = ['a', 'b', 'c'];

addWithoutDuplicates(arr, 'a'); // ['a', 'b', 'c']
addWithoutDuplicates(arr, 'd'); // ['a', 'b', 'c', 'd']

function addWithoutDuplicates(arr, el) {
  if (arr.includes(el)) {
    return arr;
  }
  arr.push(el);
  return arr;
}

Using includes() works, but can cause performance issues because includes() scans through the entire array every time you call it. So the below loop is O(n^2).

const arrWithoutDuplicates = [];
for (let i = 0; i < arr.length; ++i) {
  if (arrWithoutDuplicates.includes(arr[i])) {
    continue;
  }
  arrWithoutDuplicates.push(arr[i]);
}

Instead, we recommend using a JavaScript set to represent a collection of objects where every element should be unique.

const set = new Set(['a', 'b', 'c']);

set.add('a');
set; // Set(3) { 'a', 'b', 'c' }

set.add('d');
set; // Set(4) { 'a', 'b', 'c', 'd' }

More Fundamentals Tutorials

  • Calculate the Median of an Array in JavaScript
  • The encodeURIComponent() Function in JavaScript
  • How to Check if a Date is Between Two Dates in JavaScript
  • Check a String for Numbers in JavaScript
  • Rename Variables When Using Object Destructuring in JavaScript
  • Split on Multiple Characters in JavaScript
  • Empty Objects are Truthy in JavaScript?

How do you add an element to an array in array?

First get the element to be inserted, say x. Then get the position at which this element is to be inserted, say pos. Then shift the array elements from this position to one position forward(towards right), and do this for all the other elements next to pos.

How do you add an element to an array of objects?

The push() method is used to add one or multiple elements to the end of an array. It returns the new length of the array formed. An object can be inserted by passing the object as a parameter to this method. The object is hence added to the end of the array.

How do you push data into an array?

The arr. push() method is used to push one or more values into the array. This method changes the length of the array by the number of elements added to the array. Parameters This method contains as many numbers of parameters as the number of elements to be inserted into the array.

How do you append items in JavaScript?

How it works:.
First, select the ul element by its id by using the querySelector() method..
Second, declare an array of languages..
Third, for each language, create a new li element with the textContent is assigned to the language..
Finally, append li elements to the ul element by using the append() method..