This question already has answers here:
Do 'if' statements in JavaScript require curly braces? [duplicate]
(4 answers)
Closed 8 years ago.
I'm working thru a HTML5 projects course right now on Udemy.com and the guy's example code has this:
//Use a timer to call paint function
if(typeof game_loop != "undefined") clearInterval(game_loop);
game_loop = setInterval(paint, speed);
I thought 'if' statements had to have curly braces so the code inside can run if the the 'if' statment is true. Please advise. Thanks
You can use if with any single statement, whether that statement is a block statement or any other kind.
The grammar for the if statement in ECMAScript is:
IfStatement :
if ( Expression ) Statement else Statement
if ( Expression ) Statement
Notice that there are no curly braces defined. Any valid statement is permitted.
This:
if (condition)
then_case();
else
else_case();
evaluates the same as this:
if (condition) {
then_case();
} else {
else_case();
}
If your have multiple statements, then you need a block statement in order to contain them.
if (condition) {
then_case();
also_this();
} else {
else_case();
also_that();
}
Sometimes you see things like
if (condition)
then_case(), also_this();
which evaluates, but is ugly. (Best just forget my last example. :-) )
Your example code is syntactically correct. You may omit the brackets assuming you have a single line of code after your if/else statement.
if (condition)
//Do something
else
//Do something
Many folks, including myself, loath this practice. Check out further discussion here:
Is it bad practice to use an if-statement without brackets?
Why is it considered a bad practice to omit curly braces?
Similar to other 'c' syntax languages, the scope of the context may be omitted if the statement is only a single line.
e.g.
if(true)
alert('hello');
is equal to
if(true) alert('hello');
is equal to
if(true){ alert('hello'); }
You may also see another form
var myBool = Boolean(someValue) ? false : true
If you have only one statement to be part of body of if or else, then curly braces are optional. But if you want group of statements to be part of if or else's body then it is mandatory to have curly braces.
if(condition)
//Only one statement
else if(condition2)
//Only one statement
else
//Only one statement
But in the following it is mandatory to have curly braces.
if(condition){
//first statement
//second statement
.....
//nth statement
}
else if(condition2){
//first statement
//second statement
.....
//nth statement
}
else{
//first statement
//second statement
.....
//nth statement
}
And please note, it is not only for JavaScript, it is same behavior in most of the programming languages as well, like C, C++, Java etc.
You don't need the curly braces for a one-line consequence of the if statement. But if the consequence of the if statement is multiple statements, then you wrap them in curly braces to identify them as such.
Related
{
var x = 0;
...
}
What are the curly braces supposed to do, it is clearly not a function or a loop, it's just empty curly braces with nothing before.
p.s. if anyone finds a better way to rephrase this question, please do
Those are called block statements, they are simply there to group together statements to be executed together.
Here are some useful links:
https://www.w3schools.com/js/js_statements.asp
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/block
This question already has answers here:
Concise syntax for javascript if statements without curly brackets
(5 answers)
Closed 6 years ago.
Once and awhile I see and try to use an if statement like this:
var boo = true;
if(boo)
console.log("a");
as opposed to :
var boo = true;
if(boo == true){
console.log("a");
}else{
console.log("not true");
}
Is there a way to have an "else" with my first switch statement? How does the compiler even know when to stop? Does it do the conditional logic after a linebreak?
An if is just followed by a statement. A block (which is typically and idiomatically used there) is just a type of statement that wraps up a group of other statements.
Is there a way to have an "else" with my first switch statement?
The same is true of else
if (1)
something();
else
something_else();
How does the compiler even know when to stop?
It allows a single statement.
Does it do the conditional logic after a linebreak?
No, a statement. The line break there just triggers ASI.
The formal syntax for if else is something like:
if statement else statement
The generic "statement" there can be something like a simple assignment expression, a single function call, or a block of one or more statements enclosed in { }. Thus, the { } are not part of the syntactic structure of the if statement. They're part of the general and often-used compound statement. (JavaScript may formally call that something else; it's a common thing however and the name isn't so important. edit A comment notes that it's formally a "block statement", but I think "compound" is more descriptive so I'll leave it in.) A brace-enclosed compound statement contains any number of other statements, but from the outside it comprises just one statement.
The else part of the if statement is optional, so
if statement
is fine too.
Thus, in your examples:
if (boo)
console.log(a);
The console.log(a); is the single statement. In the second example:
var boo = true;
if(boo == true){
console.log("a");
}else{
console.log("not true");
}
there is an else clause, and both the if and the else have compound statements playing the role of the single statement in the formal syntax.
As to exactly how the parser understands that, well, that's a big topic. Suffice to say that programming languages are designed to be as unambiguous as possible, so that the code to parse the raw text of a program can be as simple as possible. Of course, as with anything, no such design is perfect, and in particular JavaScript has syntax features that are surprisingly hard to parse. What we're talking about here, however, isn't one of those. The whole purpose of the { } wrapper around a compound statement is to give the parser a clear signal: here comes a compound statement.
if (condition)
stuff...
else
stuff...
if(true)
alert("A")
else
alert("B")
alternatively
if(false)
alert("A")
else
alert("B")
I'm trying to learn about chaining and how to do it myself by reading OPC. I'm still very stuck. While learning this, I ran into a bit of error handling that raised my eyebrows. It seems, from the indentation, that line 4 is not a part of the if statement that begins on line 2. Am I right to assume that 2-line if statements do not require curly braces, and the interpreter assumes that when there is a lack of curly braces, only the line directly proceeding an if statement is a part of that same if statement; therefore, the fourth line is not a part of the if statement in the following block:
set: function (mystr, func) {
if (!this[mystr])
throw new Error("unknown hook " + mystr);
this[mystr] = func;
},
It's typically not the line but the statement succeeding the if-statement that's considered belonging with it.
The curly braces are only required if you have multiple statements inside the block. If you don't use braces, the next statement (single) will be inside the block, the following statements will be outside the block.
if (something)
StatementIfTrue();
StatementEitherWay();
if (something)
{
StatementIfTrue1();
StatementIfTrue2();
}
StatementEitherWay();
if (something) StatementIfTrue(); StatementEitherWay();
Yes, line 4 is not in the if block.
Without the braces, only the next statement right after if will be in the if block.
This question already has answers here:
Do you recommend using semicolons after every statement in JavaScript?
(11 answers)
Closed 7 years ago.
I want to know, is this legal?
function test()
{
alert ("hello")
$("#loading").show();
}
Or should I write this instead:
function test()
{
alert ("hello");
$("#loading").show();
}
Are semicolons optional in JavaScript? Because I saw this in a forum:
No, semicolons are usually optional in JavaScript (Google for ASI / automatic semicolon insertion). Using them makes the code look much cleaner though and ASI is a horrible mis-feature (at least in my opinion).
Semicolons are not always mandatory, but I would always recommend using them. See the ECMAScript spec for the rules on automatic semicolon insertion:
Certain ECMAScript statements (empty statement, variable statement,
expression statement, do-while statement, continue statement, break
statement, return statement, and throw statement) must be terminated
with semicolons. Such semicolons may always appear explicitly in the
source text. For convenience, however, such semicolons may be omitted
from the source text in certain situations. These situations are
described by saying that semicolons are automatically inserted into
the source code token stream in those situations.
Update (to explain further)
Perhaps the most common situation used to show why automatic semicolon insertion can be bad is that touched on by #sissonb in another answer. Consider the following:
function something(a, b) {
return
a + b;
}
What you may be expecting is for the new-line to be ignored, and the code interpreted as:
function something(a, b) {
return a + b;
}
Unfortunately, automatic semicolon insertion comes into play, and the code is actually interpreted like this:
function something(a, b) {
return;
a + b;
}
And an empty return statement means the function returns undefined. So instead of a nice sum of the two argument, you get undefined and potentially end up very confused as to where you've gone wrong! Which is why I completely agree with the statement in your question that automatic semicolon insertion is a horrible misfeature.
Example (returns undefined because of ASI).
Example (returns expected result).
Semicolons are not mandatory. They are automatically added at the end of a line if it is missing which actually causes this code to return undefined.
return
{
text:"hello"
}
This question already has answers here:
Why do results vary based on curly brace placement?
(6 answers)
Closed 6 years ago.
I am quite new to JavaScript and just started some more serious development in JavaScript. I had a lot of fun implementing the Module pattern. One thing that really drove me crazy was the behavior of the 'return' statement. It is a big difference if you write
Test = ( function()
{
var message = "Hello World!";
return
{
// Does not work
printTest: function() { window.alert(message); }
};
}());
or
Test = ( function()
{
var message = "Hello World!";
return {
// Works well
printTest: function() { window.alert(message); }
};
}());
Note the curly brace after the 'return' statement.
Is that a typical stupid rookie error and is well documented somewhere?
Firebug was not able to give a hint. IE9 and Chrome did report some obscure syntax error at a later location in the code: the opening brace after the 'function' statement in "printTest: function()".
Any comments on this? Are there more such pitfalls in JavaScript?
If you put your brackets to the next line, the interpreter assumes that there is a semi-colon.
So your return statement will be interpreted as:
return;
{
printTest: function() { window.alert(message); };
}
If I remember well, i've red about this problem in JavaScript: The Good Parts
A.3. Semicolon Insertion
JavaScript has a mechanism that tries to correct faulty programs by automatically inserting semicolons. Do
not depend on this. It can mask more serious errors.
It sometimes inserts semicolons in places where they are not welcome. Consider the consequences of
semicolon insertion on the return statement. If a return statement returns a value, that value expression
must begin on the same line as the return:
return
{
status: true
};
This appears to return an object containing a status member. Unfortunately, semicolon insertion turns it
into a statement that returns undefined. There is no warning that semicolon insertion caused the
misinterpretation of the program. The problem can be avoided if the { is placed at the end of the previous line
and not at the beginning of the next line:
return {
status: true
};
"JavaScript: The Good Parts by Douglas Crockford. Copyright 2008 Yahoo! Inc.,
978-0-596-51774-8."
Are there more such pitfalls in JavaScript?
This made me smile :) Oh boy, you're in for a treat.
Have a look at this site for example: http://wtfjs.com/
Yes, it's a difference. I think it actaully is a part of documentation, the subject that is to be returned has to be in the same line as the return statement.
It's beacause semicolons are optional, and the expression is interpreted as
return;
{
....
}
JavaScript does automatic semi-colon insertion. If you put the brackets on the next line after the return, the interpreter automatically inserts a semi-colon after the return, ending the statement.