Adding and Removing Items from an Array. Javascript

Arrays essential part in most programming languages including javascript. Mastering it makes your programming life easier than you think. This article is for javascript beginners, and it provides essential array methods every programmer should know.

Unlike some other programming languages like java, c++, c,… in javascript array size is not fixed, meaning that you can add, remove, and change array size however you want.

Adding new item

let arr = [1,2,3];
arr.push(10, 11);
arr.push(100);
console.log(arr); //[1,2,3,10,11,100]

unshift() method is used to add new items from the beginning of the array. Here also you should pass new items as an argument of the method.

let arr = [1,2,3];
arr.unshift(10, 11);
arr.unshift(100);
console.log(arr); //[100, 10, 11, 1, 2, 3]

Removing items

let arr = [1,2,3];
arr.pop();
console.log(arr); //[1,2]

shift() method is used to remove the first item of an array. After removal of the first item all items are shifted forward and their index change respectively.

let arr = [1,2,3];
arr.shift();
console.log(arr); //[2,3]

Note: Keep in mind that these methods directly change the current array and they return different results.

Inserting or removing items in the middle

let arr = ["a", "b", "c", "d", "e"];
arr.splice(1,2);
console.log(arr); //["a", "d", "e"]

After the second argument, you can pass as many values as you want in order to insert them in the same place.

let arr = ["a", "b", "c", "d", "e"];
arr.splice(1,2, "x", "y", "z");
console.log(arr); //["a", "x", "y", "z", "d", "e"]

Other methods

const arr = [1,2,3,4,5];
console.log(arr.length); //5

slice() method is used to take some part of an array. The index of starting point is passed as the first argument, and the ending index is passed for the second argument. The ending index will not be included in the extracted array. If there is no second argument it extracts items till the end of an array. Keep in mind that this method returns extracted array and won’t change the original array.

let arr = ["a", "b", "c", "d", "e"];
const arr1 = arr.slice(1, 3);
console.log(arr1); //["b", "c"]
const arr2 = arr.slice(2);
console.log(arr2); //[ "c", "d", "e"]

React dev.