Infinite for loop on decremented by 2 - javascript

I want to decrement the value var i by two but I am stuck in infinite loop.
for(var i=10;i>=0;i-2){
console.log(i);
}
I found that the code given below is working but what is wrong with the above code.
for(var i=10;i>=0;i-=2){
console.log(i);
}

Breaking down what happends in a for loop helps explain this.
iteration the var i = 10 is called
iteration it runs i-=2 which is short hand for i = i - 2
(the wrong code i-2 would never designate i with a new value)
it would then check the condition in the middle of the for loop.
same as 2nd
...
untill i >= 0

but what is wrong with the above code.
since i-2 is actually not decrementing the value at all, so the value of i never changes in the loop and i >=0 never fails, which is why the loop never ends.

In the upper code, the loop incrementor is just calculating what i-2 is. It never assigns the result back to i.

the first code sets i to 8 (probably), but never changes i after that. no incrment(i++ or decrement i-- or any variation of the two)

Related

Why cant I scroll browser window in a loop in console?

I want to scroll down the browser window in a loop in console. I want it so that every time a scroll down (x)px down I stop, do something and then scroll (x)px again and then stop etc. until the page with ends (its a very long one, I want to parse info from it).
But when I started I stumbled upon an issue, that the scrolling function is executed only once, after the loop ends.
let i = 0;
scrollDownTillEnd = () => {
for(i; i<100; i++) {
window.scrollBy(0, 1000);
};
scrollDownTillEnd();
(it is a simplified example, but the idea should be clear)
I put the code in the console, being on a page I want to scroll, and get then the value of i at the end of the loop and only one scroll down.
Please, explain me, why this piece of code behaves like this and how to make it work, as I mentioned before (in every loop it scrolls a little bit).
Thank you!
Let me help address a few issues going on here.
1) You have an infinite loop going on because you are not checking that i is less than 100 even though you are incrementing it each time. You need to check that i < 100 so that the loop will eventually end. In your loop, 0 will always be less than 100 so the loop will never end.
2) You have a syntax error in your example because you're not actually closing out the scrollDownTillEnd function with a curly brace before calling the function itself.
3) Lastly, as good practice, you need to reset your i variable to 0 each time so that we can run this piece of code over and over again. The way you have it set up in your example, since i will be equal to 100 at the end of the first run, the loop won't ever run again after that until you reset i to 0 again. The easiest way to do this is to just initialize i to a value of 0 each time you execute this loop.
Try something like this:
scrollDownTillEnd = () => {
for(let i = 0; i < 100; i++) {
window.scrollBy(0, 1000);
};
};
scrollDownTillEnd();
You can use setInterval() since for loop will executes only once
function scrollDownTillEnd(countryDropdownList)
{
let scrollingInterval = setInterval(function(){
window.scrollBy(0,1000)
// write your condition
if (window.scrollHeight > 10000)
{
clearInterval(scrollingInterval)
}
},100)
}
scrollDownTillEnd();

How to do something indefinitely until a condition is met, with no loop?

Whenever I use a loop, the tab crashes. I can't seem to figure out how to work this out. I just start typing while(true) {document.getElementById("loadingText").textContent++;} and before I can type if(document.getElementById("loadingText").textContent === "100") {break;} the screen freezes and the tab crashes. Can someone help me?
Since you're using an online editor with real-time browser updates based on changes, you need to make sure you don't make your code loop infinitely. Sadly that's what while (true) { // code } does if there's no code in the statement to break the loop.
For the timebeing, until you've figured out the meat of that loop, just intentionally cause an error:
while (i <= 100) { // code }
which you can go ahead an amend until you get the desired result.
There are a couple of things you should take into account.
1) You should cache the element once so you're not repeatedly grabbing it on each loop iteration.
2) textContent is a string, so you can't use el.textContent++ as it won't be successfully evaluated.
3) You'll find it difficult to slow a traditional loop down so that you can see the number increment properly.
So here's a method using setTimeout instead of a traditional loop.
// Cache the element
const el = document.getElementById("loadingText");
(function displayNumber(n, end) {
// Repeat until the iteration number (n)
// is 10 (for this example)
if (n <= end) {
el.textContent = n;
// Wait 0.5s then call the function again with an increased n
setTimeout(() => displayNumber(++n, end), 500);
}
// Pass in the initial number, and the end limit
}(1, 10));
<div id="loadingText"></div>
You are asking if your property is === "100" as ++ increment the numeric value, the loop never breaks, compare to 100 instead of "100" as string
if(document.getElementById("loadingText").textContent == "100") {break;}
or
if(document.getElementById("loadingText").textContent === 100) {break;}
I dont think that a textContent could be incremented. Try Node.value++.
If this still doesn't works. To run an infinite loop you can use setInterval(); method.
example:
var i=0;
var z = setInterval(foo,10);
function foo() { alert(i); }
In the above example the function foo() will execute infintely with a gap of 10 mili seconds. You can put it to 0 ms as well if you wish to.

