0
0
Javascriptprogramming~5 mins

Modifying arrays in Javascript

Choose your learning style9 modes available
Introduction

We change arrays to add, remove, or update items. This helps keep our list of things up to date.

You want to add a new friend to your list of friends.
You need to remove a finished task from your to-do list.
You want to change the name of a product in your shopping cart.
You want to insert a new song in your playlist at a specific spot.
You want to clear all items from a list to start fresh.
Syntax
Javascript
const array = [1, 2, 3];

// Add item at the end
array.push(newItem);

// Remove last item
array.pop();

// Add item at the start
array.unshift(newItem);

// Remove first item
array.shift();

// Change item at index
array[index] = newValue;

// Remove item at index
array.splice(index, 1);

// Insert item at index
array.splice(index, 0, newItem);

Array indexes start at 0, so the first item is at index 0.

splice() can add or remove items anywhere in the array.

Examples
Adds 'orange' to the end of the array.
Javascript
const fruits = ['apple', 'banana'];
fruits.push('orange');
console.log(fruits);
Removes the only item, resulting in an empty array.
Javascript
const numbers = [10];
numbers.pop();
console.log(numbers);
Adds 'red' to the start of an empty array.
Javascript
const colors = [];
colors.unshift('red');
console.log(colors);
Replaces the item at index 1 ('b') with 'x'.
Javascript
const letters = ['a', 'b', 'c'];
letters.splice(1, 1, 'x');
console.log(letters);
Sample Program

This program shows adding, removing, changing, and inserting tasks in an array.

Javascript
const tasks = ['wash dishes', 'do laundry', 'buy groceries'];

console.log('Before modification:', tasks);

// Add a new task at the end
const newTask = 'call mom';
tasks.push(newTask);

// Remove the first task
const removedTask = tasks.shift();

// Change the second task
tasks[1] = 'fold clothes';

// Insert a task at index 1
tasks.splice(1, 0, 'clean room');

console.log('After modification:', tasks);
console.log('Removed task:', removedTask);
OutputSuccess
Important Notes

Adding or removing items at the end with push/pop is very fast (constant time).

Using splice to add or remove items in the middle can be slower because items need to move.

Remember array indexes start at 0, so be careful when choosing the index.

Use push/pop for stack-like behavior, shift/unshift for queue-like behavior, and splice for precise control.

Summary

Arrays can be changed by adding, removing, or updating items.

Use push/pop for the end, unshift/shift for the start, and splice for anywhere.

Always check your indexes to avoid errors.