lazeevv
lazeevv

Reputation: 55

Explaining variable scope in JavaScript

This is simple, but I cannot understand why it does not work.

var a = function() {
	console.log(c); // "10" is expecting, but it is not defined
};

var b = function() {
	var c = 10; // local variable, but it is accessibly for b(), I think
	a();
}();

Why is variable c not defined? And how can I resolve this problem without passing c into b() as an argument?

Upvotes: 0

Views: 57

Answers (5)

woland
woland

Reputation: 129

function inherits parent scope where it was declared, not where it was called. All functions inherit window scope, so you can just make variable c global.

var a = function() {
    console.log(c); // "10" is expecting, but it is not defined
};

var b = function() {
    c = 10; // local variable, but it is accessibly for b(), I think
    a();
}();

Upvotes: 0

Arif
Arif

Reputation: 1643

you forgot to add parameter to function a

var a = function(c) {
    console.log(c); // "10" is expecting, but it is not defined
};

var b = function() {
    var c = 10; // local variable, but it is accessibly for b(), I think
    a(c);
}();

Upvotes: 1

Ben
Ben

Reputation: 683

The function a has a new scope in which c isn't defined. You could define var c = 0; outside of a or pass c as argument to a.

Upvotes: 1

Katana314
Katana314

Reputation: 8610

The question is better viewed from the other side. Why would it be defined? a wouldn't really be so reusable with a comment saying "NOTE: You can only run this function if you have a var c declared in the encompassing function". That's just not very discoverable, and means it's very hard to track how long a certain naming scope is used.

A feature of JavaScript that may do what you desire is "closures". This is when you declare an entire function inside of another; it's very handy for callbacks when you don't feel the second function deserves its own naming and place in the code structure.

What will happen here is that the language will automatically see that it needs c (already declared) inside of the function you're declaring, and so it preserves an internal reference to it, associated with the callbackFunction variable. So, you can still refer to it in there.

var b = function() {
    var c = 10; // local variable, but it is accessibly for b(), I think
        var callbackFunction = function() {
           console.log(c);
        };
        // optionally, place c in a setTimeout, ajax callback, etc.
    callbackFunction();
}();

Upvotes: 1

Gene R
Gene R

Reputation: 3744

this way:

var c = 0;
var a = function() {
    console.log(c); // "10" is expecting, but it is not defined
};

var b = function() {
    c = 10; // local variable, but it is accessibly for b(), I think
    a();
}();

Upvotes: 1

Related Questions