0

Can you guys please explain why this function logs "undefined world" ??? I'm confused...

var a = 'hello';
function b() {
  console.log(a);
  var a = 'world';
  console.log(a);
}
b();
  • 1
    The good thing about `var` is that you don't actually need to understand how it works because you should never use it. Use `let` and `const` instead. – Guillaume Brunerie Sep 28 '22 at 09:12
  • Altought what @GuillaumeBrunerie mentioned is true, it doesn't answer the question. – Thiago Romano Sep 28 '22 at 09:13
  • The real reason of why it is happening is that `var` variables are hoisted, it means that the declaration is moved to the top of the enclosing function, so Javascript actually runs a `var a = undefined;` just at the beginning of the function. – Thiago Romano Sep 28 '22 at 09:15
  • As can be seen here: https://stackoverflow.com/questions/30469755/why-a-variable-defined-global-is-undefined – Thiago Romano Sep 28 '22 at 09:16
  • thank you guys so much! I'm trying to become a JS trainee and this var thing is in the test, so i have to learn it :c – Why cry when you can code Sep 28 '22 at 09:56

0 Answers0