0
<script>
    name = "Tim";
    function greet() {
      console.log(name);
      var name = "David" ;
    }
    greet();
</script>

Why does the result show "undefined"? I expected Tim or David.

Simon MᶜKenzie
  • 8,344
  • 13
  • 50
  • 77
user2507818
  • 2,719
  • 5
  • 21
  • 30
  • Here is the extensive explanation [http://stackoverflow.com/a/9085872/2413470][1] [1]: http://stackoverflow.com/a/9085872/2413470 – spring Jun 21 '13 at 07:20

2 Answers2

3

The first 'name' you declare is a global variable. Inside the function, you declare it again, so you lose the visibility of the global one. But you use the variable before it is defined.

name = "Tim";  // global name here
function greet() {
  // var name; // here name is automatically declared ( because of hoisting ) but undefined
  console.log(name);    // here you use name before it is defined
  var name = "David" ;  // here name is defined
}
greet();

Javascript has scope in functions, that's important. Google for 'javascript hoisting' it will help.

AntouanK
  • 4,880
  • 1
  • 21
  • 26
  • +1 Exactly. Javascript sees the re-declaration of the variable in the new scope, so it cancels out the original, but then it's used before it's set. – musicnothing Jun 21 '13 at 06:14
1

Chage it like this,

var name = "Tim";
function greet() {
  console.log(name);
  name = "David" ;
}
greet();
Chamika Sandamal
  • 23,565
  • 5
  • 63
  • 86