DEV Community

Michal Bryxí
Michal Bryxí

Posted on

 

Know your brackets in JavaScript

Basic syntax in JavaScript for defining and calling functions is:

function foo() {return '🙀'}; foo(); 
// "🙀"

With the new ES6 fat arrow syntax you can also store the function in a variable and then call it in the same way as before:

foo = () => {return '🙀'}; foo();
// "🙀"

Arrow functions have an option of concise body which have implicit return. You just omit the curly braces and the return statement:

foo = () => '🙀'; foo();
// "🙀"

So what if we want to return a hash in a concise body? My first guess would be:

foo = () => {cat: '🙀'}; foo();
// undefined

Does not work. Why? Turns out JavaScript has a concept of labels. So cat is the label in this code.

To make an implicit return of a hash, one has to wrap the hash in parentheses:

foo = () => ({cat: '🙀'}); foo();
// {cat: "🙀"}

And now if we want to call the function directly, without storing it anywhere, we will have to wrap the whole function definition in parentheses again:

(() => ({cat: '🙀'}))();
// {cat: "🙀"}

We might also want to fetch the value of the cat key directly. ES6 has a nice destructuring assignment syntax for that:

let {cat} = (() => ({cat: '🙀'}))(); cat
// "🙀"

Credits

Top comments (1)

Collapse
 
michalbryxi profile image
Michal Bryxí • Edited

Moved the article to a repo to collect all the weirdness of languages. If anyone wants to contribute: gitlab.com/michal.bryxi/wat-the-duck/

Visualizing Promises and Async/Await 🤓

async await

☝️ Check out this all-time classic DEV post on visualizing Promises and Async/Await 🤓