0

Why is abc undefined in first output, then printed out in the final console.log ? I would expect hello world hello...

var abc = 'hello';

function test() {
  console.log(abc);

  var abc = "world";
  console.log(abc);

}

test();
console.log(abc);
mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • Because `var abc;` is *hoisted* to the top of the function. – jonrsharpe May 13 '20 at 14:13
  • 1
    It is undefined because local `var` variables are hoisted to their functions. So the local `abc` doesn't have a value until you give it one – Taplar May 13 '20 at 14:14
  • When a specific variable defined in a local scope, any reference of it will looking for a value of the local variable, which mean (for the references before initialization) `undefined` if the variable sefined as `var`, or *throw error* if the variable defined as `let` – Yosef Tukachinsky May 13 '20 at 14:16
  • I'm really struggling to understand this concept. Thanks for your clarifications. – Ben Leonard May 13 '20 at 14:20

0 Answers0