JavaScript Function:
function greet(){
console.log("Hello world");
}
JavaScript regular function expression:
A regular function expression is like storing something into a variable. Following example might help you understand it better. We declare a variable,and then we write down the function.
const greet = function(){
console.log("Hello world");
}
Arrow function
Now, here comes the arrow function. Arrow function is nothing but syntactically a compact alternative to a regular function expression.
const greet = () => {
console.log("Hello world");
}
Notice there is no function
keyword in the above function expression. instead we just use an arrow and the curly braces. Also, we use parentheses before the => sign, where we can pass any arguments/parameters if needed.
const greet = (name) => {
console.log(`Hey ${name}!`);
}
We can do a lot more using arrow function. Here is a short trick if we want to return something.
const add = (x,y) => {
return x+y;
}
Instead of writing the return
keyword and using curly braces, we put the statement or expression which need to be returned inside a parentheses and that's it.
const add = (x,y) => (
x+y;
)
We can write even more shorter if we use single line statement.
const add = (x, y) => x + y;
In that case we don't even need to use any parentheses or curly braces.
Summary
const greet = function(){ //regular function expression
console.log("Hello world");
}
const greet = (name) => { //arrow function with parens around param
console.log(`Hey ${name}!`);
}
const greet = name => { //no parens around param
return (`Hey ${name}!`);
}
const greet = name => ( //implicit return
`Hey ${name}!`;
)
const isEven = num => num % 2 === 0 //one liner implicit return
Thanks for reading.
Read my other articles : Dev blogs
Top comments (0)