Basic array operations in Javascript

child theme

How to add elements at the start of an array in javascript?

let list1 = [‘b’, ‘c’];
//using spread operator
console.log([‘a’, …list1]);

//Or using unshift method
list1.unshift(‘a’);
console.log(list1);

How to add elements at the end of an array in javascript?

let list2 = [‘a’, ‘b’];
//using spread operator
console.log([…list2, ‘c’]);

//or push method
list2.push(‘c’);
console.log(list2);

How to remove an element from the end of an array in javascript?

//using shift function
let list3 = [‘b’, ‘c’];
list3.shift(‘a’);
console.log(list3);

How to add elements in the middle of an array at a specified location in javascript?

//using splice function
let list4 = [“a”, “b”, “e”, “f”];
list4.splice(2, 0, “c”, “d”);
console.log(list4);