1

I have the following code:

var myFriend = 'David';
function Hi(){
   var myFriend = 'Emma';
   console.log(global.myFriend); //prints undefined
}
Hi();

I am trying to access the global variable myFriend inside the function. I am unable to understand why it is printing undefined. Can someone please explain?

nehacharya
  • 925
  • 1
  • 11
  • 31
  • 1
    When you say `returns undefined`, do you mean that it **prints** the word "undefined"? The word "return" has a technical meaning in programming that isn't related to what you are doing here. – Code-Apprentice Apr 30 '18 at 16:21
  • 3
    What environment are you running this in? – T.J. Crowder Apr 30 '18 at 16:21
  • @Code-Apprentice, yes it prints undefined. – nehacharya Apr 30 '18 at 16:23
  • 1
    @T.J.Crowder environment is Node.js – nehacharya Apr 30 '18 at 16:28
  • 1
    Cool, thanks for confirming. Then the problem is that your code is being run at module scope, not global scope, and so `var myFriend` is not creating a global. Node.js runs your code in a module scope by default. See the linked question's answers for more details. Happy coding! – T.J. Crowder Apr 30 '18 at 16:33
  • 1
    @T.J.Crowder I understand now. Thanks! – nehacharya Apr 30 '18 at 16:40
  • 1
    If you remove the first `var` keyword you would be assigning to an implicit global and it would log `David` as expected. Also if you log `global.myFriend` immediately after the first statement, you would get the same behaviour as you do in the closure. – Paul Apr 30 '18 at 16:43
  • @Paulpro You are right. I just tried out your solution and it worked. Thanks :) – nehacharya Apr 30 '18 at 16:46
  • I kind of disagree that this is a duplicate question -- although there are helpful details in the linked answer, asking 'why is this a thing" and 'what is the default' are two different things -- the latter implies more knowledge of what's going on, and the asker of the former wouldn't search for those words. – Hannele May 01 '18 at 01:23

0 Answers0