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?
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.
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.
With ES2015, in addition to function-level scoping, JavaScript also supports block-level scoping with the help of the let keyword & const keyword.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With