Is line 4 inside the if statement started on line 2? - javascript

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.

Related

Unable to understand the use of break master in below code snippets [duplicate]

This question already has answers here:
What is the use case for "break Identifier" in JavaScript?
(2 answers)
Closed 5 years ago.
master:
switch(chipType)
{
case "ICs":
for (var i = 0; i < ICs.length; i++)
{
if (ICs[i].name == chipName)
{
outField.value = ICs[i].price;
break master;
}
}
can anyone explain to me what is master doing in the above code snippets?
I am referring javascript Bible book 7th edition
The symbol master is a label. The break statement can take as a sort of "argument" a label, which must be on another statement that lexically encloses the break. The meaning of that is to "jump" (what used to be called "go to" basically) to the statement following the labeled statement.
That's useful here because without the label, the break would only apply to its enclosing for loop.
Any type of statement can have a label, but it's really only useful for statement types that may have a break statement. Note that although it's OK (but weird) to label a function declaration statement, it can't be used to "break out" of the function from a break statement inside the function. Probably obvious, as that's what return is for.
When the "break" statement is used with a label ("master" in this case), it causes the statement immediately following the label (in this case the switch statement) to be exited, with program flow skipping immediately to the following statement. So "break master" here causes the program to stop executing code inside the switch statement and go directly to whatever statement (if any) comes directly after the switch statement.
Using "break" without a label causes the innermost for, while, do-while or switch statement (i.e. the most nested loop or switch containing the break statement) to be exited, with program flow skipping immediately to the statement following the loop. This is by far the more typical case of the break statement in Java code.

Can anyone point me to the standards in ecma-262 that defines using parentheses for returns?

// Create a component named MessageComponent
var MessageComponent = React.createClass({
render: function() {
return (
<div>{this.props.message}</div>
);
}
});
NOTE Why do we need the parentheses around the return statement (line
3)? This is because of JavaScript's automatic semicolon insertion.
Without the parentheses, JavaScript would ignore the following lines
and return without a value. If the JSX starts on the same line as the
return, then parentheses are not needed.
Taken from here.
There is no specific part of the spec that handles using parens for returns. Parenthesis is just one way to create an expression.
When a continue, break, return, or throw token is encountered and a
LineTerminator is encountered before the next token, a semicolon is
automatically inserted after the continue, break, return, or throw
token.
http://www.ecma-international.org/ecma-262/5.1/
Looks like the parentheses here are just vanilla JS expressions wrapped in parentheses i.e return (1 + 2), except multi-line:
function x() {
return (
1 + 2
);
}
*Edited to not use the word closure.

Javascript if statement-- no {} needed? [duplicate]

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.

How are labels used with statements that are not a loop?

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.

Are semicolons mandatory in javascript statements? [duplicate]

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"
}

Categories