1

I am trying to understand closures.

var a = 1; var g = function () { var a = a; return function() { console.log(a); } } g()(); 

As far as I know, the function invocation g()() should log the value of a, i.e. 1. But it is logging undefined on the console. I know my concept is weak somewhere, but am not able to figure out even after spending few hours. Can someone help?

2 Answers 2

1

JavaScript hoists var declaration in the entire function scope. The variable from the outer scope var a = 1 is overwritten.
The example is equivalent to this:

var a = 1; var g = function () { var a; // a is undefined a = a; // a = undefined return function() { console.log(a); } } g()(); 

Without initial value assignment, a is simply undefined. Later you assign the variable to itself a = a, which is a noop and a remains undefined.

For more information about variables hoisting, check this article.

Sign up to request clarification or add additional context in comments.

Comments

1

The problem is the line

var a = a; 

This is both declaring a locally scoped variable and assigning it to itself - it's not interacting with the global a. You need to use a differently named local variable:

var a = 1; var g = function() { var b = a; return function() { console.log(b); } } g()();

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.