Premshankar Tiwari
Premshankar Tiwari

Reputation: 3106

When does the code inside if statement get executed?

Consider the following 3 scenarios.

var y = 1;
if (function f(){}) {
   y += typeof f;
}
console.log(y);     // "1undefined"

the above output indicates that function f(){} is just checked for its truthiness, but is not defined before the execution of if block.

var y = 1;
if (y--) {
   y += typeof f;
}
console.log(y);     // "0undefined"

However, here we get the value of y as 0, that means the expression inside if condition is executed before the if block. But shouldn't the if block be skipped as y-- evaluates to 0 which is a falsey value as in below.

var y = 1;
if (0) {
   y += typeof f;
}
console.log(y);     // "1"

Upvotes: 0

Views: 78

Answers (2)

deceze
deceze

Reputation: 522322

if (function f(){})

This doesn't define f because it's just a named function expression. Expressions don't declare a function in the local scope under the name f, so no f is being created.

if (y--)

The post-decrement operator first returns the value of y and then decrements it. Compare with the pre-decrement operator --y.

Those are the reasons you get the behaviour you get. When "if is executed" is irrelevant.

Upvotes: 2

Quentin
Quentin

Reputation: 943935

the above output indicates that function f(){} is just checked for its truthiness, but is not defined

A named function expression creates a variable which shares its name (f in this case) only inside its own scope.

You never create a variable f which is in a scope accessible to your y += typeof f; statement.


But shouldn't the if block be skipped as y-- evaluates to 0

y-- doesn't evaluate to 0.

It evaluates to 1 and then decrements y to 0.

Upvotes: 3

Related Questions