Consider this code snippet:
var x = 10;
for (var i=0; i<100; i++) {
if (x === 10) {
/* do some stuff */
}
}
The condition within the if-statement is static except for x
, whose value is evaluated only once just before entering the loop. This value could come from anywhere - it can be hard coded, an input from the user, the result of a math problem, etc. The point is that once x
is evaluated, it doesn't change. Therefore, the condition inside the if-statement would be the same at every loop iteration, but the code clearly evaluates the condition nonetheless, wasting processing cycles in the process. Is there a way to make the condition evaluate once and have every iteration afterwards immediately execute the right code branch?