OneBite.Dev - Coding blog in a bite size

insert an element at the beginning of an array in Javascript

Code snippet on how to insert an element at the beginning of an array in Javascript

  // Javascript code snippet to insert an element at the beginning of an array 
  let arr = [1, 2, 3, 4]; 
  let x = 10; 
 
  // We can use `unshift()` method to add an element at the beginning of an array 
  arr.unshift(x); 
  
  console.log(arr);  // Output: [10, 1, 2, 3, 4]

This code snippet creates a new array, arr, with four elements, then creates a new variable x with the value 10. We then use the array method unshift() to add the value of x to the beginning of the array. Finally, we log the result to the console. In this example, the output will be [10, 1, 2, 3, 4]. unshift() is a powerful method for adding elements to the beginning of an array as it does not require us to manually shift existing elements to the right to make room for the new element.

javascript