-1

If a variable is declared but not initialized , it will print undefined in the console.But in this particular case if i console.log(this.name) inside Person function it should create a global variable called name whenever i invoke the function .But the global variable must be undefined, instead it is holding a empty string .I even checked the window object .It has a property called name which holds empty string.Why it is behaving this way ?

function Person(){
     
        console.log(this.name)
    
    } 
    
    Person() // should prints undefined ,but prints empty string

enter image description here

Liam
  • 27,717
  • 28
  • 128
  • 190
AL-zami
  • 8,902
  • 15
  • 71
  • 130

2 Answers2

3

That code doesn't create any global variable (other than Person, which is a kind of variable), it just tries to use one. But if you run it in a browser in the default loose mode, you see a string because browsers have a predefined name global: It's the name of the window in which the code is running. (If you ran it in strict mode, you'd get an error because this would be undefined during the call.)

If you run that not on a browser, or with a different name (one that isn't already a global), you'll see undefined.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • Say i have used username instead of name.How come it doesn't get attached to window object? can you explain? – AL-zami Sep 05 '17 at 16:24
  • 1
    @AL-zami: Because you're just *reading* the value of it. Reading the value of a non-existant property doesn't create the property, it just yields `undefined`. *Assigning* to a non-existant property creates the property. – T.J. Crowder Sep 05 '17 at 16:25
  • thanx, so if i assign a value to it like this.username = "donald duck" , then i will be creating a global variable ? – AL-zami Sep 05 '17 at 16:32
  • @AL-zami: Yes. Of course, it's best to avoid global variables... :-) – T.J. Crowder Sep 05 '17 at 16:32
0

There already exists a property name on the global object (window in the browser) which is an empty string, otherwise the value would certainly be undefined.