SitePoint Sponsor

User Tag List

Results 1 to 5 of 5
  1. #1
    SitePoint Enthusiast
    Join Date
    May 2001
    Location
    brazil
    Posts
    39
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    curly braces optional?

    recently i've been looking at some js scripts and notice that there are times when a conditional statement looks as follows:

    Code:
    if (condition) somevar=value
    now my question is, isn't the correct pattern like this?

    Code:
    if (condition) {somevar=value}
    is it OK to ommit the curly braces after an if statement?

  2. #2
    SitePoint Wizard Aes's Avatar
    Join Date
    Jun 2001
    Location
    Oklahoma
    Posts
    3,392
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    To be safe, as it is my personal preference, I always include curly braces (be it PHP, Java2, or JavaScript). In PHP as well as Java2, if you don't use curly braces, it executes the first statement (e.g. everything until the first ;), and then continues on. I would assume the same for JavaScript. So, if you only need to execute one statement, you may forgo using the braces; if you need to execute more than one statement, or simply want to safeguard the code, use braces.

    -Colin
    Colin Anderson
    Ambition is a poor excuse for those without
    sense enough to be lazy.

  3. #3
    + platinum's Avatar
    Join Date
    Jun 2001
    Location
    Adelaide, Australia
    Posts
    6,441
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Aes is basically right

    Yes, when you have a one line condition like that it is acceptable to not use braces, anything more then two and then you'll need braces

    PHP Code:
    if (name == thmz)
      
    First
      second
    else
      Do 
    third 
    If name does = thmz then it will get to "first" and stop.

    PHP Code:
    if (name == thmz)
      {
      
    First
      second
      
    }
    else
      Do 
    third 
    however the above will do both first and second.


    It just makes it great to quikly compare things without cluttering your code . It's the same with php as well I think.

  4. #4
    SitePoint Enthusiast
    Join Date
    May 2001
    Location
    brazil
    Posts
    39
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    thanks a lot guys!

  5. #5
    SitePoint Evangelist Mr. Brownstone's Avatar
    Join Date
    May 2002
    Location
    Relative
    Posts
    452
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Incidentally, enclosing your code within curly-brackets in a conditional statement (like if, for) turns it into a compound statement. If you’re learning about the technique you might as well learn the terminology too.
    Of course, that's just my opinion. I could be wrong.


Bookmarks

Posting Permissions

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