Vivek m
Vivek m

Reputation: 55

Why does the function below log undefined to the console? Shouldn't it throw an error like a is not defined?

function first() {
   var a = "Hello";
   console.log( this.a );
}

first(); // undefined

Why does the function below log undefined to the console ? Shouldn't it throw an error like a is not defined ?

Upvotes: 0

Views: 365

Answers (3)

Alex S.
Alex S.

Reputation: 632

You need use this instead of var.

function first() {
    this.a = "Hello";
    console.log(this.a);
}
first(); // "Hello"

If you want to create variable in the scope of object first, then modify the code like

function first() {
    this.a = "Hello";
    this.b = function() {
        console.log(this.a);
    }
}
obj = new first;
obj.b();

Upvotes: 0

Akxe
Akxe

Reputation: 11575

In non strict mode, this will refer to window, therefore this.a will equal to window.a.

Try this with 'use strict' at first line.

// Original
function first() {
  var a = "Hello";
  console.log(this == window)
}
first();

// Strict example
(function(){
  'use strict'
  function first() {
    var a = "Hello";
    try {
      console.log(this.a)
    } catch(e){
      console.log(e.message)
    }
  }
    first();
})();

// Class-like example
function First() {
  this.a = "Hello";
  console.log(this.a)
  return this
}

new First();

Upvotes: 4

Nikhil Aggarwal
Nikhil Aggarwal

Reputation: 28475

As you said a is not defined it will mean that it is undefined. Whenever, you try to access property from an object and if the object does not exist then the error will be thrown, however, if the property does not exist, then undefined will be returned.

In the said example, try and run in browser console and log this, it points to window object. Hence, this.a will try to access the property from window object, which not found will return undefined.

var a = "Hi";

function first() {
  var a = "Hello";
  console.log(this.a)
}
first(); // Hi

Error scenario

function first() {
  var a = "Hello";
  console.log(obj.a) // throws error
}
first();

Upvotes: 0

Related Questions