-3

Why JavaScript shows "undefined" alert in the 1st line of of r() in the below snippet?

Image contains HTML & JavaScript code

Albert Einstein
  • 7,472
  • 8
  • 36
  • 71

2 Answers2

1

You need to remove the var from the b in the r function. You cant set a local variable with the same name as global.

function r() {
    alert(b);
    b = "another stuff";
    alert(b);
    alert(window.b);
}
Albert Einstein
  • 7,472
  • 8
  • 36
  • 71
finnishNinja
  • 91
  • 1
  • 5
0

Look this: question, point 7. JavaScript always moves variable declarations (not initializations) to the top of the scope.

Dizip
  • 85
  • 7