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

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.

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.

Is it a browser bug that I can't use js labeled statements with an if?

Disclaimer: Yes, I know goto is bad, I'm interested here in the spec and implementations, not best practices.
I have this super simple javascript example of a labeled statement
let i = 0;
foo:
if(i < 5) {
console.log(i);
i +=1;
continue foo;
}
As far as I can tell for the spec for labelled statements and for statements this should work!
So am I reading the spec wrong or is there a bug somewhere?
Note that usage as shown on MDN with for statements works fine
From the specification for continue:
It is a Syntax Error if this production is not nested, directly or indirectly (but not crossing function boundaries), within an IterationStatement.
An IterationStatement is defined as a for loop or a case block. An if block is an IfStatement, not an IterationStatement, so you cannot use continue inside one.
The problem is that continue can only be used in a loop.
The continue statement terminates execution of the statements in the current iteration of the current or labeled loop, and continues execution of the loop with the next iteration.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/continue

How do simplified if statements work in javascript? [duplicate]

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

Can labels with "continue" and "break" jump to other statements?

What the title says is my question. I'm new to JavaScript. I am wondering if I can use statements to jump to certain lines of code. I have looked here and here. They don't explicitly say this can be done, but I think there might be a way for it to be done.
The way I understand it now it that I can designate any block of code or statement to have a label. I can attach that label to a break or continue statement, and it will jump to that line of code. But it seems, from the W3 tutorial, I can only jump to the top of the block of code where the label is.
It seems pointless to allow a continue statement to have a label proceed it when it can only be used inside of a loop and anything it can do with a label can also be done with a break and a label. In this example there is a break statement used to go to the top of the statement block; is there any difference in using the continue vs break?
I realize this could be bad practice because of what is hisorically known as "spaghetti code," but I am a curious person.
continue ends the current iteration and jumps straight to the next iteration in the loop, so basically to the top of the code block in the loop, if there is a next iteration to do.
break ends the loop, so it jumps past it. No further iterations are performed.
So that's quite a big difference. What they have in common, is that they can have a label to indicate a specific statement. So if you have a nested for loop, you can continue or break the outer for loop if it has a label. That doesn't mean that you jump to the label, it just means that you apply the break or continue to the loop indicated by the label, instead of the inner-level loop which you are in at that moment. You still have to be inside that labeled statement, though. You cannot jump to another part of the program.
What you are asking for is basically a goto statement. For that, maybe you'd like to read this question: How can I use goto in Javascript?
A break foo; does not "go to the top of a statement block" - it is not a GOTO.
Rather, the name specified informs JavaScript of which loop to break from, which is sometimes (although perhaps rarely) useful for nested loops.
Consider this code which does terminate:
outer: while (true) {
inner: while (true) {
break outer; // goes from here -->
}
}
// <-- to here
And a [flawed] variation, which loops until forcibly terminated:
outer: while (true) {
inner: while (true) {
// break; or,
break inner; // goes from here -->
}
// <-- to here
}
On the other hand, continue merely skips the remaining code within the loop - the post actions are performed and the loop condition is re-evaluated. That is, continue does not unconditionally terminate the loop.

What is difference between "options and error code" in jshint?

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

Categories