max fraguas
max fraguas

Reputation: 438

JavaScript function variable scope

In the following code, why can I access the variable x.b? Shouldn't it have a local scope?

CODE

function x() {
    var a = 3;
}


x.b = 8;

console.log(x.a);
console.log(x.b);

OUTPUT

undefined
8

Upvotes: 3

Views: 111

Answers (3)

Lasantha Basnayake
Lasantha Basnayake

Reputation: 379

You have defined x.b to 8 and it becomes a global var. Which means you can access it from anywhere.

So the x() is a function which has its own scope. So you can't access the vars inside a function scope in the mentioned way. However you can access the 'a' by doing this and calling the x function.

function x() {
  var a = 3;
  return a;
}

Upvotes: 0

Keyur Kamdar
Keyur Kamdar

Reputation: 46

Javascript considers x.b as a global object. so you can access it even inside the function like:

x.b = 8;
function x() {
    var a = 3;
    alert(x.b)
}
x();
console.log(x.a);
console.log(x.b);

But make sure you specify x.b before function declaration.

whereas object a is specified inside the function x() which makes it private thats why you are getting undefined result for console.log(x.a);

if you write it like this:

a = 5;
function x() {
    var a = 3;
}
x.b = 8;

alert(a);
alert(x.b);

you will get results as bellow:

5
8

for javascript a and x.a are two separate objects.

Upvotes: 0

Samuel Toh
Samuel Toh

Reputation: 19228

When you use var to declare a within x's constructor, a is mark as private, however when you do x.b you are essentially saying - add the property b to the object x.

Hence when you do x.b, technically speaking you are accessing object x's property b, which is 8.

Upvotes: 3

Related Questions