0

I am trying to use callMe in following code. But my output is coming as undefined.if I remove last console.log(myGreeting); from functopn then it printing "Hello" How it works and why its coming undefined.

var myGreeting="Hello";
function callMe(){
console.log(myGreeting);
var myGreeting = "HI";
console.log(myGreeting);
}

8
  • You aint calling callMe function, are you? No logs...running the snippet. Commented Aug 9, 2016 at 7:02
  • have you called this callMe() or not on any event?? Commented Aug 9, 2016 at 7:05
  • I did not. And that'w why I asked how it is work. I was not clear with msdn doc. Commented Aug 9, 2016 at 7:06
  • so it will console like first will be undefined and then second will be Hii Commented Aug 9, 2016 at 7:07
  • does it run like it? Commented Aug 9, 2016 at 7:07

1 Answer 1

3

JavaScript has 2 scopes, local and global. Local Scope is the every function's scope. If you have 2 variables with the same names which one is in the funciton's scope, it will first access to it's scope. So in your example the outer myGreeter is hidden for the function.Any variable that is defined as var works with hoisting. So your code translates into this one

var myGreeting="Hello";

function callMe(){

   var myGreeting; // which is undefind

   console.log(myGreeting); // undefined

   myGreeting = "HI";

   console.log(myGreeting); // HI
}

In which every variables with var keyword and functions declaration are moved to the top of the function.

For more see here https://www.sitepoint.com/demystifying-javascript-variable-scope-hoisting/

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

8 Comments

@shanky singh see here
yes I am reading the doc. Thanks for answer.
@SurenSrapyan In call function why we need to declare variable. Can not we access global variable.
@shankysingh Of Course we can, in your code you have declared inside the function. You can remove the inner's declaration and your code will work as you want
That I declare after first console.log(myGreeting); . You declare that one before which is coming as undefined. Any how I am getting undefined.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.