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
Related
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.
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);
}
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.
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.
I have seen some developers place a return at the end of their JavaScript functions like this:
$(".items").each(function(){
mthis = $(this);
var xposition = some .x() position value;
if(xposition < 0){
mthis.remove();
return;
}
});
Is having a return even necessary? I know that return false cancels out of a loop early and I know that return x, returns a value, but having just return??? What does that mean?
Sorry - I forgot to put an end } at the very end of the code. the return is in the if conditional.
New Update - just discovered that the intent of the loop was to cancel out the nth .item that entered the loop. so return false is my replacement for a simple return; (which means undefined anyway). Thanks everyone for the help!
Having return with not proceeding it at the end of the function doesn't really do anything. Returning "this" however allows for method chaining.
Your example is specific for how jQuery.each handles the return values from a loop function. From the docs:
We can break the $.each() loop at a particular iteration by making the
callback function return false. Returning non-false is the same as a
continue statement in a for loop; it will skip immediately to the next
iteration.
So there you have it, returning anything else than false makes no difference, it will just move on to the next iteration. false, however, breaks the loop.
Note that return; is exactly the same as return undefined;.
It's just a way to end the function execution without necessarily having to choose a proper return value. At the end of the function it really doesn't make a difference.
The behaviour of return; anywhere in your function is exactly the same as when the code reaches the end of your function, the caller receives undefined.
In that code it's used together with a condition. I would have to assume that you didn't show the full code.
This method is used often to jump to the end of the function when a pre-condition is not met as it might be more readable than five indentations, each with another condition.
The problem is that your opening and closing { } braces don't line up, so depending on which is correct, this will perform differently. If the closing brace for the if is after the return, then this will act like a continue in a regular for loop.
$(".items").each(function(){
mthis = $(this);
var xposition = some .x() position value;
if (xposition < 0) {
mthis.remove();
return;
}
}
As it turns out, a continue at the end of a for loop is also implicit, so this doesn't really serve a purpose.
Of course, if you're question is more theoretical, the answer is that generally it doesn't make a difference:
function doSomething() {
alert("Hello, world");
return; //purely a matter of preference
}
Here, the method would implicitly return even without the direct invocation of return by virtue of being at the end of the code-block; in some cases it can be useful just as an indicator that you are at the end of the function, particular if there was a lot of nesting. If not at the bottom, it definitely makes a difference, since nothing after the return; will be executed. Otherwise the difference is purely stylistic. Saves you a few characters to leave it out of course!
Just like return false, it'll cancel out of the block (in this case, the function) early. The return value will be undefined.
At the end of a function, it's equivalent to not using a return statement at all, but your example doesn't look like the end of a function to me.
EDIT: Just to make it a bit clearer: This particular return statement is at the end of the surrounding if clause, not the function as a whole. In other words, the condition of the if clause specifies a situation in which the function should terminate mid-way.
EDIT 2: By "the function", I refer to the inner, anonymous function. return;, being equivalent to return undefined;, will indeed cause jQuery.each() to move on to the next item. (Also, it seems that I was mistaken about there being more code in the function; given the OP's edit to the code sample, it really does look like a pointless return statement.)