When I started developing, I followed tutorials that always used {}
(curly braces) to enclose blocks. However, when I began looking at other peoples code (classes on GitHub for example, or just more code in general than what a basic tutorial would show), however I've also seen block statements without being enclosed in {}
, for example;
if($var < 15)
$string = 'Hello, Jimmy!';
elseif($var >= 15)
$string = 'Hello, Anne!';
Is the same as
if($var < 15) {
$string = 'Hello, Jimmy!';
} elseif($var >= 15) {
$string = 'Hello, Anne!';
}
I've never used blocks not enclosed in {}
, however I used them today and I'm starting to see the efficiency of doing so (it looks a lot cleaner too, as I'll often find my functions riddled with {}
from loops, conditionals etc.
What I'm asking is;
a) are there any limitations on blocks without curly braces (; I noticed my IDE dropped back from an indent after I enter a single line and returned after an if()
conditional?
b) are there any best practices to be had, when not using {}
?
Any answers, specifically those inc. background/docs on the convention of curly brace usage for blocks vs. not using them would be greatly appreciated, as I'd really like to understand the usage of curly braces :)!