Skip to content

WebDevHubs

  • Home
  • HTML
  • CSS
  • JavaScript
  • Web Technologies
  • Web Templates
  • Toggle search form

Add New Elements at the Beginning of an Array in JavaScript

Posted on December 18, 2024 By Admin No Comments on Add New Elements at the Beginning of an Array in JavaScript

There are multiple ways to add new elements at the beginning of an array in JavaScript.

1. Using unshift() Method

The unshift() method add elements to the beginning of an array. It modifies the original array and returns the new length of the array.

Adding One Element

let arr = [10, 20, 30, 40, 50];

// Add 5 at the beginning
arr.unshift(5);

console.log(arr); 
// Output: [5, 10, 20, 30, 40, 50]

Adding Multiple Elements

let arr = [30, 40, 50];
arr.unshift(10, 20);
console.log(arr); 
// Output: [10, 20, 30, 40, 50]

2. Using splice() Method

The splice() method can insert elements at any position, including the beginning of the array.

let arr = [30, 40, 50];
arr.splice(0, 0, 10, 20);
console.log(arr);
// Output: [10, 20, 30, 40, 50]

3. Using Spread Operator (…)

The spread operator allows you to expand arrays, making it possible to add elements at the beginning without modifying the original array.

let arr = [30, 40, 50];
let newArr = [10, 20, ...arr];
console.log(newArr);
// Output: [10, 20, 30, 40, 50]

4. Using concat() Method

The concat() method combines arrays or values into a new array. It does not modify the original array.

let arr = [30, 40, 50];
let newArr = [10, 20].concat(arr);
console.log(newArr);
// Output: [10, 20, 30, 40, 50]

5. Using a for Loop

If you want to insert elements manually, you can use a for loop to shift the existing elements and add new ones.

let arr = [20, 30, 40, 50];
let item = 10;

// Shift elements manually
for (let i = arr.length; i > 0; i--) {
    arr[i] = arr[i - 1];
}
arr[0] = item;
console.log(arr); 
// Output: [10, 20, 30, 40, 50]
JavaScript, Web Technologies Tags:JavaScript-Array, JavaScript-Questions

Post navigation

Previous Post: How to Get First and Last Elements of an Array in JavaScript?
Next Post: How Do I Empty an Array in JavaScript?

Leave a Reply Cancel reply

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

Archives

  • June 2025
  • May 2025
  • March 2025
  • February 2025
  • January 2025
  • December 2024

Categories

  • CSS
  • HTML
  • JavaScript
  • Lodash
  • PHP
  • Python
  • Web Technologies
  • Web Templates

Recent Posts

  • JavaScript Array isArray() Method
  • JavaScript Array forEach() Method
  • JavaScript Array includes() Method
  • JavaScript Array keys() Method
  • JavaScript Array lastIndexOf() Method

Recent Comments

No comments to show.

Copyright © 2025 WebDevHubs.

Powered by PressBook Green WordPress theme