17

In Javascript, you can have lonely code blocks, that is, code blocks without an if, function or something like that preceding them, placed arbitrarily in the code, like this:

var a = 3,
b = 4;
{
  a = 50;
  b = 50;
}
alert(a + b); //alerts 100

I know some other languages have this (I think C++ does), and they use it for scope control: variables declared inside the lonely code block cannot be accessed outside of it. But since Javascript has function scope rather than block scope, you have to use a self-executing function (function(){})() to acheive the same effect.

Is there a purpose for this construct? Have you ever seen anybody use it? Does the spec mention it? Is this just a side effect of the grammar having some sort of general rule about code blocks?

12
  • 1
    Specification: ecma262-5.com/ELS5_HTML.htm#Section_12.1 Commented Jan 5, 2012 at 0:02
  • 2
    I think most times you see this the code was written by somebody who mistakenly thought they were getting block scope. Some people who know that it doesn't give scope control use it anyway because they like the visual grouping, but I find that harder to read since it implies scope and leaves me wondering what the original coder meant.
    – nnnnnn
    Commented Jan 5, 2012 at 0:06
  • @FelixKling like anyone can comprehend that ...
    – c69
    Commented Jan 5, 2012 at 0:11
  • 1
    @c69: That was not necessarily my intention. I just wanted to show that it is in the spec (re: Does the spec mention it?). Commented Jan 5, 2012 at 0:12
  • 1
    @FelixKling -- this has been deprecated, or there are plans to deprecate it, not sure. It doesn't work with use strict and it won't work in future ES5 engines.
    – user578895
    Commented Jan 5, 2012 at 0:20

4 Answers 4

9

As I found out after googling my answer for How are labels used with statements that are not a loop?, the lonely code blocks can be related to labels:

myLabel:
{
    for(x in y) {
        break myLabel;
    }
}

Will break out not only of the loop, but of the outer code block as well.

4
  • Actually, after thinking about it some I'm not sure that this is technically the correct answer. By Labeling the code block, you might not consider it to be strictly lonely: instead of a for or function etc. it's attached to a label.
    – Jeff
    Commented Jan 10, 2012 at 2:35
  • I'll accept it anyways. ;) I actually learned something from this answer, when the others basically told me what I already knew. Commented Jan 10, 2012 at 2:42
  • Changing that break to continue and it fails to work when it should start executing at the top of the code block. Says undefined label! How's that, it was identified when the only difference was it being a break statement! Commented Feb 14, 2015 at 20:36
  • @user3015682: This explains the way continue label; works: developer.mozilla.org/pl/docs/Web/JavaScript/Reference/…. This is what you tried: jsfiddle.net/tadeck/9b1xeqsd. Try this instead: jsfiddle.net/tadeck/9b1xeqsd/1. The difference is that in your case you were not labelling the loop statement.
    – Tadeck
    Commented Jul 21, 2015 at 21:27
8

Update (as this question shows up high on Google for "javascript code block"):

With the introduciton of the let keyword in ECMAScript 6, code blocks can also be used to limit scope of variables.

{
    let x = 20;
    alert(x) // 20
}
alert(x) // undefined
3

Only code readability, nothing more.

They do not even give you the advantage of closures:

var c = 'fail';
{
    var c = 123;
}
alert(c); //alerts 123

(see it live)

4
  • What do you mean by visibility? Commented Jan 5, 2012 at 0:04
  • @PeterOlson: I mean code readability. This is useful only when reading the code, I know no other reason to do that.
    – Tadeck
    Commented Jan 5, 2012 at 0:06
  • 1
    There are probably some cases where it could be argued that it's more readable. Personally I would never use this syntax for JavaScript.
    – sissonb
    Commented Jan 5, 2012 at 0:11
  • 1
    @sissonb: I also never use it - I try to write as readable code as possible, without using unnecessary "constructs". But the question was about the purpose of such blocks and in fact the only purpose can be (arguable) improvement of code readability. (Unless someone has made a mistake and assumed it will work as (function(){/* ... */})()). So, basically, there are two possible reasons: 1) readability, 2) mistake ;)
    – Tadeck
    Commented Jan 5, 2012 at 1:21
-1

Only readability. Other than that, nothing. Do not do this as it's not future-proof. The following will happily break:

"use strict";

var a = 3,
b = 4;
{
  a = 50;
  b = 50;
}
alert(a + b); //alerts 100

I used to use it myself as it allowed logical separation of functionality, but no longer do due to the above.

2
  • Wouldn't it be simpler and more maintainable to use code paragraphing to denote logical separation? Commented Jan 5, 2012 at 0:25
  • 1
    @PeterOlson -- I've used this mostly for larger scripts. Things like Program Config, Handle Command-Line Options, Error Handling, etc are all broken into their own sections and then wrapped with anonymous blocks. It "enforced" the idea that all code here belongs to a certain group of functionality. It looks very clean and clear when done properly
    – user578895
    Commented Jan 5, 2012 at 0:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.