0

I have been reading about closure in JS and I wouldn't say I understand it perfectly but at least having some knowledge about it after reading a few examples and info from different sites but I can't really understand why one of these is a closure and not the other one.

Not closure function

var secret = "007";

function getSecret(){
    var secret = "008";

    function getValue(){
        return secret;
    }

    return getValue();
}

getSecret();

Closure function

var secret = "007";

function getSecret(){
    var secret = "008";

    function getValue(){
        return secret;
    }

    return getValue;
}

var getValueFun = getSecret();
getValueFun();

both of them has the same output as I can realize the first one that's not a closure returns the function invoked and the closure one just returns the function. This is the only difference I can think of and is this part of the reason why one of them is a closure and not the other one?

Tsuna
  • 2,098
  • 6
  • 24
  • 46
  • Yes, that's the key difference. – Pointy Feb 01 '16 at 22:53
  • The first returns the result of the `getValue` function - the second returns the `getValue` function itself - hence why in the second example you need to execute `getValueFun()` to get the result of the first. – tymeJV Feb 01 '16 at 22:53
  • 1
    Who says [it's not a closure](http://stackoverflow.com/a/30252701/1048572)? – Bergi Feb 01 '16 at 23:01
  • A function that has a reference to the environment it was created in (or any environment really), is a closure. – Felix Kling Feb 01 '16 at 23:11
  • @Bergi would it make sense saying if an inner function returns all the free variables in the outer function, it's a closure? – Tsuna Feb 02 '16 at 01:11
  • @Tsuna: It doesn't need to return them. As soon as a function *uses* free variables, it's a closure. Of course it only becomes interesting when it leaves its scope (like being returned from the outer function) - your first example would work in languages without closures as well. – Bergi Feb 02 '16 at 01:14

1 Answers1

-2

// You can try this:

var secret = "007";

function getSecret(){
    var secret = "008";

    var getValueFunc = function(){
        return secret;
    }

    return {
         getValue:getValueFunc
   };
}

var getValueFun = new getSecret();
getValueFun.getValue();