JavaScript Array.shift() Method Example

📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.

🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.

▶️ Subscribe to My YouTube Channel (176K+ subscribers): Java Guides on YouTube

▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube

The JavaScript Array.shift() method removes the first element from an array and returns that removed element. This method changes the length of the array.

Syntax

arr.shift()
Return value - The removed element from the array; undefined if the array is empty.

JavaScript Array.shift() Method Examples

Example 1: Remove the first element from an array

var array1 = [1, 2, 3]; var firstElement = array1.shift(); console.log(array1); // expected output: Array [2, 3] console.log(firstElement); // expected output: 1

Example 2: Removing an element from an array

The following code displays the myFish array before and after removing its first element. It also displays the removed element:
var myFish = ['angel', 'clown', 'mandarin', 'surgeon']; console.log('myFish before:', JSON.stringify(myFish)); var shifted = myFish.shift(); console.log('myFish after:', myFish); console.log('Removed this element:', shifted); 
Output:
myFish before: ["angel","clown","mandarin","surgeon"] myFish after: (3) ["clown", "mandarin", "surgeon"] Removed this element: angel

Example 3: Using shift() method in while loop

The shift() method is often used in condition inside while loop. In the following example every iteration will remove the next element from an array until it is empty:
var names = ["Andrew", "Edward", "Paul", "Chris" ,"John"]; while( (i = names.shift()) !== undefined ) { console.log(i); } // Andrew, Edward, Paul, Chris, John

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare