I wonder if I put an object creation in a if, will it take resources even if the if isn't true?

For example, in the following code:

if (foo) {
    doSomething({
        option1: aVeryLongCallToGetThisValue(),
        option2: idem()
    });
}

If foo is false, will JS optimize it and skip the creation of the object containing option1 and option2 (this snippet is supposed to be called many times)? Furthermore option1 and option2 depend on the context (imagine a variable passed to aVeryLongCallToGetThisValue so I can't compute it once for all beforehand.

1 Answers

0
melpomene On

If foo is false, will JS optimize it

That's not so much optimization as it is basic execution semantics. That is, conditional execution is just what if does. If the condition is not true, none of the statements in the if body are executed and none of its effects happen.

This is true in all programming languages. It's a very fundamental feature.