2

Can someone explain to me why I can access "m" in global scope in the following scenario:

const a = {m: 'beeb'};


const magic = function topLevel () {
   function lowerLevel() {
    if ({m} = a ) { 
      console.log('in lowerLevel-func: ', m);
    }
  }

  lowerLevel();
}


magic();

console.log('in global', m);

and here is JSFiddle

Edit: Just to clarify, I am not using this anywhere, I was just wondering how it was possible. Now I know, thanks!

Yellowhill
  • 115
  • 6

3 Answers3

1

If you assign a value to a variable that has not been declared, it will automatically become a GLOBAL variable. And since you are doing =(Assigning) instead of ==(compairing)

<!DOCTYPE html>
<html>

<body>

  <p>
    If you assign a value to a variable that has not been declared, it will automatically become a GLOBAL variable:
  </p>

  <p id="demo"></p>

  <script>
    myFunction();

    // code here can use carName as a global variable
    document.getElementById("demo").innerHTML = "I can display " + carName;

    function myFunction() {
      carName = "Volvo";
    }
  </script>

</body>

</html>

References

Also Read What is the scope of variables in JavaScript?

Sanchit Patiyal
  • 4,910
  • 1
  • 14
  • 31
  • This states a general rule of the language, it doesn't answer this specific question. – axiac Feb 26 '18 at 12:34
  • 1
    Yeah, I am aware of scopes etc. I just did not know that undeclared variable becomes part of global scope automatically. Thanks. – Yellowhill Feb 26 '18 at 12:42
1

It happens because you never explicitly declared (with var, let or const statements) m variable, so it becomes a property of the global Window object (that's why you can access it from anywhere in your code). It would be the explanation if you intended to assign a value to m inside if statement and not to compare.

Note that if you do the same in strict mode, you won't get such behaviour as it doesn't allow to use variables that have never been declared.

oniondomes
  • 2,034
  • 13
  • 22
1

You observe this behaviour because you are making an assignment to a previously non declared variable and you are executing your code in non-strict mode.

The line:

if ({m} = a ) { 

Is effectively an assignment of the m field of the variable a to a variable m. Now because m has not been previously declared nor exists in the global scope two things can happen:

  • in non strict mode this degenerate into an assignement to window['m'] which makes it available globally
  • in strict mode you get a reference error.

Imo the last behaviour should be the behaviour you should be targeting as it is (imo) the least "surprising" one.

adz5A
  • 2,012
  • 9
  • 10