Arrow functions
Arrow functions is very simple and short syntax for creating functions, it’s often better than Function Expressions.
it looks like this:
let func = (arg1, arg2, ..., argN) => expression
This creates a function func that accepts arguments arg1..argN, then evaluates the expression on the right side with their use and returns its result.
Let’s see a solid example:
let add = (x, y) => x + y;
alert( add(1, 2) ); // 3
/* This arrow function is a shorter form of:
let add = function(x, y) {
return x + y;
};*/
If we have only one arg, then parentheses around parameters can be ignored, making that even smaller.
e.g.
let num = n => n * 2;
// roughly the same as: let num = function(n) { return n * 2 }
alert( num(3) ); // 6
If there are no arguments, parentheses will be empty (but they should be present):
let myName = () => alert("Talha!");
myName();
Multiline arrow functions
let sum = (a, b) => { // the curly brace opens a multiline function
let result = a + b;
return result; // if we use curly braces, then we need an explicit "return"
};
alert( sum(1, 2) ); // 3
For now, we can already use arrow functions for one-line actions and callbacks.
I will share more in my upcoming posts.
Thanks for reading
Top comments (0)