Search code examples
javascriptecmascript-6block

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()


Solution

  • 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.