JavaScript closures and an unexpected - undefined - return

Viewed 77

while I'm trying to understand JS closures, i wrote this code :

const outer = function() {
  let a = 10, c = 100;
  const inner = function() {
    let b = 20;
    console.log(a + b); // line 5 (30)
  };
  return inner;
};
let K = outer();
console.log(K()); // line 10 (undefined)

The console's output:

30 ( line 5)

undefined ( line 10 )

the console outputs the result ( 30 )

and it points to (line 5) of the code ( this seems reasonable for me ) after that ( and that's what I didn't understand) it returns undefined when it gets back to the last line of code ( line 10 ) Anyone can clarify this JS behavior?

1 Answers

In your code, K is the result of executing outer, which in this case is the function inner.

When you execute K (which has been assigned the function defined as inner earlier), you get the console output of 30, which is a + b.

However, you also log the return value of K, and because your inner function doesn't have a return value, you get undefined.

Try modifying your code to have inner return a value and you'll see what I mean:

const outer = function(){
    let a = 10, c = 100 ; 
    const inner = function(){
        let b = 20 ; 
        console.log( a + b ) ; 
        return a * b; // Without this return, the return value of inner is undefined.
    }
    return inner ; 
}
let K = outer(); 
console.log( K() ) ;
Related