1.for...of
Used to iterate (loop) through the values of an iterable object
It gives the actual values one by one
Used for Arrays, Strings, Sets, Maps
Syntax
for (let variable of iterable) {
// Code to execute
}
let name = "Kiruthiga";
for (let letter of name) {
console.log(letter);
}
Output:K
i
r
u
t
h
i
g
a
let fruits = ["Apple", "Orange", "Mango"];
for (let fruit of fruits) {
console.log(fruit);
}
Output:Apple
Orange
Mango
2.for...in
Used to iterate (keys) through the property name & index of an iterable object
It gives the index or property name one by one
Used for Objects, Array indexes
Syntax
for (let key in object) {
// Code to execute
}
let fruit = ["Apple", "Orange", "Mango"];
for (let index in fruit) {
console.log(index);
}
Output:0
1
2
let name = "Kiruthiga";
for (let letter in name) {
console.log(name[letter]);
}
Output:K
i
r
u
t
h
i
g
a
let fruits = ["Apple", "Orange", "Mango"];
// Indexes
for (let index in fruits) {
console.log(index);
}
// Values
for (let fruit of fruits) {
console.log(fruit);
}
Output:0
1
2
Apple
Orange
Mango
3.flatMap()
first maps all elements of an array and then creates a new array by flattening the array
Syntax
array.flatMap(function(currentValue, index, array) {
return newValue;
});
let number=[1,2,3];
let result = number.flatMap(multiple);
console.log(result);
function multiple(x){
console.log(x);
return[x,x*5];
}
Output:[1, 5, 2, 10, 3, 15]
4.filter()
Creates the new array and assign the element if pass in the condition
let array=[16,27,8,29,75];
let newArray= array.filter(element);
console.log(newArray);
function element(x){
return x>18;
}
Output:[27, 29, 75]
5.reduce()
runs a function on each array element to produce a single value
works from left-to-right in the array
let numbers = [10, 20, 30, 40];
let sum=numbers.reduce(summ);
function summ(total,current){
return total+current;
}
console.log(sum);
Output:100
6.reduceRight()
runs a function on each array element to produce a single value
works from left-to-right in the array
let numbers = [10, 20, 30, 40];
let sum=numbers.reduce(summ);
function summ(total,current){
return total+current;
}
console.log(sum);
Output:10
7.every()
checks whether all elements in an array satisfy a given condition
let a=[16,27,8,29,75];
let newarray= a.every(element);
console.log(newarray);
function element(x){
return x>18;
}
Output:false
*8.some() *
checks if one array value pass a test
let b=[16,27,8,29,75];
let c= b.some(element);
console.log(c);
function element(x){
return x>18;
}
Output:true
9.from()
creates a new array from an array-like object or an iterable object (such as a string, Set, or Map)
let k = new Set([10, 20, 30]);
let l = Array.from(k);
console.log(l);
Output:[10, 20, 30]
Top comments (0)