Question on this Function

Question on this Function
0.0 0

#1

Hey folks, I have a question on this function that has me confused for the whole day now. Maybe I’m just looking at it wrong or doing the calculations wrong. I am reading up on the Book 2 Scope and Closure of YDKJS and in Chapter 3 on topic “Hiding In Plain Scope” the author writes the function:

function doSomething(a) {
	function doSomethingElse(a) {
		return a - 1;
	}
	var b;
	b = a + doSomethingElse( a * 2 );
	console.log( b * 3 );
}
doSomething( 2 ); // 15

Shouldn’t this return 12 instead of 15?

I’m thinking its doSomething(2) so a = 2,
so it should be b = (2 + doSomethingElse((2 - 1) * 2)), which is 4.
Then console.log(b * 3) would be 4 * 3 = 12.

Confused…any clarification would be greatly appreciated.


#2

Your math is wrong in b = (2 + doSomethingElse((2 - 1) * 2)).

b = a + doSomethingElse( a * 2 )
b = 2 + doSomethingElse( 2 * 2 ) // a==2
b = 2 + doSomethingElse( 4 ) // 4 gets sent 
b = 2 + 3   // the function call returns 3
b = 5

The subtraction in doSomethingElse happens after the function call, not before. The number 4 gets sent to doSomethingElse, not 3. 4 gets sent and then 3 gets returned.


#3

Ah ok I see now. I was thinking everything in the function occurred first. Forgot about the different scope and how JS reads it. Thanks for the clarification.


#4

Right, the function call on line 6 is sending that value a*2 and at that moment a is 2. The function doSomethingElse has been declared but not called. Nothing happens until the function is called. You could have put the declaration after the function call and it would have worked the same:

function doSomething(a) {
  var b;
  b = a + doSomethingElse( a * 2 );
  console.log( b * 3 );
  function doSomethingElse(a) {
    return a - 1;
  }
}
doSomething( 2 ); // 15

You also could have put the declaration of doSomethingElse outside of doSomething and it wouldn’t have mattered - as long as it’s in the scope of where it’s called.


#5

I cleaned up your code.
You need to use triple backticks to post code to the forum.
See this post for details.


#6

Ok thanks ArielLeslie