- Published on
Higher order functions in Javascript
- Authors
- Name
- Khalil
- @Im_Khalil
A function that accepts and/or returns another function is called a higher-order function.
It’s higher-order because instead of strings, numbers, or booleans, it goes higher to operate on functions.
With functions in JavaScript, you can
- Store them as variables
- Use them in arrays
- Assign them as object properties (methods)
- Pass them as arguments
- Return them from other functions
Example:
Strings as arguments:
sayHi = (name) => `Hi, ${name}!`;
result = sayHi('Khalil');
console.log(result); // 'Hi, Khalil!
Numbers as arguments:
double = (x) => x * 2;
result = double(4);
console.log(result); // 8
Booleans as arguments:
getClearance = (allowed) => allowed ?
'Access granted' : 'Access denied';
result1 = getClearance(true);
result2 = getClearance(false);
console.log(result1); // 'Access granted'
console.log(result2); // 'Access denied'
Objects as arguments:
getFirstName = (obj) => obj.firstName;
result = getFirstName({
firstName: 'Khalil'
});
console.log(result); // 'Khalil'
Arrays as arguments:
len = (array) => array.length;
result = len([1, 2, 3]);
console.log(result); // 3
Functions as Arguments:
isEven = (num) => num % 2 === 0;
result = [1, 2, 3, 4].filter(isEven);
console.log(result); // [2, 4]
Returning Functions::
add = (x) => (y) => x + y;
result = add(10)(20);
console.log(result); // 30
Comments are closed but If you want to respond, please send me a message over WhatsApp or facebook or tweet or send email.