Javascript Array Length Confusion Issue

I am having trouble understanding an answer to a question.
I was told to find the last element in any array the answer would be for example :
alert(countries[countries.length - 1]);
However, I was told to go loop through the entire list of array I would put for example
for(counter=0; counter < presidents.length; counter++) {
document.write(presidents[counter]);
}
Question is....
Why is is counter < presidents.length and not counter < presidents.length-1 like in the example before?
Because you need to print the last value too.
For example, let the array be,
var presidents = ["one", "two", "three", "four"];
Here, presidents.length = 4.
Now, if you do counter < presidents.length-1 then counter goes from 0 to 2.
You either need to do
counter <= presidents.length-1 or counter < presidents.length
in order to make counter go from 0 till 3.
PS: Array indices begin from 0 in JavaScript.
Because array index start with zero and last element will be in (size-1) position. In for loop, you are using less than(<) symbol. It will be < size or <= (size -1).
Probably also worth mentioning that the for loop works because of when things happen. Take the following statement:
for ([initialExpression]; [condition]; [incrementExpression]) {
[statement]
}
initialExpression is evaluated immediately and is typically used to create a variable to increment, as you did with counter=0.
condition is evaluated before executing the statement. If the condition is truthy, the statement is executed; if not, the loop is terminated.
incrementExpression is evaluated after executing the statement. So, incrementing counter here informs the next condition evaluation.
Putting it together, the condition evaluation looks like this:
if 0 < presidents.length // true
if 1 < presidents.length // true
. . .
if 44 < presidents.length // true and will produce the final president element
if 45 < presidents.length // false and terminate the loop

For Loop does not reach 5

I am working on CodeAcademy trying to learn some JavaScript and I have encountered this interesting thing actually. Please take a look here:
for(var counter = 100; counter > 0; counter = counter - 5){
console.log(counter);
}
Here I tell the loop to loop through an print the counter number as long as counter is bigger than 0, however it only ends up printing 100..95..90 etc down to 5.
I do know how to fix this, by just adding a simple equals sign just after the bigger than sign.
Like this:
for(var counter = 100; counter >= 0; counter = counter - 5){
console.log(counter);
}
But I am interested in knowing why this doesn't work differently?? I mean it ends the output with a 5, 5 is bigger than 0, isn't it?? When I do put a equals sign before the bigger than sign, it really should output some undefined number cause it should loop even then counter is equal to 0. My head hurts from this.
Could someone please explain, thank you :)
No, it should not continue the loop once it reaches zero. The way for loops work is this:
for (initialization; condition; increment) {
body;
}
And it performs these operations in this order:
initialization
loop {
condition true? then:
body
increment
else:
stop loop
}
So when the counter reaches zero, the condition will be false, and the body will not be executed with the counter having value "0", it will simply stop. When you put >=, however, the condition is still true at that point.
The English translation of the "for" loop is:
Set counter to 100
If counter > 0 is not true, end this block
Run this code block (in this case, log counter)
Reduce counter by 5
Go back to step 2
So in this case, if counter is zero, it is not > 0 and therefore the code doesn't go back to step 2. Whereas in the second case, it is >= 0 so it runs through one last time.
Let's see what's happening here,
When you say counter > 0, then it should continue till it is strictly greater than zero. Since zero is not greater than itself, therefore the loop stops at 5.
When you change the expression to counter>=0, then, it tells the compiler to continue till counter is greater than OR equal to zero, therefore it goes on to print zero as well.

