DEV Community

Kaushal
Kaushal

Posted on

JavaScript arrow function

Introducrion

ES6 comes with a new function syntax which looks very different from others. Arrow functions were added in 2015, on the whole to make writing functions with less expression. Instead of using the "function" keyword, we can use an arrow (=>), which made up of an equal sign and a greater-than character (do not get confused with the greater-than-or-equal operator, which is written like >=).

Syntax

const variable = (parameter) => {
  // function body
}

The arrow comes after a list of function's parameters and followed by the function's body. Which is same as,

function functionName () {
  // function body
}

If the function has only one parameter, we can omit the parentheses around the parameter list. If the body is a single expression, rather than a block in braces, that expression will be returned automatically from the function. So, these two function definitions will do the same thing.

const func1 = (x) => { return x*x; };

cosnt func2 = x => x*x;

If function has only a single argument in the argument list, its parameter list is just empty set of parentheses.

const func = () => {
  return "Hello, world";
}

Top comments (0)