Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the purpose of lonely code blocks in Javascript?

Tags:

javascript

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?

like image 825
Peter Olson Avatar asked Jan 04 '12 23:01

Peter Olson


People also ask

What is the purpose of code blocks in JavaScript?

JavaScript statements can be grouped together in code blocks, inside curly brackets {...}. The purpose of code blocks is to define statements to be executed together.

Can I use code blocks for JavaScript?

JavaScript Code BlocksCode blocks can exist anywhere in your script. In fact, if you wanted to you could make a script that's just a single code block, and do everything in JavaScript.

Does JavaScript have block scope?

With ES2015, in addition to function-level scoping, JavaScript also supports block-level scoping with the help of the let keyword & const keyword.

What is function scoped and block scope in JavaScript?

Function Scope: When a variable is declared inside a function, it is only accessible within that function and cannot be used outside that function. Block Scope: A variable when declared inside the if or switch conditions or inside for or while loops, are accessible within that particular condition or loop.


2 Answers

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.

like image 142
Jeff Avatar answered Sep 20 '22 08:09

Jeff


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
like image 40
Johannes H. Avatar answered Sep 20 '22 08:09

Johannes H.