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.

Was it helpful?

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top