Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do standalone JavaScript blocks have any use?

The MDN article on JavaScript blocks gives this example:

var x = 1;
{
  var x = 2;
}
alert(x); // outputs 2

As you can see JavaScript doesn't have block scope. So are there any good use cases for standalone blocks in JavaScript?

By "standalone" I mean not paired with a control flow statement (if, for, while, etc.) or a function.

like image 390
Web_Designer Avatar asked Jul 30 '13 05:07

Web_Designer


2 Answers

ES2015 introduces block scoping with let and const, so standalone blocks become useful for limiting the scope of variables:

{
  let privateValue = 'foo';
}

console.log(privateValue); // -> ReferenceError

In contrast to var:

{
  var privateValue = 'foo';
}

console.log(privateValue); // -> "foo"

let and const are implemented in the latest versions of all major browsers (including IE11).

  • let compatibility table
  • const compatibility table
like image 69
joews Avatar answered Nov 09 '22 06:11

joews


Short answer: ...not really.

The only use I know for them is labels:

myBlock: {
    // stuff
    if (something) break myBlock // jump to end of block
    // more stuff
    if (somethingElse) continue myBlock // jump to beginning of block
    // blah blah blah, more stuff
}

(almost like a goto, better watch out for the raptors)

Needless to say, this is a very bad idea. So basically, nothing; just don't use them.

(side note: a do { /* stuff */ if (something) break; /* stuff */ } while (false) could do the same thing)

like image 34
tckmn Avatar answered Nov 09 '22 07:11

tckmn