0

Let I have a simple code

{
  let i = 10;
  function outer() {
    let j = 20;
    console.log(i, j);
  }
  let inner = outer();
}

And the output is

10 20

which is obvious. But I thought I only stored the function value in inner, but never called it. Then why is it logging the output to the console?

3
  • 1
    You called the function let inner = outer(); Commented Jul 20, 2020 at 5:03
  • 2
    Not sure what exactly you want to know. You call the function right there in your code. inner is equal to the return value of your outer function: undefined. If you want to copy the reference to your function, you’d use let inner = outer; instead. Commented Jul 20, 2020 at 5:05
  • Thank you for your clarification. I almost forgot that bracket part. Commented Jul 20, 2020 at 5:07

2 Answers 2

1

let inner = outer() => executes the function

let inner = outer => save the function to inner

As you can see the difference is the parentheses.

When you use parentheses, you are saying execute this function.

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

Comments

1

The outmost braces just indicate they make a "code block", not a function body.

In outer function, it initializes a local variable 'j' and refer to a external variable i. And you called the function with let inner = outer().

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.