JavaScript 3 statement for looping:
1.For...of loop :
used to get the values of an array one by one.
For array we prefer for...of to get value.
let nums = [10, 20, 30];
for(let x of nums){
console.log(x);
}
output:
10
20
30
2.for...in loop :
used to access the keys or indexes of an array.
(Not recommended)
let nums = [10, 20, 30];
for(let i in nums){
console.log(i);
}
3.forEach() :
Execute/ calls a function for each array element. it doesn't create a new array.
const numbers = [45, 4, 9, 16, 25];
numbers.forEach(myFunction);
//function myFunction(value, index, array)
function myFunction(value){
console.log(value);
}
output :
45
4
9
16
25
notes : within function we can give 3 arguments(value index, array).
4.map() :
create a new array transforming/performing a function each element.
const num1=[1, 2, 3];
const num2= num1.map(myFunction);
//function myFunction(value, index, array)
function myFunction(value){
return value*2;
}
console.log(num2);
5.flatMap() :
first map each array element then create new array by flatten the array.
let nums = [1, 2, 3];
let result = nums.flatMap(n => [n, n * 10]);
console.log(result); //1,10,2,20,3,30
6.filter() :
create new array containing only elements that satisfy a condition.
let nums = [10, 15,20,25];
let result = nums.filter(myFunction);
function myFunction(value){
return value >15;
}
or
let nums = [10, 15,20,25];
let result = nums.filter(n => n > 15);
console.log(result); //[20, 25]
7.reduce()
combines array elements into single result.
note : works from left to right.
let nums = [10,20,30];
let result = nums.reduce((total, n) => total + n, 0);
console.log(result); //60
8.reduceRight() :
works from right to left
9.every() :
checks all elements satisfy a condition.
returns true or false.
let nums = [10,20,30];
console.log(nums.every(n => n>5)); //true
console.log(nums.every(n => n>15));//false
10.some() :
checks at least one element satisfies a condition.
let nums = [10,20,30];
console.log(nums.every(n => n>5)); //true
console.log(nums.every(n => n>15));//true
11.Array.from() :
create a new array from a iterable or array like value , string.
let text = "CAT";
let result = Array.from(text);
console.log(result);
output: ["C", "A", "T"]
12.keys() :
returns an iterator containing the array's indexes.
let fruits = ["apple", "mango", "orange"];
console.log([...fruits.keys()]);
output : [0, 1, 2]
13.spread operator(...) :
spread expands an array's elements. it is used to copy or combine arrays.
let a = [10,20, 30];
let b = [...a];
console.log(b); //[10, 20, 30]
let a = [10, 20];
let b = [30, 40];
console.log(...a, ...b); //[10, 20, 30, 40]
14.rest parameter(...) :
rest collects arguments into single array. spread and rest are same but differ purpose.
function add(...nums){
return nums.reduce((total, n) => total + n, 0);
}
console.log(add(10, 20, 30)); //60
Top comments (0)