www.webdeveloper.com
Results 1 to 3 of 3

Thread: anyone know why this works?

  1. #1
    Join Date
    May 2003
    Location
    O!
    Posts
    200

    anyone know why this works?

    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?
    Code:
       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?

  2. #2
    Join Date
    Nov 2002
    Location
    Baltimore, Maryland
    Posts
    12,279
    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.
    “The power of the Web is in its universality. Access by everyone regardless of disability is an essential aspect.”
    —Tim Berners-Lee, W3C Director and inventor of the World Wide Web

  3. #3
    Join Date
    May 2003
    Location
    O!
    Posts
    200
    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!

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles