Question

In javascript I get confused with the nested if's elses

when a JS compiler/engine has this code to interpret

if (cond1)
if (cond2)
statement1
else
statement2

(It is not indented on purpose)

Does it gets interpreted like this?

if (cond1) {
  if (cond2) {
    statement1
  }
}
else {
  statement2
}

Or like this?

if (cond1) {
  if (cond2) {
    statement1
  }
  else {
    statement2
  }
}

The question would be: Do the 'else' corresponds to the first or second 'if'?

I would like to know also if this problem of interpretation has some name (like 'operator precedence') (I'm sure it has). I can't find this issue in internet, because I don't know how to search for it by its name.

It might be a little obvious, but I'm going to say it: I ask about javascript because I'm using it right now, but this question could be about almost any procedural language.

Était-ce utile?

La solution

it should be the second one in JS. It would throw an error in python and get your nose punched in php as soon as a colleague debugs your code.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top