minhluuquang / TIL

You are seeing a part of my brain
0 stars 0 forks source link

JS ES6 arrow function return #12

Open minhluuquang opened 6 years ago

minhluuquang commented 6 years ago

Arrow functions can return a value implicitly or explicitly. When there is no function body (no curly brace {}) then you are returning implicitly:

const x = () => 'we are returning a string here';  

When we use a function body, we need to use the return key word:

const x = () => {
  return 'another string returned'
};

There is another option to return something without the return key word, you can wrap the curly brace with parentheses () and this will signal the engine that the curly brace are not a function body but an object, this is considered as creating an expression:

const x = () => ({myKey: 'some string'});

This is similar as we usually do with function expressions. Especially with IIFE (Immediately Invoked Function Expression) :

(function() {
    //some logic...
})();

If we will not return anything, then the function will just return undefined.