Click to See Complete Forum and Search --> : anyone know why this works?


ccoder
11-12-2003, 10:23 AM
I'm making some custom changes to the web-based portion of a Help Desk app that we purchased. While working on one of the requested changes, I came across some code that I would have said can't work. But it does. Has anyone seen anything like this?

if ( condition 1 ) {
1 line of code
}
else {
if ( condition 2 )
1 line of code
}
else if ( condition 3 )
1 line of code
}
else {
2 lines of code
}
2 lines of code
}

There are no opening braces after the tests for conditions 2 & 3, but there are closing braces following the code for each of the conditions.

I would have thought that this would cause a compile error. The only reasonable answer that I could come up with is that the closing braces are ignored in these 2 conditions because there is a single line of code to be executed and therefore they aren't really necessary.

Does anyone have a better explanation?

Charles
11-12-2003, 10:32 AM
It's because there is a single line of code to be executed and therefore they aren't really necessary. JavaScript is like that. You'll find that the ";" at the end of a line of text is also optional.

ccoder
11-12-2003, 03:06 PM
Well, I knew that the semicolon was optional, but I didn't think of that when I guessed that the brace might also be optional in this case. I would have expected to see an "Else without If" error.

HTML is pretty forgiving whan it comes to missing tags. Seems the author(s) did the same with JavaScript.

Thanks for the clarification!