This question already has answers here:
Two semicolons inside a for-loop parentheses
(4 answers)
Empty for loop - for(;;)
(4 answers)
Closed 3 months ago.
It's in JavaScript not C language, so I think it's not duplicate
I was testing some code and I found this one :-
for (;;) {
console.log("test");
}
And the iterations kept going forever
I was wondering what does this ;; mean? And what is its use case?
PS :- don't run it as it will freeze for infinite iteration.
The reason that for(;;) loops forever is because for has three parts, each of which is optional. The first part initializes the loop; the second decides whether or not to continue the loop, and the third does something at the end of each iteration. It is full form, you would typically see something like this:
for(i = 0; i < 10; i++)
If the first (initialization) or last (end-of-iteration) parts are missing, nothing is done in their place. If the middle (test) part is missing, then it acts as though true were there in its place. So for(;;) is the same as for(;true;), which is the same as while(true).
Related
This question already has answers here:
Explanation of `let` and block scoping with for loops
(5 answers)
Re-assign/declare a const variable in a JavaScript for-loop and save it more than one time with different values?
(2 answers)
const variable can be redeclared inside while loop even though it should be constant
(1 answer)
Closed last year.
In the code below, is ele available only for an individual iteration of the loop?
for (var i=0; i<3; i++){
const ele = i
console.log(ele)
}
I'm thinking this should be the case, otherwise there will be a
Syntax Error: Identifier 'ele' has already been declared
every time the loop iterates after the very first time.
I could not find a way to confirm this using console.log(), so looking for a concrete answer.
EDIT: To clarify, I understand that ele is valid within the for loop only. My question is specifically if the scope is ' reinstantiated' every iteration of this loop or not. It definitely looks like it, but I haven't heard or read that explicitly anywhere yet.
why do not directly use console.log(i) ?
howei think you should try to use var or let instead of const
This question already has answers here:
Short circuit Array.forEach like calling break
(30 answers)
Closed 3 years ago.
I'm working on a homework problem using JavaScript. I have a solution that currently works, but I am sure that it is not the most efficient way to do it. I am iterating over an array to check if any element meets a certain condition. But there doesn't seem to be a way to exit the forEach() function early. In other languages, I have used break to quit a forEach loop early. Does something similar exist in JavaScript?
My code (simplified for this question):
let conditionMet = false;
numbers.forEach((number) => {
if (number % 3 === 0) {
conditionMet = true;
// break; <-- does not work!
}
});
Rather than using Array.forEach, you can use Array.some (see docs). This function iterates over the elements of the array, checking to see if any element meets a certain condition. If an element is found that meets the condition, the function stops iteration, and returns true. If not, the function returns false. This means that you can also skip the step of initializing conditionMet to false.
Your code can therefore be simplified as:
let conditionMet = numbers.some(number => (number % 3 === 0));
You can’t break .foreach() loop unless through an exception
So you can choose another tool like a simple for loop.
This question already has answers here:
How do I work around JavaScript's parseInt octal behavior?
(10 answers)
parseInt method in JavaScript
(6 answers)
Closed 3 years ago.
Time for some more education.
I've come across a javascript 'for loop' which loops through a nested object. What does the ,10 portion, represent in the condition statement?
for (var x = 0; x < parseInt(myObj[myCategory][MySubCategory]['amount'], 10); x++)
{
// stuff happens
}
I am not finding any documentation that talks about this so I presume I'm just unclear on what I would even search on. Thanks.
Notice, in your example, that 10 is the 2nd argument of the parseInt function.
The ,10 is for specifying a base of 10.
See radix.
You'd think base 10 would be the default, but it isn't; you need to specify this each time you call the parseInt function.
This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
In JavaScript, what are specific reasons why creating functions within a loop can be computationally wasteful?
(2 answers)
Closed 8 years ago.
I checked over my script the other day with JSFiddle and got a warning on one of the lines: Don't make functions within a loop.
for (x = 0; x < 10; x++) {
if (moment(now) > moment(then)) {
doIt(x); // do it now
} else {
timeTillEnd = moment(then) - moment(now);
setTimeout(function () {
doIt(x); // do it later
}, timeTillEnd); // <-- flagged here
}
}
Why shouldn't I make functions within a loop in Javascript?
Also: Could the usage of a function in the particular situation shown here be problematic?
What you are trying to do is probably wrong, the x variable might not be what you expect it to be. See the following link:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures#Creating_closures_in_loops.3A_A_common_mistake
And they are also relatively expensive to create.
Each function comes with the closure of the variables it uses, that is an unnecessary overhead if you are doing "normal imperative programming" and just want to make the code look clearer by defining inner functions for sub-tasks:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures#Performance_considerations
In your case, it seems that you actually need a function with its closure, since you are deferring some computation, but make sure that you do the proper value capture.
Because it can lead to unexpected closure behaviour (the captured variable will have the value assigned in the last iteration of the loop). You will also get a new instance of the function for each loop which is wasteful of resources.
Modern browsers take a third argument for setTimeout which is the argument to the function. See here. This also gets rid of the problems with closures.
This question already has answers here:
Javascript infamous Loop issue? [duplicate]
(5 answers)
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 9 years ago.
Currently working on a piece of code that is supposed to add eventlisteners to images on a page in a dynamical way.
var images = document.getElementsByClassName("imageBox");
function imageZoomer(imageName) {
console.log(imageName);
}
for(var i = 0; i < images.length; i++) {
images[i].addEventListener("click", function(){imageZoomer(i)}, false);
}
However the i is showing different values then I expect. At first everything is going wel. It iterates just like it's suppose to do. But on my test page with 2 images the console log reveals '2' at both the images.
This happens because i keeps incrementing and by the time you click an image i is probably images.length - 1. You need a way to save the current i in each handler. You can store that value on each image (images[i].index = i; usually works) and retrieve it later but finding the object is a pain - it'd end up being something like:
images[i].index = i;
images[i].addEventListener("click", function(e){imageZoomer(e.target.index)}, false);
However, I've found the slickest way to do this is using an IIFE (read: iffy - Immediately Invoked Function Expression) to restrict the scope of i to whatever it was when the event was created. That looks something like:
images[i].addEventListener("click", (function(i){return function(){imageZoomer(i)}})(i))
IIFEs are super powerful. Take a look at Ben Alman's post: http://benalman.com/news/2010/11/immediately-invoked-function-expression/