1
var name="prevName";
function printName(){
   console.log(name);
   var name="newName";
}
printName();

prints undefined

var name="prevName";
function printName(){
    console.log(name);
}
printName();

prints prevName

I don't understand why

could you please anyone Explain why??

Thanks in advance....

  • See the linked duplicate(s)' answers. In your first example, you're printing the **local** `name`, which has the value `undefined` as of where you're printing it, exactly as though the code looked like this: `var name="prevName"; function printName() { var name = undefined; console.log(name); name="newName"; } printName();`. In your second example, you're printing the `name` that `printName` closes over, since you haven't declared it locally. – T.J. Crowder Nov 03 '18 at 11:15

2 Answers2

1

In the first case the inner var name (which is different from the global name) gets hoisted to the function top. So it's the same as

var name = "prevName";
function printName(){
   var name; // name = undefined
   console.log(name);
   name = "newName";
}
printName();

In second case, you address the global variable.

Nikita Skrebets
  • 1,518
  • 2
  • 13
  • 19
1

Variables in JavaScript (and function declarations) get hoisted, i.e. their declaration moves at compile time, up to the start of their scope (either the function their in, or module). But the assignment does not get hoisted. That is why the first function prints undefined - the local variable replaces the outer one, but it’s undefined until after the log is called.

William
  • 741
  • 4
  • 9