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

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

1

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

+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.
0

Chage it like this,

var name = "Tim";
function greet() {
  console.log(name);
  name = "David" ;
}
greet();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.