1. Home
  2. >
  3. Arrow functions explained!
1

Arrow functions explained!
rahoolbenji

Arrow functions are handy for one-liners. They come in two flavors:

  1. Without curly braces: (...args) => expression – the right side is an expression: the function evaluates it and returns the result.
  2. With curly braces: (...args) => { body } – brackets allow us to write multiple statements inside the function, but we need an explicit return to return something.
/**
There’s another very simple and concise syntax for creating functions, that’s often better than Function Expressions.

It’s called “arrow functions”, because it looks like this:
*/
let func = (arg1, arg2, ...argN) => expression


// Here is non-arrow version of the above function
let func = function(arg1, arg2, ...argN) {
  return expression;
};



let sum = (a, b) => a + b;

/* This arrow function is a shorter form of:

let sum = function(a, b) {
  return a + b;
};
*/
console.log( sum(1, 2) ); // 3




let double = n => n * 2;
// roughly the same as: let double = function(n) { return n * 2 }

console.log( double(3) ); // 6



let sayHi = () => console.log("Hello!");

sayHi();






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"
};

console.log( sum(1, 2) ); // 3
# javascript# arrow-functions