Skip to content

WebDevHubs

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

JavaScript Array unshift() Method

Posted on December 31, 2024December 31, 2024 By Admin No Comments on JavaScript Array unshift() Method

The Array.unshift() method is a built-in JavaScript function that adds one or more elements to the beginning of an array and returns the new length of the array. This method is useful when you need to prepend elements to an array.

Syntax

arr.unshift(element1, element2, ..., elementN);

Parameters

ParameterDescription
element1, …, elementN(Required) The elements to be added to the beginning of the array.

Return Value

The method returns the new length of the array after the elements have been added.

Example 1: Adding a Single Element

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

Example 2: Adding Multiple Elements

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

Example 3: Using unshift() with an Empty Array

let arr = [];
let newLength = arr.unshift(10);
console.log(arr);  // Output: [ 10 ]
console.log(newLength);   // Output: 1

Example 5: Adding Objects to an Array

let users = [{ name: 'John' }];
users.unshift({ name: 'Alice' });
console.log(users);
// Output: [{ name: 'Alice' }, { name: 'John' }]

Supported Browsers

BrowserSupport
Chrome1+
Firefox1+
Safari1+
Edge12+
Opera4+
Internet Explorer5.5+

JavaScript, Web Technologies Tags:JavaScript-Array, JavaScript-Array-Method, JavaScript-Method

Post navigation

Previous Post: JavaScript Array toString() Method
Next Post: JavaScript Array values() Method

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