简体   繁体   中英

Javascript Closure: function returning “undefined” instead of a value

I am trying to learn JavaScript closure and got confused by an output. I am sure that this should be easy and quick to answer. When I run following code snippet, I get "undefined" as an output.

function foo(){
    var x = 5;
    function bar(){
        return x; // returning value of x
    }
    baz(bar); // output is "undefined"
}

function baz(fn){
    fn();
}

However if i run following code, then correct value of x is printed on console.

function foo(){
    var x = 5;
    function bar(){
        console.log(x); // printing value of x on console
    }
    baz(bar); // output is 5
}

function baz(fn){
    fn();
}

So i am confused as to why when value of x is returned output is "undefined", but when value of x is printed on console then correct value of x is printed. Really appreciate if someone can explain this behavior.

Modify Your code to this :-

function foo(){
var x = 5;
function bar(){
    return x; // returning value of x
}
return baz(bar); // returns 5
}

function baz(fn){
  return fn();
}
console.log(foo())

You were not returning the values returned by "bar" function in your "baz" function, and also "foo" function should return the value returned by baz function.You can hold it in a variable or console the value returned by foo.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM