You-dont-know-js: May be a calculate error

Created on 17 Mar 2018  路  1Comment  路  Source: getify/You-Dont-Know-JS

I found calculate error in section interleave of Chapter 4: Generators.

Before I tell you the results, can you figure out what a and b are after the preceding program? No cheating!

console.log( a, b ); // 12 18

b i got here is 24. See my step list:

// make sure to reset a and b
a = 1;
b = 2;

var s1 = step( foo );
var s2 = step( bar );

s2(); // b--; a 1 b 1
s2(); // yield 8 a 1 b 1
s1(); // a++; a 2 b 1
s2(); // a = 8 + b; a 9 b 1
// yield 2
s1(); // b = b * a; a 9 b 9
// yield b
s1(); // a = b + 3; a 12 b 9
s2(); // b = a * 2; a 12 b 24

Correct me if i was wrong.

Most helpful comment

You're correct up until the last step... because of the left-to-right evaluation of expressions, the a in a * 2 is evaluated to value 9 before that yield 2, so that subsequent update of a to 12 is not seen by that multiplication. Instead, it's 9 * 2, which is 18.

>All comments

You're correct up until the last step... because of the left-to-right evaluation of expressions, the a in a * 2 is evaluated to value 9 before that yield 2, so that subsequent update of a to 12 is not seen by that multiplication. Instead, it's 9 * 2, which is 18.

Was this page helpful?
0 / 5 - 0 ratings