Search code examples
javascriptscopevariable-assignmentdestructuringhoisting

Object destructing in if-condition results in global variable?


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!


Solution

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