How does this "for (;;)" syntax work in Javascript? - javascript

I came across a strange syntax for the for in an open source Javascript library.
for (;;) {
}
What does this even do? Can anyone answer?

It's "loop forever" and it works the same in C, C++, C#, Java etc. You've got a for statement with
no init step
no termination check (=> continue forever)
no end-of-loop step

It's an infinite loop, just like while(true).

As others have already pointed out, if will run forever, but you can still end the loop with break. Like:
for (;;) {
if (condition) {
break;
}
}
Mozilla
has a good breakdown of how javascript evaluates for loops:
for ([initialization]; [condition]; [final-expression])
statement
initialization
An expression (including assignment expressions) or variable declaration. Typically used to initialize a counter variable. This
expression may optionally declare new variables with the var keyword.
These variables are not local to the loop, i.e. they are in the same
scope the for loop is in. The result of this expression is discarded.
condition
An expression to be evaluated before each loop iteration. If this expression evaluates to true, statement is executed. This conditional
test is optional. If omitted, the condition always evaluates to true.
If the expression evaluates to false, execution skips to the first
expression following the for construct.
final-expression
An expression to be evaluated at the end of each loop iteration. This occurs before the next evaluation of condition. Generally used to
update or increment the counter variable.
statement
A statement that is executed as long as the condition evaluates to true. To execute multiple statements within the loop, use a block
statement ({ ... }) to group those statements.
Most relevant to this question is in the condition section:
This conditional test is optional. If omitted, the condition always
evaluates to true.

A simple/empty ; in many languages acts as a blank but true (and executable) statement.
Hence, in the for loop, all three expressions are true, always matched and hence, results in an infinite loop.
It has also been on Wikipedia. As per the wiki page
This style is used instead of infinite while(1) loops to avoid a
warning in Visual C++.
The controlling expression of an if statement or while loop evaluates to a constant. If the controlling expression of a while loop is a constant because the loop will exit in the middle, consider replacing the while loop with a for loop. You can omit the initialization, termination test and loop increment of a for loop, which causes the loop to be infinite (like while(1)) and you can exit the loop from the body of the for statement.

This is valid for loop for (;;) {} if condition is not given in for loop its by default true. So loop run infinitely. same as for (;1;) {}
Additionally not only in Javascript its true in C, C# language also etc.
Read this: Is “for(;;)” faster than “while (TRUE)”? If not, why do people use it? to know why some programmers may prefer for (;;) {} over simple while(true){} (interesting)

It runs an infinite loops, because
Essentially, a for loop is a shortened version of another loop, with this syntax
for(a;b;c){
}
is
a;
while(b){
c;
}
so loops forever, since the b is empty, and it has no increment operator to change anything.
Basically, it's an infinite loop of nothingness.
EDIT: Apparently, the empty command evaluates to true.

Related

Can someone explain me the Syntax of a loop like "for (;;)"

Can someone explain me the Syntax of a for-loop like "for (;;)" what i need to know is whether the header of a for-loop like "for (;;)" is having empty-statements or not.
I searched the ECMAScript specification about what will happen if all the optional expressions within the for-loop's header is skipped like for (;;) in the specification but i still didnt find about it
can someone explain me about this even the specification haven't mentioned that a for-loop like for (;;) loops/runs infinite times
and i need to know one last thing why people call the header of a for-loop is having Expression's i see that the syntax of a for loop allows us to write declarations like var i = 0 in the header of the for-loop and i see the for-loops syntax allows us to write semicolons ; in its header only statements require semicolons does that mean all the syntax within the for-loop's header is having Statements
In a standard for loop definition, it would go as follows:
for (var i = 0; i < 5; i++)
{
//Do something here
}
You have your statement being defining i as 0 (var i = 0). Then, there is the condition/expression that the for loop checks each time as it runs, which in this example checks that i is less than 5 (i < 5).
So, to address the first part of your question, when you define a for loop as for(;;), you are simply defining a loop with no condition that must be met. Therefore, it continues to run/loop forever. This can be done because all parts of the for loop definition are optional. So, there are no "empty-statements". It is simply defining the for loop without the optional arguments. We fill it in with semicolons instead in order to represent the transition between the empty arguments.

5.2 Eloquent Javascript - 3rd Edition

