<script>
name = "Tim";
function greet() {
console.log(name);
var name = "David" ;
}
greet();
</script>
Why does the result show "undefined"? I expected Tim or David.
<script>
name = "Tim";
function greet() {
console.log(name);
var name = "David" ;
}
greet();
</script>
Why does the result show "undefined"? I expected Tim or David.
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.
Chage it like this,
var name = "Tim";
function greet() {
console.log(name);
name = "David" ;
}
greet();