lundi 24 août 2020

Why does nested 'if' statement not work without braces?

After all these years using JavaScript I stumbled upon a mistake I made and it took quite some time to find. It has to do with nested if statement.

I have used the following a lot of times

for( i=0; i<n; i++)
    if(condition)
        //Do something in one line.

It works and I never had any problem whatsoever with this. The fact that this pattern works seems to imply that the if and one subsequent conditional statement is considered as one single statement.

Until I did this:

if(condition1)
    if(condition2)
        //Do something in one line.

Now the one liner after the second if will not get executed, not even if I write it in the same line with that if. (If I know my stuff, then it shouldn't matter either way.)

I'm curious as to why this happens. It would have worked if I wrote a single statement without braces after the first if. Am I wrong in assuming that the an if statement followed by a one-liner is not considered as a single statement?

Note : I do realize that I could just do the following -

if(condition1 && condition2)
    //Do something in one line.

I'm just curious as to why subsequent if s won't work without braces. And at the time it didn't occur to me to merge the conditions because I never noticed the if which I nested, which I inserted at a different point of time.

Aucun commentaire:

Enregistrer un commentaire