Relatively new at programming, looking for an explanation of a question in Chapter 5 of Eloquent Javascript.
Your own loop Write a higher-order function loop that provides something like a for loop statement. It takes a value, a test
function, an update function, and a body function. Each iteration, it
first runs the test function on the current loop value and stops if
that returns false. Then it calls the body function, giving it the
current value. Finally, it calls the update function to create a new
value and starts from the beginning.
When defining the function, you can use a regular loop to do the
actual looping.
loop(3, n => n > 0, n => n - 1, console.log); // → 3 // → 2 // → 1
The answer:
function loop(start, test, update, body) {
for (let value = start; test(value); value = update(value)) {
body(value);
}
}
loop(3, n => n > 0, n => n - 1, console.log);
// → 3
// → 2
// → 1
Looking for a walkthrough of what the code is doing. Any help to clearly understand this problem would be helpful.
A for loop consists of 4 parts:
Initialization - this is run at the beginning of the loop; it usually initializes the variable(s) used in the Condition and Repetition parts.
Condition - This is executed before each iteration. If its value is truthy, the body is then executed; otherwise, the loop stops immediately.
Repetition - This is executed after each body execution, and usually updates variable tested by the Condition.
Body - This is just ordinary code that's executed each time through the loop. It usually makes use of the variable(s) updated by the other parts.
The syntax is:
for (Initialization; Condition; Repetition) {
Body
}
So in your example, the Initialization sets the current loop value (the value variable) to the value that was given to the function.
The Condition then executes test(value) function. The for loop will automatically test whether this returns true or false -- if it returns false the loop stops. This fulfills the requirement:
Each iteration, it first runs the test function on the current loop value and stops if that returns false.
Then the Body is executed, and this executes body(value). This implements the requirement:
Then it calls the body function, giving it the current value.
Then the Repetition executes value = update(value), which implements:
Finally, it calls the update function to create a new value and starts from the beginning.
"For loops" are a built-in feature common to programming languages, including JavaScript. The Wikipedia article about them is pretty thorough, and I'd start there if you wanted to understand the context of the question.
The exercise at hand, then, is to write a function in JavaScript that roughly-speaking provides similar features to the built-in "for loop".
The solution you quoted defines a function ("loop") that accepts four parameters: an initial value ("start"); a function that runs at before each iteration, to test whether the loop should stop ("test"); a function that will be run after each iteration ("update"); and the function that should be run in the body of the loop during each iteration ("body"). It then uses an actual for loop to perform the requested iterations.
Trying to understand this myself while reading this...but from what I grasp from it it sounds like the author is trying to teach you one of two things.
That a for loop consists of a
for(initialExpression; condition; incrementExpression){
and then the statement
}
That you can create your own reusable customizable loop function that can function like forEach() or how ever you would like it to function.
Solving this with a for loop seems awkward, I understand why you are confused, just like me - I'm noob too :)
Here's a recursive solution, hopefully it will shed more light, if you haven't completely figured stuff out:
function loop(value, test, update, execute) {
if (!test(value)) return; // stop
execute(value);
return loop(update(value), test, update, execute);
}

What Prevents This JavaScript For Loop from Looping Infinitely?

I am definitely a novice when it comes to JavaScript. I have searched around stackoverflow and the web for an explanation as to why this JavaScript for loop does not loop infinitely, but I have yet to find a clear answer. I am currently using this loop, a loop that I borrowed and modified, on my website and it is working as intended; however, I would like to know why it isn't looping infinitely. I was under the impression that the first statement of a for loop defines the loop variable, the second sets the looping condition (which prevents an infinite loop), and the third modifies the loop variable after the code block has been executed. Why is this loop not looping infinitely if it lacks a loop condition statement?
function showAll() {
var aBoxes = document.querySelectorAll('.aBox');
for (var i = a.Boxes.length; i--;) {
aBoxes[i].style.display = 'block';
}
}
When the variable "i" is finally decremented to 0, the value of i-- will be "falsy" and the loop will terminate. The loop does not lack a condition expression; that's what i-- is.
As long as i--; is not 0, it will be evaluated to true, hence the loop will continue. When it reaches 0, which evaluates to false, it will stop
Because it doesn't lack a loop condition statement. It lacks the modifying statement. One lacking the second condition would look like this:
for (var i = a.Boxes.length; ; i--)
What your loop is doing is decrementing i whenever it's time to check the loop condition statement and then checking to see if the resulting value is true or false (i.e. non-zero or zero). When i gets small enough (i==0) this will terminate the loop.
The loop isn't missing the condition expression; it's missing the expression that occurs at the end of each loop iteration (the third expression). However, i is decremented as a side-effect of the condition expression, so a final expression is not needed.
The condition expression evaluates to false once i reaches 0 and so the loop terminates.
More generally, each of the expressions in a for statement is optional. It is perfectly fine to omit any or all of them.

