Array Methods
Introduction
JavaScript arrays provide several built-in methods to manipulate and process data easily. These methods help developers write cleaner and more readable code compared to traditional loops.
This assignment explains the following array methods:
push()andpop()shift()andunshift()map()filter()reduce()forEach()
Each method is explained with a simple practical example and the before and after array state.
1. push() and pop()
push()
push() adds a new element at the end of an array.
let numbers = [1, 2, 3];
numbers.push(4);
console.log(numbers);
Before
[1, 2, 3]
After
[1, 2, 3, 4]
pop()
pop() removes the last element from an array.
let numbers = [1, 2, 3];
numbers.pop();
console.log(numbers);
Before
[1, 2, 3]
After
[1, 2]
2. shift() and unshift()
shift()
shift() removes the first element of an array.
let numbers = [10, 20, 30];
numbers.shift();
console.log(numbers);
Before
[10, 20, 30]
After
[20, 30]
unshift()
unshift() adds a new element at the beginning of the array.
let numbers = [20, 30];
numbers.unshift(10);
console.log(numbers);
Before
[20, 30]
After
[10, 20, 30]
3. map()
map() creates a new array by transforming each element.
Example: Double each number
let numbers = [2, 4, 6];
let doubled = numbers.map(function(num) {
return num * 2;
});
console.log(doubled);
Before
[2, 4, 6]
After
[4, 8, 12]
4. filter()
filter() creates a new array with elements that satisfy a condition.
Example: Numbers greater than 10
let numbers = [5, 12, 8, 20];
let result = numbers.filter(function(num) {
return num > 10;
});
console.log(result);
Before
[5, 12, 8, 20]
After
[12, 20]
5. reduce()
reduce() is used to combine all elements into a single value such as a total sum.
Example: Find total sum
let numbers = [5, 10, 15];
let sum = numbers.reduce(function(total, num) {
return total + num;
}, 0);
console.log(sum);
Result
30
Here:
totalstores accumulated valuenumis the current element
6. forEach()
forEach() runs a function for every element in the array.
let numbers = [1, 2, 3];
numbers.forEach(function(num) {
console.log(num);
});
Output
1
2
3