3

Can anyone tell me why this logs 11, instead of 9?

function foo() {
  function bar(a) {         
    i =3;
    console.log( a + i );     
  } 

  for (var i=0; i<10; i++) { 
    bar( i *2 ); 
    //I know, infinite loop
  } 
} 

foo();

If i is hard-coded in bar(){}, shouldn't the logged result be 9?

This is part of a Scope class and I am lost.

Thanks.

3
  • Possibly something to do with i being used in both the bar function and in the for loop? Commented Jun 16, 2016 at 15:00
  • 1
    @Rocket, yup, missed the hoisting of i to the start of foo(). Commented Jun 16, 2016 at 15:01
  • Yes, I fixed it declaring var i =3; instead. Commented Jun 16, 2016 at 15:46

2 Answers 2

6

In the first iteration, i is 0 which is smaller than 10. 0 (2 * i) is passed as a to bar. i gets set to 3, then the sum is 3.

In the next iteration, i is incremented to 4 (which is still smaller than 10), then 8 (2 * i) is passed as a to bar. i gets reset to 3, then the sum is 11.

The next iteration is the same, i is incremented from 3 to 4 again and so on.

Your misunderstanding seems to be that the value of a doesn't change because i gets changed, the multiplication is evaluated first. Or you just missed the i++ statement in the loop header.

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

3 Comments

I believe the part where he got stuck (and I can understand why) is because he thought i would always be 3 from then on, indeed.
Yes, @Stephan, that's what I thought. Also, to fix the infinite loop I declared var i=3; instead.
Thanks, @Bergi, that's it. It makes sense now.
1

@Bergi has the right answer, I just want to expand on it a bit. For primitive types like a string or number the parameter is passed by value. Here you are passing i into bar as the value a. Any changes to i or a will not effect the other's value. This also will not give you an infinite loop as the values for i in this case are [0, 4,5,6,7,8,9]

Now if i had been wrapped inside of an object that was passed to foo then you would have the problem you are asking about. Objects passed to javascript functions are passed by reference, so changes to the object in bar also happen in foo.

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.