2023-05-07

Javascript :: Add an item at the start of an Array

 Two options mostly use:

  • unshift()
  • splice()

Considering splice because it's always used for inserting at any position in the array.

Using unshift:

var myArray = [1, 2];
myArray.unshift(0);
console.log(JSON.stringify(myArray));
//outputs: [0, 1, 2]


Using splice:

var myArray = [1, 2];
var valueToInsert = -1;
var indexToInsert = 0;
var deleteCount = 0;
myArray.splice(indexToInsert, deleteCount, valueToInsert);
console.log(JSON.stringify(myArray));
//outputs: [-1, 1, 2]



No comments:

Post a Comment

Please provide any feedback or post questions here...

Javascript :: comparison operators, using == vs === and != vs !==

Comparison operators are distinguished following simple logic, whether data type is being included or not. Essentially if it is === or !==, ...