forEach
, map
, filter
, some
, every
, and reduce
.forEach
method iterates over each element in an array and executes a provided function once for each element.javascript
let arr = [1, 2, 3, 4, 5];
arr.forEach(function(el) {
console.log(el);
});
forEach
method does not create a new array; it simply executes the provided function for each element in the existing array.map
method creates a new array with the results of calling a provided function on every element in the calling array.map
method transforms each element of the original array.javascript
let num = [1, 2, 3, 4];
let double = num.map(function(el) {
return el * 2;
});
console.log(double); // Output: [2, 4, 6, 8]
javascript
let num = [1, 2, 3, 4];
let double = num.map((el) => {});
console.log(double) // Output: [undefined, undefined, undefined, undefined]
filter
method creates a new array with all elements that pass the test implemented by the provided function.true
to include the element in the new array or false
to exclude it.javascript
let nums = [2, 4, 1, 5, 6, 2, 7, 8, 9];
let even = nums.filter((num) => (num % 2 == 0));
console.log(even); // Output: [2, 4, 6, 2, 8]
every
method tests whether all elements in the array pass the test implemented by the provided function. It returns true
if all elements pass the test; otherwise, it returns false
.[2, 4].every(el => el % 2 == 0)
returns true
because all elements are even.[1, 2, 3, 4].every(el => el % 2 == 0)
returns false
because not all elements are even.[2, 4, 6].every((el) => el % 2 == 0)
returns true
[2, 4, 6, 8].every ((el) => el % 2 == 0)
returns true
[2, 4, 6, 8, 1].every ((el) => el % 2 == 0)
returns false
some
method tests whether at least one element in the array passes the test implemented by the provided function. It returns true
if at least one element passes the test; otherwise, it returns false
.[1, 2, 3, 4].some(el => el % 2 == 0)
returns true
because some elements are even.[1, 3].some(el => el % 2 == 0)
returns false
because no elements are even.reduce
method executes a reducer function (provided) on each element of the array, resulting in a single output value.javascript
let nums = [1, 2, 3, 4];
let finalVal = nums.reduce((res, el) => res + el);
console.log(finalVal); // Output: 10
reduce
method can be used to find the maximum value in an array.javascript
let nums = [2, 3, 4, 5, 3, 4, 7, 8, 1, 2];
let result = nums.reduce((max, el) => {
if(el > max) {
return el;
} else {
return max;
}
});
console.log(result); // Output: 8
Check if all numbers in an array are multiples of 10 or not using every
.
let nums = [10, 20, 30, 40];
let ans = nums.every((el) => el % 10 == 0);
console.log(ans); // Output: true
let nums = [10, 20, 30, 40, 5];
let ans = nums.every ((el) => el % 10 == 0);
console.log(ans); // Output: false
Create a function to find the minimum number in an array using reduce
.
function getMin(nums) {
let min = nums.reduce((min, el) => {
if (min < el) {
return min;
} else {
return el;
}
});
return min;
}
let nums = [10, 20, 30, 40, 5];
console.log(getMin(nums)); // Output: 5
A default parameter is a value given to a function parameter if the user does not supply a value.
Syntax:javascript
function func(a, b = 2) {
// do something
}
Example:
function sum(a, b = 3) {
return a + b;
}
console.log(sum(2)); // Output: 5
console.log(sum(1, 4)); // Output: 5
If a parameter with a default value is followed by a parameter without a default value, the function may not work as expected because JavaScript assigns arguments from left to right.javascript
function sum(a = 2, b) {
return a + b;
}
console.log(sum(1, 3)); // Output: 4
console.log(sum(1)); // Output: NaN (because b is undefined)
...
).Math.min()
javascript
let arr = [1, 2, 3, 4, 5];
console.log(Math.min(...arr)); // Output: 1
javascript
console.log(...".apnacollege"); // Output: a p n a c o l l e g e
javascript
let arr = [1, 2, 3, 4, 5];
let newArr = [...arr];
newArr.push(6);
console.log(arr); // Output: [1, 2, 3, 4, 5]
console.log(newArr); // Output: [1, 2, 3, 4, 5, 6]
javascript
let odd = [1, 3, 5, 7, 9];
let even = [2, 4, 6, 8, 10];
let nums = [...odd, ...even];
console.log(nums); // Output: [1, 3, 5, 7, 9, 2, 4, 6, 8, 10]
javascript
let data = {
email: "ironman@gmail.com",
password: "abcd",
};
let dataCopy = { ...data, id: 123, country: "India" };
console.log(dataCopy);
// Output: {email: 'ironman@gmail.com', password: 'abcd', id: 123, country: 'India'}
javascript
let arr = [1, 2, 3, 4, 5];
let obj1 = { ...arr };
console.log(obj1); // Output: {0: 1, 1: 2, 2: 3, 3: 4, 4: 5}
javascript
let obj2 = { ..."hello" };
console.log(obj2); // Output: {0: 'h', 1: 'e', 2: 'l', 3: 'l', 4: 'o'}
The rest parameter allows a function to accept an indefinite number of arguments as an array.
Syntax:javascript
function sum(...args) {
// args is an array
}
Example:
function sum(...args) {
let total = 0;
for (let i = 0; i < args.length; i++) {
total += args[i];
}
return total;
}
console.log(sum(1, 2, 3, 4)); // Output: 10
Using reduce with rest parametersjavascript
function sum(...args) {
return args.reduce((sum, el) => sum + el);
}
console.log(sum(1, 2, 3, 4)); // Output: 10
Rest parameter to find mix javascript
function min(...args) {
return args.reduce((min, el) => {
if (min < el) {
return min;
} else {
return el;
}
});
}
console.log(min(1, 2, 3, 4)); // Output: 1
console.log(min(12, 445, 123, -20)); // Output: -20
Rest parameters can be combined with regular parameters.javascript
function min(msg, ...args) {
console.log(msg);
return args.reduce((min, el) => {
if (min < el) {
return min;
} else {
return el;
}
});
}
console.log(min("hello", 12, 445, 123, -20));
// Output:
// hello
// -20
javascript
let names = ["tony", "bruce", "steve", "peter"];
let [winner, runnerup] = names;
console.log(winner, runnerup); // Output: "tony" "bruce"
javascript
let names = ["tony", "bruce", "peter", "steve", "abc", "xyz", "pyq"];
let [winner, runnerup, ...others] = names;
console.log(winner); // Output: "tony"
console.log(runnerup); // Output: "bruce"
console.log(others); // Output: ["peter", "steve", "abc", "xyz", "pyq"]
Example:
const student = {
name: "karan",
class: 9,
age: 14,
subjects: ["hindi", "english", "math", "science", "social studies"],
username: "karan@123",
password: "abcd",
};
let { username, password } = student;
console.log(username); // Output: "karan@123"
console.log(password); // Output: "abcd"
Renaming Variables During Destructuringjavascript
let { username: user, password: secret } = student;
console.log(user); // Output: "karan@123"
console.log(secret); // Output: "abcd"
Setting Default Valuesjavascript
let { username: user, password: secret, city = "Mumbai" } = student;
console.log(city); // Output: "Mumbai" if city is not defined in student
If the object has a property, it will override the default value.javascript
const student = {
name: "karan",
age: 14,
class: 9,
subjects: ["hindi", "english", "math", "science"],
username: "karan@123",
password: "abcd",
city: "Pune",
};
let { username: user, password: secret, city: place = "Mumbai" } = student;
console.log(place); // Output: "Pune"
Square and sum the array elements using the arrow function and then find the average of the array.
let nums = [1, 2, 3, 4, 5];
const square = nums.map((num) => num * num);
console.log(square); // Output: [1, 4, 9, 16, 25]
let sum = square.reduce((acc, cur) => acc + cur, 0);
let avg = sum / nums.length;
console.log(avg); // Output: 11
Create a new array using the map function whose each element is equal to the original element plus 5.javascript
let numbers = [2, 4, 6, 8, -2, -4];
console.log(numbers.map((number) => number + 5));
// Output: [7, 9, 11, 13, 3, 1]
Create a new array whose elements are in uppercase of words present in the original array.javascript
let strings = ["adam", "bob", "catlyn", "donald", "eve"];
console.log(strings.map((string) => string.toUpperCase()));
// Output: ["ADAM", "BOB", "CATLYN", "DONALD", "EVE"]
Write a function called doubleAndReturnArgs
which accepts an array and a variable number of arguments. The function should return a new array with the original array values and all of the additional arguments doubled.
const doubleAndReturnArgs = (arr, ...args) => [
...arr,
...args.map((v) => v * 2),
];
console.log(doubleAndReturnArgs([1, 2, 3], 4, 4)); // Output: [1, 2, 3, 8, 8]
console.log(doubleAndReturnArgs([2], 10, 4)); // Output: [2, 20, 8]
Write a function called mergeObjects
that accepts two objects and returns a new object which contains all the keys and values of the first object and second object.javascript
const mergeObjects = (obj1, obj2) => ({ ...obj1, ...obj2 });
console.log(mergeObjects({ a: 1, b: 2 }, { c: 3, d: 4 }));
// Output: {a: 1, b: 2, c: 3, d: 4}