JavaScript Arrow Function is a function but it’s a way to create functions in a cleaner way compared to regular functions. Here is a shorter function syntax:
let myFunction = (a, b) => a * b;
let myFunction = (arg1, arg2, ...argN) => {
statement(s)
}
You can say arrow function expression is a compact alternative to a traditional function expression, but is limited and can’t be used in all situations.
An arrow function in JavaScript is a concise way of writing a function expression. It was introduced in ES6 (ECMAScript 2015) as an alternative to traditional function expressions. Arrow functions have a more compact syntax and provide implicit binding of the this
keyword.
Arrow function JavaScript
Simple example code of Arrow Function with No Argument.
<!DOCTYPE html>
<html>
<body>
<script>
hello = () => {
console.log ("Hello Arrow Function!");
}
hello();
</script>
</body>
</html>
Output:
Arrow Function with Argument
Multipication of 2 number.
let x = function(x, y) {
return x * y;
}
console.log(x(2,5))
Output: 10
Multiline Arrow Functions
let sum = (a, b) => {
let result = a + b;
return result;
}
let re s= sum(5,7);
console.log(res);
Output: 12
Differences between arrow functions and traditional functions
- It doesn’t have its own bindings to
this
orsuper
, and should not be used asmethods
. - It doesn’t have access to the
new.target
keyword. - It isn’t suitable for
call
,apply
andbind
methods, which generally rely on establishing a scope. - It can’t be used as constructors.
- It can’t use
yield
, within its body.
Traditional Function | Arrow Function |
---|---|
Uses the function keyword to define the function | Uses a => arrow to define the function |
Can have any number of parameters, which are listed in parentheses after the function name | Can have any number of parameters, which are listed in parentheses before the => arrow |
Requires a return statement to return a value | Returns the result of the expression without requiring a return statement (if the function body contains only one expression) |
Uses its own this keyword, which can be bound to the function’s execution context using bind() , call() , or apply() | Uses the this value of the enclosing lexical scope |
Can be defined using a function declaration, function expression, or method definition | Can be defined using an arrow function expression or as a concise method definition in an object literal |
Comment if you have any doubts or suggestions on this JS function topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version