A higher order function is a function that takes one or more functions as arguments, or returns a function as its result.
Arrow functions are modern JS syntax to declare a function, which is introduced in ES6. Besides a shortes syntax, below are the properties:
- Arrow functions don’t have their own bindings to
this
,arguments
, orsuper
, and should not be used asmethods
. - Arrow functions cannot be used as constructors. Calling them with
new
throws a TypeError. They also don’t have access to thenew.target
keyword. - Arrow functions cannot use yield within their body and cannot be created as generator functions.
A good suggestion from developer Lars Schöning:
- Use function in the global scope and for Object.prototype properties.
- Use class for object constructors.
- Use => everywhere else.
Syntax
(param1, paramN) => expression
(param1, paramN) => {
statements
}
let/const variableName = (argument) => {function body}
Example for function with no arguments
When having no arguments, you have to use empty parentheses in the function decalaration. When returning a single value, no need of curly brackets and return
keyword.
// Traditional function
function randomNumber() {
return Math.random();
}
console.log(randomNumber());
// Arrow function syntax
let randomNumber2 = () => Math.random();
console.log(randomNumber2());
// Traditional function with parameter as fn
document.addEventListener('click', function() {
console.log('click')
})
// Arrow function with parameter as fn
document.addEventListener('click', () => console.log('click'))
Example for function with only one argument
When having exactly one argument, you may omit the parentheses.
function isPositive(number){
return number >= 0
}
let isPositive2 = number => number >= 0;
console.log(isPositive2(3));
const multiply = number => number * 2;
console.log(multiply(3));
Example for Function with more than one arguments
function sum(a, b){
return a+ b;
}
const sum2 = (a,b) => {
return a+b;
};
console.log(sum2(10,100));
What are your thoughts on this post?
I’d love to hear from you! Click this link to email me—I reply to every message!
Also use the share button below if you liked this post. It makes me smile, when I see it.