Why is for(;;){…} an infinite loop? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Empty for loop - for(;;)
I just found a strange construct in the JS parser of UglifyJS (at L1045): for(;;){…}.
I assumed that an empty condition would resolve to undefined, which is converted to the boolean value false. But that's definitely not the case.
Apparently, it triggers an infinite loop. I was able to reproduce this behavior, but I have no clue why. Any (logical) explanations?
Besides: When this is possible, why doesn't while(){…} work?
That's just the definition of the semantics. A missing "test" expression is treated as an expression with the value true. Languages are made up by people, and they are at liberty to specify any behavior they like. Clearly, that behavior is something Mr. Eich likes :-)
for(;;){…} interprets an empty condition as true and while(){} is not considered as valid. As said before it's totally language dependant but described in the specification.
In the ECMA-262 language specification of JavaScript (section 12.6.3) it is defined how the behaviour of the for loop should be.
You can see from the definition that if the information around and between the semi-colons is not available, there are no conditions to leave the loop. The only way to leave the loop is by defining a test condition and optionally some start and step values.
The behaviour could be defined in a different way but that's just not how it is.
From the spec.
12.6.3 The for Statement
The production
IterationStatement : for (ExpressionNoIn(opt) ; Expression(opt) ; Expression(opt)) Statement
is evaluated as follows:
1. If ExpressionNoIn is present, then.
a. Let exprRef be the result of evaluating ExpressionNoIn.
b. Call GetValue(exprRef). (This value is not used but the call may have side-effects.)
2. Let V = empty.
3. Repeat
a. If the first Expression is present, then
i. Let testExprRef be the result of evaluating the first Expression.
ii. If ToBoolean(GetValue(testExprRef)) is false, return (normal, V, empty) .
b. Let stmt be the result of evaluating Statement.© Ecma International 2011 91
c. If stmt.value is not empty, let V = stmt.value
d. If stmt.type is break and stmt.target is in the current label set, return (normal, V, empty) .
e. If stmt.type is not continue || stmt.target is not in the current label set, then
i. If stmt is an abrupt completion, return stmt.
f. If the second Expression is present, then
i. Let incExprRef be the result of evaluating the second Expression.
ii. Call GetValue(incExprRef). (This value is not used.
Gist of this spec: for statement stops when first Expression returns "falsey" value.
Since absence of expression doesn't return false, the script will run forever (or until break statement is executed from inside the loop body).

In JavaScript what does for(;;){...} do?

I've seen this in some JavaScript code but I don't get what it does.
for(;;){
//other code
}
I'm used to the for(i=0;i<someLength;i++){...} format but I'm stuck to figure out how or what the "(;;)" syntax is for?
In JavaScript, for (;;) { ... } just creates an infinite endless loop, which is almost exactly the same as:
while (true) {
// ...
}
or
do {
// ...
} while (true);
for (;;) is the exact same syntax. You're allowed to leave out parts that go between the semicolons, even all of them. If you leave the condition out, it's assumed to be true, so it results in an infinite loop. You can of course still exit with break or return or whatnot, hence making it not useless.
It creates a loop that runs indefinitely. It's the same syntax you're used to seeing, there's just no code between the semicolons.
The syntax for a for loop includes an initializer, followed by a semicolon, followed by a condition for continuing the loop, followed by a semicolon, followed by code to run after each iteration of the loop.
Since there is no initializer, no condition that ever evaluates to false, and no post-loop code, the loop runs forever.
That's an infinite loop. A for loop has 3 sections separated by ;: the initialization section where you normally declare and define your counter's starting conditions, the middle conditional statement that evaluates to true or false, and the increment section.
All 3 of these sections are optional. You can include any or none. The loop continues to loop until the conditional is false. If that condition is never met (since it was left out), it loops forever.
A place where you'll likely see it is prepended to JSON data as described by this SO post.
always true https://developer.mozilla.org/en/JavaScript/Reference/Statements/for

Categories

Resources