JavaScript Arrow Function

Arrow functions are a recent introduction to JavaScript.

They are very often used instead of "regular" functions, the one I described in the previous chapter. You'll find both forms used everywhere.

Visually, they allow you to write functions with a shorter syntax, from:


function getData(){ 
  //...
}

to


;() =>{ 
  //...
}

But.. notice that we don't have a name here.

Arrow functions are anonymous. We must assign them to a variable.

We can assign a regular function to a variable, like this:

let getData = function getData(){ 
  //...
}

When we do so, we can remove the name from the function:

let getData = function(){ 
  //...
}

and invoke the function using the variable name:

let getData = function(){ 
  //...
}
getData() 

That's the same thing we do with arrow functions:

let getData = () => { 
  //...
}

If the function body contains just a single statement, you can omit the parentheses and write it all on a single line:

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

Example


let getData = () => console.log("Hello World!");
console.log(getData()); // Output: "Hello World"

Parameters are passed in the parentheses:

let getData = (param1, param2) => console.log(param1, param2);

Example


let getData = (user, job) => console.log("My name is " + user +" and I'am a " + job +" in Coding Koleji");
console.log(getData("Fateemah", "Fronend Developer")); 

If you have one (and just one) parameter, you could omit the parentheses completely:

let getData = (param) => console.log(param);

Example


let getData = (user) => console.log("My name is " + user);
console.log(getData("Fateemah")); 

Arrow functions allow you to have an implicit return: values are returned without having to use the return keyword.

It works when there is a on-line statement in the function body:

let getData = () => "Hello World!"
getData() //Hello World

Example


let getData = () => "Hello World!"
console.log(getData()); //Hello World

Like with regular functions, we can have default parameters:

You can have default values for parameters, in case they are not passed:

let getData = (color = 'black', age = 2) => {
//do something
}

Example


let getData = (color = 'black', age = 2) => {
  return "The color is "+ color + " and the age is " + age;
}
console.log(getData("Green", 3));

Arrow functions can contain other arrow function, or also regular functions.

They are very similar, so you might ask why they were introduced? The big difference with regular functions is when they are used as object methods. This is something we'll soon look into.