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(); 
// "🙀"
Enter fullscreen mode Exit fullscreen mode

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();
// "🙀"
Enter fullscreen mode Exit fullscreen mode

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

foo = () => '🙀'; foo();
// "🙀"
Enter fullscreen mode Exit fullscreen mode

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

foo = () => {cat: '🙀'}; foo();
// undefined
Enter fullscreen mode Exit fullscreen mode

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: "🙀"}
Enter fullscreen mode Exit fullscreen mode

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: "🙀"}
Enter fullscreen mode Exit fullscreen mode

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
// "🙀"
Enter fullscreen mode Exit fullscreen mode

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/