-3

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

Image contains HTML & JavaScript code

Kiran Shahi
  • 6,738
  • 6
  • 35
  • 66

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);
}
Kiran Shahi
  • 6,738
  • 6
  • 35
  • 66
finnishNinja
  • 91
  • 1
  • 5
0

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

Dizip
  • 75
  • 7