Higher Order Functions In JavaScript
1. forEach()
Function
The forEach()
method is used to execute a provided function once for each element in an array. It does not return a new array; it simply iterates over the array.
Syntax:
array.forEach(callback(currentValue, index, array));
callback: The function to execute for each element.
currentValue
: The current element being processed.index
(optional): The index of the current element.array
(optional): The arrayforEach
is being called on.
Example:
let arr = [1, 2, 3, 4, 5];
function display(el) {
console.log(el);
}
arr.forEach(display);
// or we can aslo write it with arrow function
arr.forEach((i) => {
console.log(i);
});
// or we can also write it by using simple funtion
arr.forEach(function (i) {
console.log(i);
});
- all the above codes will display the same output ( 1,2,3,4,5)
2. map()
Function
The map()
method creates a new array populated with the results of calling a provided function on every element in the calling array.
Syntax:
const newArray = array.map(callback(currentValue, index, array));
callback: The function to execute for each element.
currentValue
: The current element being processed.index
(optional): The index of the current element.array
(optional): The arraymap
is being called on.
Example:
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
function double(el) {
return 2 * el;
}
let doubleArray = arr.map(double);
console.log(doubleArray);
// output: [ 2, 4, 6, 8, 10 ]
3. filter()
Function
The filter()
method creates a new array with all elements that pass the test implemented by the provided function.
Example:
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
function odd(el) {
return el % 2 == 1;
}
let ans = arr.filter(odd);
console.log(ans);
Output: [ 1, 3, 5, 7, 9 ]
4. every()
Function
The every()
method tests whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value.
Example:
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
function odd(el) {
return el % 2 == 1;
}
let ans = arr.every(odd);
console.log(ans);
// output : false
arr = [1, 3, 5, 7, 9, 11];
ans = arr.every(odd);
console.log(ans);
// output : true
5. reduce()
Function
The reduce()
method executes a reducer function (that you provide) on each element of the array, resulting in a single output value.
Syntax:
const result = array.reduce(reducerFunction(accumulator, currentValue, index, array), initialValue);
reducerFunction: A function to execute on each element.
accumulator
: Accumulates the return values.currentValue
: The current element being processed.index
(optional): The index of the current element.array
(optional): The arrayreduce
is being called on.
initialValue (optional): A value to use as the first argument for the accumulator.
Example:
let arr = [1, 2, 3, 4, -5, 6, 7, 8, 9, 10];
let min = arr.reduce((min, el) => {
if (min > el) {
return el;
} else {
return min;
}
});
console.log(min);
Output : -5
6. Default Parameters
Default parameters allow you to initialize function parameters with default values if no argument is passed or if undefined
is passed.
Example:
function add(a, b = 5) {
console.log(a + b);
}
add(10);
Output: 15
function add(a=5, b) {
console.log(a + b);
}
add(10)
Output : Nan ( since b is undefined)
7. Spread Operator (...
)
The spread operator allows an iterable (like an array or object) to be expanded into individual elements.
let name = "dheeraj singh";
console.log(...name);
Output : d h e e r a j s i n g h
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const combined = [...arr1, ...arr2];
console.log(combined);
Output: [1, 2, 3, 4, 5, 6]
8. Rest Parameters (...
)
Rest parameters allow you to represent an indefinite number of arguments as an array. It collects all remaining arguments into a single array.
function sum(...numbers) {
return numbers.reduce((acc, num) => acc + num, 0);
}
console.log(sum(1, 2, 3)); // Output: 6
console.log(sum(10, 20)); // Output: 30
- The rest operator is used to handle an indefinite number of arguments passed to a function and collects them into an array.
Rest parameters for the object
let data = {
email: "javascript@gmail.com",
password: "abcd",
};
let dataCopy = { ...data, id: 7895 };
console.log(dataCopy);
Destructuring in Js
Destructuring in JavaScript is a convenient way of extracting values from arrays or objects into distinct variables. This syntax allows us to unpack data from arrays or properties from objects in a cleaner and more readable way.
let winner = ["india", "south africa", "Afghanistan", "Australia", "England"];
let [first, second, ...restTeam] = winner;
console.log(first);
console.log(second);
console.log(restTeam);
Output :
india
south africa
[ 'Afghanistan', 'Australia', 'England' ]
Destructuring Objects
With object destructuring, you can unpack values from an object into individual variables based on the object’s properties. This is particularly useful when working with objects that have a lot of properties, and you only need a subset of them.
const person = {
name: "Alice",
age: 25,
city: "New York"
};
// Object destructuring
const { name, age } = person;
console.log(name); // Output: "Alice"
console.log(age); // Output: 25
- In this example, the
name
andage
properties of theperson
objects are destructured into their own variables.
Example with Default Values:
You can also assign default values to variables in case the object doesn’t contain the specified property
const person = {
name: "Alice",
age: 25,
city: "New York",
};
// Object destructuring
const { name, age, section = "A" } = person;
console.log(name); // Output: "Alice"
console.log(age); // Output: 25
console.log(section); // Output : A
Example with Renaming Variables:
You can rename variables while destructuring by specifying new variable names.
const person = {
name: "Alice",
age: 25,
city: "New York",
};
// Object destructuring
const { name : FirstName, age, section = "A" } = person;
console.log(FirstName); // Output: "Alice"
console.log(age); // Output: 25
console.log(section); // Output : A
- Here,
name
is renamed tofirstName
, andage
is renamed toyearsOld
while destructuring.
Destructuring Nested Objects
You can destructure nested objects by using a similar syntax to access deeper properties.
Example:
const user = {
id: 101,
details: {
name: "Charlie",
age: 28
}
};
const { details: { name, age } } = user;
console.log(name); // Output: "Charlie"
console.log(age); // Output: 28
- Here, the
details
object within theuser
object is destructured to accessname
andage
directly.
*******************************************************************
que: create a function to find the min element in the array
let arr = [10, 20, 30, -40, 50, 60, 70, 80, 90, 10];
let answer = function (arr) {
let min = arr.reduce((min, el) => {
if (min > el) {
return el;
} else {
return min;
}
});
return min;
};
console.log(answer(arr));
Output : -40
que: check if all the numbers in the array are multiple of 10 or not.
let arr = [10, 20, 30, 40, 50, 60, 70, 80, 90, 10];
let answer = arr.every((el) => {
return el % 10 == 0;
});
console.log(answer);
Output : True
Subscribe to my newsletter
Read articles from dheeraj koranga directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by