DEV Community

Cover image for Javascript Array Methods Part 1
Ahmed Ibrahim
Ahmed Ibrahim

Posted on

Javascript Array Methods Part 1

Javascript Array Methods

Arrays in Javascript provide a lot of methods, To make things easier.

Add Items

There are many ways to add items in an array Like:

  • push
  • unshift



We use push method to add items to the end of an array.

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

Enter fullscreen mode Exit fullscreen mode

And, The second method is unshift is used for add items to the beginning.

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

Enter fullscreen mode Exit fullscreen mode

How to delete an element from the array?

For delete any element form an array the is a arr.splice() method.

Let's know the syntax of splice() method:

let arr = [1,2,3];
arr.splice(startIndex, num_of_items, ...addItems);

Enter fullscreen mode Exit fullscreen mode

Now if we have an array like this:

let names = ['Ahmed', 'Mohamed', 'Mahmoud', 'islam'];
Enter fullscreen mode Exit fullscreen mode

And, we need to delete any items. Easily we use splice() method like this:

names.splice(0,1); // here we say please start from index 0 and delete one item.
console.log(names); // ['Mohamed', 'Mahmoud' , 'islam']

let removed = names.splice(1, 1); 
console.log(removed); // ['Mahmoud']


Enter fullscreen mode Exit fullscreen mode

we can add items after with delete items.

let arr = ['hello', 'world'];
names.splice(0,1, ...arr);
console.log(names); // ['hello', 'world', 'Mohamed', 'Mahmoud', 'islam']

Enter fullscreen mode Exit fullscreen mode

If you need to read the other parts of this article follow us:

Facebook Page :
Semantic Code

Hashnode :
Semantic Code

dev.to :
Ahmed Ibrahim

Top comments (0)