Skip to content

WebDevHubs

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

JavaScript Array shift() Method

Posted on December 30, 2024December 30, 2024 By Admin No Comments on JavaScript Array shift() Method

The Array.shift() method is a built-in JavaScript function used to remove the first element from an array and return it. This method modifies the original array, reducing its length by one.

Syntax

arr.shift();

Parameters

The shift() method does not take any parameters.

Return Value

The shift() method returns:

  • The removed first element of the array if the array is not empty.
  • undefined if the array is empty.

Example 1: Removing the First Element

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

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

Example 2: Using shift() on an Empty Array

let arr = [];

let item = arr.shift();
console.log(item); // Output: undefined
console.log(arr);  // Output: []

When the array is empty, shift() method returns undefined without causing an error.

Example 3: Processing Elements in a Queue

let tasks = ['task1', 'task2', 'task3'];

while (tasks.length > 0) {
    let currentTask = tasks.shift();
    console.log(`Processing: ${currentTask}`);
}
// Output:
// Processing: task1
// Processing: task2
// Processing: task3

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: How to Find the Sum of an Array of Numbers in JavaScript?
Next Post: JavaScript Array slice() 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