2

So I was testing scope of JavsScript (var, let, and const), and I found a weird behavior that I couldn't really understand.

var write = document.getElementById('demo');

function test() {
    var m = 'hello';
}

test();

write.innerHTML = m;
//This doesn't work

In above case, JS cannot accesses var m declared locally from global scope.

var write = document.getElementById('demo');

if(true) {
    var m = 'hello';
}

write.innerHTML = m;
//This works

In above case, JS accesses var m declared locally from global scope.

Can someone explain why that is..?

Kev
  • 103
  • 4

2 Answers2

3

It is because of Hoisting. Also var has function level scope

var write = document.getElementById('demo');
var m; // m will be undefined here, declared but not initialized
if (true) {
  m = 'hello'; // m is initialized her
}

write.innerHTML = m;
<div id='demo'></div>
brk
  • 48,835
  • 10
  • 56
  • 78
2

In the first case, var declaration is scoped at function level and thus its limited to function test

In the second case, if scope is block scope and hence var declaration escapes into the global scope due to Hoisting

Thus in the first case you can't use m outside function test but you can do so in the second case.

Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400