0

I tried to search it on internet but didn't got any answer. Why access of two variables before declaration have two different outputs:

function test() {
    console.log(a); // prints 'undefined'.
    console.log(b); // prints 'b is not defined'.
    var a = 5;
    this.b = 10;
}
Ravinder Kumar
  • 622
  • 5
  • 16
  • 1
    [variable hoisting](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var#var_hoisting) – Darin Dimitrov Feb 26 '17 at 06:58
  • A block of code does not constitute a question. You should declare the question in there so people can better target their answers. – Chris Feb 26 '17 at 07:27
  • 1
    @RavinderKumar, you'll want to look at variable hoisting as Darin Dimitrov pointed out. The code is initially ran through for declarations. This allows things like variables and functions to be called prior to them being hit in run-time. Since this.b is an assignment and not a declaration, you end up seeing that it is not defined. – Chris Feb 26 '17 at 08:06

3 Answers3

0

when you write a variable with var like var a it become a function level variable. so now a is a variable which is present there before consol.log(a) and its not given a value so its undefined for b there is no variable defined with name b before it called.

And which all variables are defined with var will be function level variable and will be created before anything else in the function. so a will be present in the function at the starting itself.

and here this will be holding the object of Windows.

0

when you declare var variable inside the function then that variable is limited to that function. That mean scope of that variable is limited to that function so you can't access that variable outside of that function.

But if you use this then it can be access through outside but then again you need to create a object of that class/function and access trough it.

function test() { 
    var a = 5;
    this.b = 10;
  
   this.printB = function(){
     return this.b;
    
    }
    
    this.printA = function(){
     return a;
    }
}

var obj = new test();
console.log(obj.a)
console.log(obj.b)
console.log(obj.printA())
console.log(obj.printB())
Sachila Ranawaka
  • 28,742
  • 4
  • 48
  • 69
-1

First of all, you are trying to examine the variables before you declared them. This is the correct order:

function test()
{
  var a=5;
  this.b=10;

  console.log(a); // Should print 5
  console.log(b); // Should print undefined
  console.log(this.b); // Should print 10
}

Second, regarding your question, declaring a var inside your function, make is a local private variable inside your function. declaring this.b, will cause b to be in a different scope, and b for itself as undefined. If you want to use b inside the function, use this.b.

Koby Douek
  • 14,709
  • 15
  • 58
  • 84