[JavaScript]Removing Array Elements: Operating on the Start and End with shift and pop

目次

Overview

When organizing array data, common tasks include discarding the oldest data (removing from the start) or canceling the most recent addition (removing from the end). In JavaScript, the shift and pop methods allow you to perform these operations intuitively and efficiently. This article explains the behavior of these methods and how to utilize their return values, which contain the removed data.


Specifications (Input/Output)

MethodActionPositionReturn Value
shift()Removes the first elementFront (Index 0)The value of the removed element (or undefined if empty)
pop()Removes the last elementBack (Last index)The value of the removed element (or undefined if empty)

Both of these are mutative methods, meaning they modify the original array directly and decrease its length by 1.


Basic Usage

1. Removing from the Start (shift)

Like guiding people from the front of a line, this method retrieves and removes the oldest data entry.

const storageItems = ['Backup_A', 'Backup_B', 'Backup_C'];

// Remove the first item 'Backup_A' and store it in a variable
const processed = storageItems.shift();

console.log(processed); // "Backup_A"
console.log(storageItems); // ["Backup_B", "Backup_C"]

2. Removing from the End (pop)

Like taking a box off the top of a stack, this method retrieves and removes the most recently added data entry.

const debugLogs = ['Log_1', 'Log_2', 'Log_3'];

// Remove the last item 'Log_3' and store it in a variable
const removed = debugLogs.pop();

console.log(removed); // "Log_3"
console.log(debugLogs); // ["Log_1", "Log_2"]

3. Execution on an Empty Array

Running these methods on an empty array will not cause an error but will return undefined.

const emptyStack = [];
const result = emptyStack.pop();

console.log(result); // undefined

Full Code (Notification Manager)

This demo creates a notification center. We implement operations to “Process oldest” (shift) and “Cancel last sent” (pop) to demonstrate how these methods function in a real application.

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Notification Manager</title>
    <style>
        body { font-family: sans-serif; padding: 20px; }
        .container {
            max-width: 400px;
            border: 1px solid #ccc;
            padding: 20px;
            border-radius: 8px;
            background-color: #f9f9f9;
        }
        .btn-group {
            margin-bottom: 20px;
            display: flex;
            gap: 10px;
        }
        button {
            padding: 8px 12px;
            cursor: pointer;
            border: none;
            border-radius: 4px;
            color: white;
            font-size: 0.9rem;
        }
        .btn-process { background-color: #2196F3; } /* Blue: shift */
        .btn-undo { background-color: #F44336; }    /* Red: pop */
        
        .list-area {
            background: white;
            border: 1px solid #ddd;
            min-height: 100px;
            padding: 10px;
            list-style: none;
            margin: 0;
        }
        .list-item {
            padding: 8px;
            border-bottom: 1px solid #eee;
        }
        .message-box {
            margin-top: 15px;
            padding: 10px;
            background-color: #e0f7fa;
            color: #006064;
            border-radius: 4px;
            font-size: 0.9em;
            display: none;
        }
    </style>
</head>
<body>

<div class="container">
    <h2>Notification Inbox (Queue & Stack)</h2>
    
    <div class="btn-group">
        <button id="btn-shift" class="btn-process">Process Oldest (shift)</button>
        <button id="btn-pop" class="btn-undo">Cancel Last (pop)</button>
    </div>

    <ul id="notification-list" class="list-area"></ul>

    <div id="action-log" class="message-box"></div>
</div>

<script src="manager.js"></script>
</body>
</html>

JavaScript

/**
 * Notification Management System
 * Demonstrating the use of shift and pop
 */

// Initial notification data
const notificationQueue = [
    'User1: Hello',
    'System: Update complete',
    'User2: Regarding the meeting',
    'Admin: Maintenance scheduled'
];

const listDisplay = document.getElementById('notification-list');
const logDisplay = document.getElementById('action-log');

/**
 * Refreshes the notification list in the UI
 */
const refreshDisplay = () => {
    listDisplay.innerHTML = '';
    
    if (notificationQueue.length === 0) {
        listDisplay.innerHTML = '<li style="color:#999; padding:8px;">No notifications</li>';
        return;
    }

    notificationQueue.forEach((text) => {
        const li = document.createElement('li');
        li.className = 'list-item';
        li.textContent = text;
        listDisplay.appendChild(li);
    });
};

/**
 * Displays an action log message
 * @param {string} message
 */
const updateLog = (message) => {
    logDisplay.textContent = message;
    logDisplay.style.display = 'block';
    
    // Hide after 3 seconds
    setTimeout(() => {
        logDisplay.style.display = 'none';
    }, 3000);
};

// Initial render
refreshDisplay();

// 1. Shift button: Process the oldest notification at the front
document.getElementById('btn-shift').addEventListener('click', () => {
    if (notificationQueue.length === 0) return;

    // Execution of shift()
    const removedMessage = notificationQueue.shift();
    
    refreshDisplay();
    updateLog(`Processed: "${removedMessage}" (${notificationQueue.length} remaining)`);
});

// 2. Pop button: Cancel the latest notification at the end
document.getElementById('btn-pop').addEventListener('click', () => {
    if (notificationQueue.length === 0) return;

    // Execution of pop()
    const removedMessage = notificationQueue.pop();
    
    refreshDisplay();
    updateLog(`Canceled: "${removedMessage}" (${notificationQueue.length} remaining)`);
});

Customization Points

The return value is highly useful. In the code above, the removed value is captured in a variable and used for logging. You can move this value to a separate “trash” array or save it in a history list to implement an “Undo” feature. Additionally, it is more user-friendly to disable the buttons using the disabled attribute when the array length reaches zero.


Important Notes

Both shift and pop are destructive methods that modify the original array. If you need a version of the array with an element removed while keeping the original intact, consider using slice or filter instead. Regarding performance, shift requires re-indexing every remaining element in the array, which can lead to slower execution times if the array contains tens of thousands of items. Finally, always check if the returned value is undefined before performing operations on it, as this is the default result when these methods are called on an empty array.


Advanced Usage

Removing All Elements

While you could use shift or pop in a loop to clear an array, it is faster and simpler to directly set the length property to zero.

const sessionData = [10, 20, 30, 40, 50];

// Clearing the array by setting length to 0
sessionData.length = 0; 

console.log(sessionData); // []

Summary

The shift method removes elements from the front of an array and is primarily used for queue-based processing. In contrast, the pop method removes elements from the back, making it ideal for stack structures or undoing the most recent user action. Because both methods return the removed element, you can easily track and reuse the data that was taken out of the collection. Understanding the behavioral differences between these two operations is fundamental to effective data organization and management in any JavaScript application.

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次