Arrays in JavaScript are powerful and come with many built-in methods that make working with lists much easier. Today, we’re going to break down some of the most commonly used array methods: push
, pop
, shift
, unshift
, splice
, slice
, concat
, indexOf
, reverse
, and sort
.
1. push()
– Add to the End
Usage: Adds one or more elements to the end of the array.
let fruits = ["apple", "banana"];
fruits.push("orange");
// ["apple", "banana", "orange"]
2. pop()
– Remove from the End
Usage: Removes the last element of the array.
let fruits = ["apple", "banana", "orange"];
fruits.pop();
// ["apple", "banana"]
3. shift()
– Remove from the Start
Usage: Removes the first element of the array.
let fruits = ["apple", "banana"];
fruits.shift();
// ["banana"]
4. unshift()
– Add to the Start
Usage: Adds one or more elements to the beginning of the array.
let fruits = ["banana"];
fruits.unshift("apple");
// ["apple", "banana"]
5. splice()
– Add/Remove Anywhere
Usage: Changes the contents of an array by removing or replacing elements.
let colors = ["red", "green", "blue"];
colors.splice(1, 1, "yellow");
// ["red", "yellow", "blue"]
Syntax: splice(start, deleteCount, item1, item2, ...)
6. slice()
– Copy a Portion
Usage: Returns a shallow copy of a part of an array.
let fruits = ["apple", "banana", "cherry"];
let copy = fruits.slice(1, 3);
// copy = ["banana", "cherry"]
7. concat()
– Merge Arrays
Usage: Joins two or more arrays.
let a = [1, 2];
let b = [3, 4];
let result = a.concat(b);
// [1, 2, 3, 4]
8. indexOf()
– Find Position
Usage: Returns the index of the first occurrence of a value.
let colors = ["red", "green", "blue"];
colors.indexOf("green");
// 1
9. reverse()
– Reverse Order
Usage: Reverses the array in place.
let numbers = [1, 2, 3];
numbers.reverse();
// [3, 2, 1]
10. sort()
– Sort Elements
Usage: Sorts the elements of an array.
let nums = [5, 1, 10];
nums.sort();
// [1, 10, 5] – be careful! It sorts as strings by default
Tip: For numbers, use:
nums.sort((a, b) => a - b);
// [1, 5, 10]
Conclusion
These array methods are the foundation for working with lists in JavaScript. Practice them, play around with combinations, and soon they’ll become second nature.
Top comments (0)