{
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
Related
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.
I had confusion between options and error/warning code in jshint.
curly : true
or
W116
How to identify "curly options" belongs to W116 Code?
while(true)
alert("ok");
demo.js: line 3, col 5, Expected '{' and instead saw 'alert'.(W116)
Please let me know, If my question is not clear.
Update
And if you really want to know what error codes belong to what options, I guess you'll have to dive in the source code here..
But usually the documentation should be enough, curly option:
This option requires you to always put curly braces around blocks in
loops and conditionals. JavaScript allows you to omit curly braces
when the block consists of only one statement, for example:
while (day)
shuffle();
However, in some circumstances, it can lead
to bugs (you'd think that sleep() is a part of the loop while in
reality it is not):
while (day)
shuffle();
sleep();
Also, if sometimes you wonder what an error code corresponds to, check this file:
messages.js
So in your case:
messages.js#L189
I am completing a book called "DOM Scripting - Web Design with JavaScript and the Document Object Model" written by Jeremy Keith.
Here is the 'do...while' example given:
var count = 1;
do {
console.log(count);
count++;
} while (count < 11);
In the book he has stated that if we look at our do...while loop example we can be formulate it in full like this:
initialize;
while (condition) {
statements;
increment;
}
Surely this is in fact a mistake and this is actually the formulation of a while loop and not a do...while loop.
I have also checked the Errata to see if this was an error in the book but there is no mention of it.
Am I correct in saying this is the formulation of a while loop and not a do...while loop? Is there some authoritative ECMAScript documentation I can consult?
In the book that you mentioned above , do-while has been described like this :
As with the if statement, it is possible that the statements contained within the curly
braces of a while loop may never be executed. If the condition evaluates as false on the
first loop, then the code won’t be executed even once.
There are times when you will want the code contained within a loop to be executed at
least once. In this case, it’s best to use a do loop. This is the syntax for a do loop:
do {
statements;
} while (condition);
This is very similar to the syntax for a regular while loop, but with a subtle difference. Even
if the condition evaluates as false on the very first loop, the statements contained within
the curly braces will still be executed once.
So it becomes clear after reading this section that the author never says that do-while and while are the same. What he says is that, whatever you are doing using while, you can do the same using do-while. However, in a while, if condition evaluates to false during the first iteration itself, it will not even enter the loop. But in do-while, since iteration in the syntax is specified later, so it will enter the loop at least once. That's pretty much what he means.
According to the ECMAScript 5.1 spec, section 12.12, any statement can be labelled - and in a brief test my browser accepted a label before any statement. The spec also states that labels are used exclusively with break and continue statements, and a quick test revealed that those statements throw an "undefined label" error if the label they reference does not refer to a loop that contains them.
So my question is this: what are labels for statements that are not loops used for? Is there some context in which break or continue can reference a label that is not a loop?
Apparently the break and continue statements can be used within any statement:
http://docstore.mik.ua/orelly/webprog/jscript/ch06_11.htm
In which case things like this become legal:
function show_alert()
{
label:
{
break label;
alert("Hello! I am an alert box!");
}
alert("hi");
}
When show_alert() is called, only the "hi" alert is shown.
As far as I know, this is the only use of the {} code blocks, other than for code styling. (there was a question on here about that, and noone could come up with anything other than readability, but I can't find it now...)
Yes you can label any statement. You just need to put the statement in curly braces, i.e.
{start:var a=1;}
this will not show undefined label error.
I have seen and used javascript code that both has and omits the ';' from the end of statements. Are they required in some cases and not in others? If so can you give some examples, and if not what is the general standard, to use the ';' or to not...that..is the question??
JavaScript uses a (generally disliked) method called Semicolon Insertion, where it will allow you to omit semicolons.
The rules for where you can and cannot insert semicolons is extensive, and covered fairly well here.
In general, do not rely on semicolon insertion. It is a poorly thought out feature and will hurt you before it helps you.
Not only should you always use semicolons, but you should also get in the habit of putting your { braces on the same line, as semicolon insertion can actually misinterpret what you meant.
For example, say I'm trying to return a javascript object from a function:
function f() {
return { "a":"b", "c":"d" } // works fine
}
function g() {
return // wrong!!!
{
"a":"b",
"c":"d"
}
}
If I put the { on a new line (as I did in g), the return statement will actually have a semicolon inserted after it, destroying the meaning of what you were saying.
Overall, semicolon insertion is a poor feature and you should never rely on it.
Use ; to mark the end of a statement. Javascript follows the syntactical theme set in C family languages, and ; is the delimiter for the end of a statement.
What code have you seen that omits this?
If there's no more code in the block after a line, the ; is technically optional. You should include it anyway.
Always use the semicolon, this makes the code easier to read. Right now I am not aware of any situation where it can be omitted.