Search code examples
javascriptobject-literal

How javascript allows object key type syntax without including ir inside a literal and also variable declaration inside it?


While running these statement in chrome console or inside script tag what I found is that the below syntax which I thought is invalid is working and all the varaibles were exposed globally which I understand could be due to curly braces are interpreted as block but that key: in front is what confuse me. But I am not sure why and looking for an explaination.

    foo: {
      a = 5,
      b = 6
    }

    console.log(a) output --->  5
    console.log(b) output --->  6


    foo: {
      a = 5;
      b = 6;
    }

    console.log(a) output --->  5
    console.log(b) output --->  6


    foo: {
      a: 5;
      b: 6;
    }

    console.log(a) output --->  5
    console.log(b) output --->  6


Solution

  • That's because foo: is interpreted as a label and your "ObjectLiteral" get's interpreted as block and the statements inside get executed.

    Your code boils down to the following.

    a = 5,
    b = 6
    

    Since you don't have any declaration like var, let, or const you're setting a global variable a and b