This question already has answers here:
Why does this 'for(;;)' loops?
(3 answers)
Closed last month.
I recently came to this thread, and had a quick question on the syntax used in the first answer. #ggorlen used this syntax/notation in the for loop that I've never seen before and couldn't find any answers online:
for (;;) {
try {
await page.waitForFunction(
`${thumbs.length} !==
document.querySelectorAll("#video-title").length`,
{timeout: 10000}
);
}
catch (err) {
break;
}
thumbs = await page.$$eval("#video-title", els => {
els.at(-1).scrollIntoView();
return els.map(e => e.getAttribute("title"));
});
}
What does the for(;;) {...} do?
Thanks!
I just have a question on the syntax used, and couldn't find an answer.
for(;;) {
}
is the equivalent of
while (true) {
}
a normal "for" loop contains 3 parts separated by semi-colons like for(initialization; condition; afterthought)
The initialization runs before the looping starts.
The condition is checked at the beginning of each iteration, and if it evaluates to true, then the code in the loop body executes.
The afterthought is executed at the end of each iteration of the loop.
It is allowed to ommit these parts of the for expression e.g. for(;;)
When omitted it essentially means that it will loop forever since the condition is not present or until the code reaches a return or break.
You can read more about the for function checkout this MDN page.
Related
This question already has answers here:
Does JavaScript have "Short-circuit" evaluation?
(3 answers)
Closed 2 months ago.
This post was edited and submitted for review 2 months ago and failed to reopen the post:
Original close reason(s) were not resolved
In javascript, if (true || false) results in true, but the question is whether the compiler will evaluate the second statement if the first is true.
In my case, I want to know if an array has changed, so I believe I have two options: compare the lengths of the arrays (what was and what is now) and compare if the array values are different.
I think the first option requires less work.
If (first || second) { give me deleted values, and give me added values }
No, it does not
first() || second()
function first() {
console.log('first')
return true
}
function second() {
console.log('second')
return false
}
This question already has answers here:
Is returning early from a function more elegant than an if statement?
(14 answers)
Is it good style (or more efficient) to "return early" at the top of a function?
(2 answers)
Invert "if" statement to reduce nesting
(25 answers)
Closed 3 years ago.
When writing javascript or PHP for that matter I use two ways to write if statements.
Return as soon as possible
Below I try to end the function as soon as possible. If the value is not what I expect, return it. The benefit I see here is that I don't need {} and I don't need to nest anything.
function hello(value = null) {
if(!value) return;
console.log("I'm still here!");
console.log("End of function");
}
Do something on match
In this case I don't return at all. Instead I do something if I get a "match". The upside here is that I don't need to return anything.
function hello(value = null) {
if(value) {
console.log("I'm still here!");
console.log("End of function");
}
}
So which is better? One of them or equally good?
This question already has answers here:
"continue" in cursor.forEach()
(7 answers)
Closed 7 years ago.
How do I go to the next iteration of a JavaScript Array.forEach() loop?
For example:
var myArr = [1, 2, 3, 4];
myArr.forEach(function(elem){
if (elem === 3) {
// Go to "next" iteration. Or "continue" to next iteration...
}
console.log(elem);
});
MDN docs only mention breaking out of the loop entirely, not moving to next iteration.
You can simply return if you want to skip the current iteration.
Since you're in a function, if you return before doing anything else, then you have effectively skipped execution of the code below the return statement.
JavaScript's forEach works a bit different from how one might be used to from other languages for each loops. If reading on the MDN, it says that a function is executed for each of the elements in the array, in ascending order. To continue to the next element, that is, run the next function, you can simply return the current function without having it do any computation.
Adding a return and it will go to the next run of the loop:
var myArr = [1,2,3,4];
myArr.forEach(function(elem){
if (elem === 3) {
return;
}
console.log(elem);
});
Output: 1, 2, 4
just return true inside your if statement
var myArr = [1,2,3,4];
myArr.forEach(function(elem){
if (elem === 3) {
return true;
// Go to "next" iteration. Or "continue" to next iteration...
}
console.log(elem);
});
This question already has answers here:
Why does the value returned should be on the same line as the return statement in JavaScript?
(4 answers)
Closed 6 years ago.
This has been the source of my pain for many hours. Can anyone explain why this is the case?
function x(){
return //when there's a line break it doesn't work
2;
};
alert(x());
function y(){
return 4; //when there's no line break it works
};
alert(y());
//Can anyone explain this?
I always thought that JavaScript didn't care about line breaks. If you have links to ECMA official documentation on this, I'd be grateful. Thanks!
Here are the ECMAScript rules for Automatic Semicolon Insertion. The relevant section is:
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.
In short, your code is parsed as if it were:
return;
2;
Unlike most other languages, JavaScript tries to "fix" your code by adding semicolons where it thinks you have forgotten them.
Return statements are such a case - if there is a linebreak after a return statement, it will be interpreted as return;
JavaScript treats a endline after return as if there was an ;
So in:
return
2;
2; is unreachable code.
And a sole return in JavaScript returns undefined. Like a function without a return does.
JS gramma from mozilla
http://www-archive.mozilla.org/js/language/grammar14.html#N-Statement
Note:
the OptionalSemicolon grammar state can sometimes reduce to «empty»
This question already has answers here:
What's the best way to break from nested loops in JavaScript? [closed]
(18 answers)
Closed 8 years ago.
I have a piece of JavaScript I can't get to work (Euler Project, problem 3), and I have nested loops as part of the solution. If a condition is met, I want to exit a child loop, and continue with the parent loop. Should I be using return or break to accomplish this?
I've read the answers here: Best way to break from nested loops in Javascript? but am still confused, especially on the answer that includes an anonymous function as part of the solution.
return always exits the current function.
If you need to exit a loop you should be using break which terminates the current loop, label or switch statement.
break exits the loop, and return exits the function, BUT... in javascript you can freely nest them, so you can have a function in a loop in a function in a loop etc. In this case, return terminates its nearest function and not the outer one. Example:
function foo() {
for(var i = 0; i < 5; i++) {
var bar = function() {
// whatever
return;
}
bar();
// after 'bar' returns, we're here and the loop goes on
}
}
PS I'm wondering why you need nested loops for Euler3... could you post your code?
To exit a loop use always the keyword break, unless you determine something inside the loop that makes you decide to exit the whole function, and in that case you use return keyword.
The link you posted, about an anonymous function is ingenious, that solution has 3 loops, but depending on a condition the programmer wants to exit the 2 inner loops simultaneously, but not the outer most, so he wrapped the 2 inner loops inside an anonymous function that executes for each iteration of the outer loop, so that when he decides to break the 2 inner loops, he can call return without exiting the outer most.
Regards.