Using the stop in a loop with conditionals

Hello there I'm finding it difficult to understand some basic JavaScript
I have written a loop that counts down from 10 to 0 and I'm using console.log to print that value to the console. Inside the loop an if statement is used to check if the number is 0, if it is then console.log prints "Blast Off!" instead of a number.
Here is my working code:
for (i=10; i>=0; i--;)
{
if (i === 0)
{
console.log("Blast Off!");
}
else
{
console.log(i);
}
}
However what I'm desperately trying to understand the is the stop of the for loop which is:
i>=0;
Is this effectively saying if i is greater than or equal to zero then progress through the loop decrementing i each time, then stop when zero is reached?
Conversely when I change the for loop code to what is shown below, is this effectively saying if i is less than or equal to zero then progress through the loop decrementing i each time until zero is reached?
What is the reason for the loop not printing, if the stop is changed? Is this because i never holds a value that is less than or equal to zero, meaning the loop will not run?
i<=0;
Any help clearing this up for me would be appreciated massively.
Your understanding sounds correct. When the for statement is executed, the first expression assigns a value to i (in this case, 10). The second expression is a comparison. It will evaluate to true if i is greater than or equal to 0 (which it is, as we just set it to 10). Because the condition evaluates to true, the loop body is executed. After that, the third expression runs, decrementing the value of i, and that process is repeated until the condition evaluates to false (when i reaches 0).
By changing the condition to i <= 0, it will evaluate to false the first time around, so the loop body will never execute.
The exact behaviour is detailed in the ECMAScript specification, in the section on "the for statement".
Imagine a set of stairs, 10 steps.
--
| i = 10
--
| i = 9
--
| i = 8
--
| i = 7
--
| i = 6
--
| i = 5
--
| i = 4
--
| i = 3
--
| i = 2
--
| i = 1
--
| i = 0
Imagine you are climbing down the stairs, in your head, you subconsciously think: "Until I get down to the bottom-most step, I'll keep stepping down".
Similar to the for loop:
for (i=10; i >= 0; i--)
This says, I start from the top-most, the 10th step as depicted in the image, then you climb down one step each time (or iteration) i--, then everytime after you step down, you check, "Am I at the bottom of the stairs already? No? Keep going", that's when you check i >= 0
Hope that helps you out of your desperation ;)
I think your problem is the semicolon extra in the loop:
this is your code:
for (i=10; i>=0; i--;)
try this:
for (i=10; i>=0; i--)
Maybe that's the reason for the loop is not printing.
for (i=10; i>=0; i--) means this:
start with i=10
if not i>=0 then execute. This is the "stop" condition.
after each loop do: i = i-1
On this example you won't enter the loop because the repeat condition fails.
Hello ok first "i=10" and
i>=0
is the condition for the loop. So everytime the i is greater or equal to zero the loop is returning continueing. Since you are using i-- so when i becomes negative less then zero the loop will stop.
if you use
i<=0
the condition for the loop is false so it won't enter the loop to execute the code inside bracket
Yes, if you were to change
for (i=10; i>=0; i--)
to
for (i=10; i<=0; i--)
the first condition check is false, as i is not smaller or equal to 0, so it will not eter the loop.
The condition is checked before entering the block, but after the incrementation. The incrementation is skipped the first interation. The first time the condition is not met, the whole loop will stop completely.
So if you use i<=0, the condition is not met, and the for will stop.
If you want to skip the zero, you should have the condition i>0.
You understand correctly, the i>=0 in your for loop tells to run the loop as long as i is greater than or equal to 0.
The i-- decrements the value of i on each iteration of the loop.

Categories