JavaScript Array Methods
Array methods simplify common tasks like adding, removing, sorting, or transforming elements. Understanding these methods helps you manipulate arrays more efficiently.
Key Topics
push() and pop()
push()
adds an element to the end of an array, while pop()
removes the last element.
let arr = ["A", "B"];
arr.push("C");
console.log(arr);
arr.pop();
console.log(arr);
Output
> ["A", "B", "C"]
> ["A", "B"]
Explanation: After pushing "C", the array has three elements. Popping removes the last element, returning it to ["A", "B"].
shift() and unshift()
shift()
removes the first element, and unshift()
adds an element to the beginning of the array.
let arr2 = ["X", "Y", "Z"];
arr2.shift();
console.log(arr2);
arr2.unshift("W");
console.log(arr2);
Output
> ["Y", "Z"]
> ["W", "Y", "Z"]
Explanation: Removing "X" with shift leaves ["Y", "Z"]. Adding "W" at the start with unshift results in ["W", "Y", "Z"].
splice() and slice()
splice()
can add or remove elements at any position. slice()
returns a shallow copy of a portion of the array.
let arr3 = ["Red", "Green", "Blue"];
arr3.splice(1, 1, "Yellow");
console.log(arr3);
let sliced = arr3.slice(0,2);
console.log(sliced);
Output
> ["Red", "Yellow", "Blue"]
> ["Red", "Yellow"]
Explanation: splice(1, 1, "Yellow")
replaces "Green" with "Yellow". slice(0,2)
copies the first two elements, resulting in a new array ["Red", "Yellow"].
JavaScript Usage in DOM
This DOM-based example shows how array methods can dynamically alter and display a list on a webpage.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Array Methods in DOM</title>
</head>
<body>
<h1>Array Methods Demo</h1>
<button onclick="modifyList()">Modify List</button>
<p id="output"></p>
<script>
function modifyList() {
let items = ["Item1", "Item2"];
items.push("Item3");
items.shift();
document.getElementById("output").textContent = items.join(", ");
}
</script>
</body>
</html>
Key Takeaways
- push()/pop(): Add/remove elements at the end.
- shift()/unshift(): Remove/add elements at the start.
- splice()/slice(): Insert, remove, or extract parts of an array.
- DOM Integration: Dynamically modify array content on webpages.