Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is this anonymous block in javascript ES6?

I am reading about new ES6 features from pragmatists. but here as you can see that they used an anonymous block in that function. Can someone please explain what is meaning of that. Is it any javascript object or what? How can we use that? Please also mention some reference for that.

function f() {
  var x = 1
  let y = 2
  const z = 3
  {
    var x = 100
    let y = 200
    const z = 300
    console.log('x in block scope is', x)
    console.log('y in block scope is', y)
    console.log('z in block scope is', z)
  }
  console.log('x outside of block scope is', x)
  console.log('y outside of block scope is', y)
  console.log('z outside of block scope is', z)
}

f()
like image 249
imrvasishtha Avatar asked Jan 24 '26 01:01

imrvasishtha


2 Answers

From docs:

The block statement is often called compound statement in other languages. It allows you to use multiple statements where JavaScript expects only one statement. Combining statements into blocks is a common practice in JavaScript. The opposite behavior is possible using an empty statement, where you provide no statement, although one is required.

Blocks are commonly used in association with if...else and for statements.

Based on your example:

function f() {
  const z = 3
  
    const z = 300
  
  console.log('z outside of block scope is', z)
}

f()

Without using block scope we get error like:

SyntaxError: redeclaration of const z

And with block scope:

function f() {
  const z = 3
  {
    const z = 300
    console.log('z in block scope is', z)
  }
  console.log('z outside of block scope is', z)
}

f()

same code works fine. Note that the block-scoped const z = 300 does not throw a SyntaxError because it can be declared uniquely within the block.

like image 143
Zuckerberg Avatar answered Jan 25 '26 14:01

Zuckerberg


Anonymous blocks are helpful when using let variable. Variables declared by var keyword are scoped to the immediate function body while let variables are scoped to the immediate enclosing block denoted by { }.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!