Add an Element at the Beginning of Array in JavaScript

Published on August 13, 2020 16 sec read

In this article, we are going to add an item at the beginning of an array. To do this, we will use the splice() method.

The splice() method takes a few arguments. To add at the first position, we need to use 0 as the first argument:

const colors = ['2', '3', '4', '5']

colors.splice(0, 0, '1')

console.log(colors);

Console log output:

Array(5)
0: "1"
1: "2"
2: "3"
3: "4"
4: "5"
length: 5__proto__: Array(0)
That’s it. Thanks for reading. 🙂

Author

Hey, I'm Md Obydullah. I build open-source projects and write on Laravel, Linux server, modern JavaScript and more on web development.

Follow

Leave a Reply

Your email address will not be published. Required fields are marked *