An arrow function is a shorter way to write a function expression.
Instead of using the function keyword, you use the arrow (=>) syntax.
Traditional function:
Arrow function:
Both do the same thing, but the arrow function is cleaner and more modern.
Basic Syntax of Arrow Functions
Example:
Output:
Welcome to JavaScript!
Arrow Function with Parameters
Explanation:
-
aandbare parameters -
The function returns the product
-
Output:
Shorter Syntax (Implicit Return)
If your function has only one line and returns a value, you can make it even shorter.
Output:
36
Here:
-
No
returnkeyword -
No curly braces
-
Cleaner and easier to read
Arrow Function with One Parameter
If there is only one parameter, you can remove the parentheses.
Output:
20
| Normal Function | Arrow Function |
|---|---|
Uses function keyword | Uses => |
| Longer syntax | Short and clean |
Has its own this | Does NOT have its own this |
| Can be used as constructor | Cannot be used as constructor |
| Can be hoisted (declaration) | Not hoisted |
Using arrow function as object method
Correct approach
Why Arrow Functions Are Important in JavaScript
Learning arrow functions in JavaScript helps you:
-
Write cleaner and shorter code
-
Understand React and modern frameworks
-
Work with callbacks easily
-
Improve code readability
-
Perform better in interviews
Almost every modern JavaScript project uses arrow functions heavily.