Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Why no curly braces in "if" statement?

I noticed that Guil did not add curly braces when writing the "if" statements around the 2:22 min mark in this video. Why is that? Is that also part of ES2015? Is there by chance a video I haven't seen yet? Example:

if (classroom.has(stevenJ)) (console.log('stevenJ is in the classroom'));

Shouldn't this normally be written like this?

if (classroom.has(stevenJ)) { console.log('stevenJ is in the classroom'); }

Steven Parker
Steven Parker
243,318 Points

That first example doesn't appear to be valid syntax. Can you provide a link to the video in question?

3 Answers

If your if or else statement only contains a single statement (usually on a single line) you are able to omit the curly braces. It does not make a difference and falls back to preference.

Thank you so much Alexander La Bianca ! Do you happen to know if the option to omit the curly braces has always been around or if it is part of ES2015?

Steven Parker sorry for forgetting the video link. This is the video I was referring to: (around the 2:56 min mark)

https://teamtreehouse.com/library/set

Thank you both for your help!

Steven Parker
Steven Parker
243,318 Points

That makes a bit more sense. The video example has fewer parentheses than shown above. What it actually showed was:

if (classroom.has(stevenJ)) console.log('stevenJ is in the classroom');

And yes, the braces are only required when there is more than one statement being controlled by the conditional.

This is a standard feature of JavaScript and has always been part of the language. You might not see it often because many programmers prefer to use the braces always.