Add an Element at the Beginning of Array in JavaScript
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. ?Md Obydullah
Software Engineer | Ethical Hacker & Cybersecurity...
Md Obydullah is a software engineer and full stack developer specialist at Laravel, Django, Vue.js, Node.js, Android, Linux Server, and Ethichal Hacking.