1

In chapter 4 of Professional JavaScript for Web Developers by Nicholas C. Zakas, author says that function arguments follow the same access rules as any other variable in the execution context. For that, I tested the follows code:

function n1(num1, num2) {
   function n2() {
      var num3 = (num1 + num2);
      console.log(num3);
   }
}

I called n1() function with: n1(1, 2). I thought that the result would be 3, but I get undefined.

Why this behavior?

1 Answer 1

4

Neither n1, nor n2 doesn't return anything (that's where undefined comes from). Additionally, n2 is never called. If you want to get 3 from n1(1, 2) you have to modify it something like this:

function n1(num1, num2) {
   function n2() {
      var num3 = (num1 + num2);
      console.log(num3);
      return num3;
   }
   return n2();
}
Sign up to request clarification or add additional context in comments.

3 Comments

Oh! That's right! Too obvious and I couldn't see it! Thanks a lot Pavlo!
BTW, can you modify the return statement in n2() function? It must be "num3". I tryed but the edit must be 6 characters at least.
@leoMestizo—edit with say 10 spurious characters, then edit again to remove them.

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.