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!
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>