Costa Costa - 1 year ago 49
Javascript Question

What do braces do in JavaScript?

I read this line in Eloquent JavaScript and would love some clarity.

...braces have two meanings in JavaScript. At the start of a statement, they start a block fo statements. In any other position, they describe an object. Fortunately, it is almost never useful to start a statement with a brace object, and...

So, braces in let's say a..... an 'if statement' create a block of statements to execute, but braces that appear in let's say a function call (as a parameter) or in a variable assignment becomes an object literal.

Is that right? What are all the other cases? I'm not sure I understand the rule for when braces bundle up statements and for when they describe an object.

Answer Source

as object literals

var a = {field1:value1, field2:value2}

as function bodies

function func() {
    // do something
var f = function() { /* do something */ };
var f = ()=>{}; // ditto

where the first item in the statement is an object literal

// {}.toString(); // syntax error, first brace of statement = code block
({}).toString(); // correct

as destructured assignment

var obj = {a:1, b:2, c:3};
var {a:x, c:y} = obj; // assign obj.a to x, and obj.c to y
({a:x, c:y} = obj); // ditto

Note - this has a lot of forms so I won't cover them all, full info found here (thanks RobG)

how this is interpreted

You can assume that all your JS code is inside some {} block. So the start of your code is immediately after a { always.

Wherever a value is expected, {} does not mean a function body. At the start of a statement this is ambiguous because you can have anonymous code blocks like so:

var x = 1;
    var x = x+2;
    // x = 3
// x = 3 (!)

This is archaic from C-style syntax where this would influence scope, but in testing this in JS it doesn't seem to have that effect, so for all intents it's rather useless syntax except to identify a code block. If you wanted such behavior you'd need to do this:

var x = 1;
    var x = x+2;
    // x = 3
// x = 1

If we need an object first in some statement, we need to clarify to JS that we want a value. This is why we use ({}) instead of {}, because the former is unambiguously an object literal inside parens.