Infinite for loops are apparently tricky. - javascript

Here I am once again. This is apparently the only way I know how to learn. What I am doing is making a for loop. Yes. Something so simple. Yet, I "have" a problem with them. More or less a problem with infinite loops. What I need to do is make a loop that counts down from 10...0. It seems easy for some of you. Yes I am very aware. I am nothing more than a student learning.
This is the code that I have:
for (var i = 11; i >= 1; i++) {
console.log(i);
}
I am stuck at this point. All that it does is crash my browser every time. Help is greatly appreciated. I would like a thorough explanation of what I am doing wrong, what I should do, and why I might have made this harder than it needed to be. Thank you!

For a loop to run from 10 to 0 iterator i should be decrementing in each iteration. But you are incrementing it instead so for loop never terminates.
for (var i = 10; i>=0; i--) {
console.log(i);
}

Everyone learns differently! In this case, you're asking the code to increment (aka add) with the ++ syntax. So, if i = 1, after i++ i = 2. Similarly i-- decrements (aka subtracts) from i.
Now, the first two parts of the loop check the value of i and continue the operation. In your case, you're asking the program set i equal to 10. If i is greater than 1, add 1 to it. That's where you're getting the infinite loop because i will always be greater than 1. What you want is. for (var i = 10; i >= 0; i--) {//code here};
You could also check out while and do/while loops.

Variable i starts at 11, and is then incremented by one each loop. Since the condition is that i >= 1, it never ends. You need to change it so that i decrements by one each loop, like this:
for (var i= 11; i>=1; i--){

First you need to learn difference between increments and decrements.
increments mean to add specific value to your variable
while on other hand decrements means to reduce the value of your variable by some specific number.
Now in your case i++ means you are adding 1 to your variable i with every iteration of loop, while to end your loop you have set the condition to i>=1
this results in an infinite loop which crashes your browser, as i would never be equal to 1 or i>=1 will never be true as with each iteration the value of i increased by 1 number, so it would continue execution, until your browser crashes.
What you are looking for is:
for (var i = 10; i >= 0; i--) {
console.log(i);
}
now i will start from 10
and will gradually reduce to 0 and your loop will end.
Hope it explained.

Related

basic Javascript While loop and boolean value questions

I would ask my instructor, but whenever I do, he gives me an even more vague answer to my questions, so I'm asking yall for help. We "learned" (i.e. watched videos) about for and while loops and I get it, I feel like I do, but whenever it comes to doing the assignments given, I feel like they don't make sense. Like back in math class in high school, they'd teach you about the problems, but then when it came time to do your homework, the problems were completely different from what you just learned about. For instance, it says the basic while loop structure is:
while(condition is true) {
//do something
}
But then in this assignment, it gives me:
// Another way to write a while loop is to have a boolean variable
// where the condition goes and then test every time if you need to
// change the boolean to false.
// Below we have a variable lessThan5 and it is set to true.
// Create a loop that tests if our variable 'j' is less than 5.
// If it is less than 5 then Increment it by 1. If it is not
// less than 5 then set our lessThan5 variable to be false.
let lessThan5 = true;
let j = 0;
while(lessThan5) {
}
We didn't learn anything about using boolean values in while loops and I feel like I'm meant to infer what to do, and what structure to use and I just have no idea. Aside from the fact I feel like the instructions to many of these questions are poorly worded, which only confuses me more!
So then there's this third one:
// Example of what the number game would look like:
// Couple things to note:
// Math is a built in object in javascript.
// Math.round() will round a decimal number to a whole number.
// Math.random() returns a decimal number between 0 to 1.
// (But not including 1)
function guessNumberGame(guess) {
let guessing = true;
let number = Math.round(Math.random() * 100);
while(guessing) {
if(guess === number) {
guessing = false;
} else {
guess = Number(prompt("That number didn't work. Try again: "));
}
}
}
// Problem 3
// We will give you a number through the 'num' parameter
// Create a while loop that will loop 'num' amount of times.
// For example if num is 3 then your while loop should loop 3 times
// If num is 20 then the loop should loop 20 times.
// Increment k every loop.
let k = 0;
function keepLooping(num) {
}
If this Problem 3 is meant to be related somehow to the number game example, I can't see it. I don't even know what it is I need to be asking. Does this make any sense to anyone? And nobody else is publicly asking questions about any of this, and it's making me feel stupid and like I am the only one too dumb to get what's going on. I was doing really well and ahead of schedule with all this until this point, but just none of this is making any sense to me.
Welcome to programming, JavaScript (JS), and StackOverflow (SO)!
Let's dive into this a little deeper. First, a quick JavaScript primer: in JavaScript, everything can be classified as either an expression or a statement. At a super high and not-technical level:
expression: something that produces a value
statement: an instruction to the computer
(For a much longer explanation, see here)
Often, statements have slots that can take expressions. Loops are a great example of that.
For example, 1 + 1 is an expression, since it produces the value 2. Even more simply, 1 on its own is also an expression, since it produces the value 1. while(/*some expression here*/) is a statement that has a slot for an expression. for(s1, e2, e3) is also a statement that has slots for statements and slots.
So, the while loop acts on an expression, and will continue to loop as long as the value returned by that expression is truthy. truthy and falsey is an interesting concept in JavaScript and can be a whole essay on it's own, but the tl;dr of it is that anything that == true is truthy, and anything that == false is falsey
So for your first question, 0 < 5 == true, while 5 < 5 == false. Thus, if you make the value of j be greater than or equal to 5, the loop will break.
let lessThan5 = true;
let j = 0;
while(lessThan5) {
// For each cycle of the loop, check if `j` is less than 5
if (j < 5) {
// If `j` is less than 5, increment it
j++; // This is equivalent to saying j = j + 1, or j += 1
} else {
// If `j` is not less than 5, set `lessThan5` to `false`
// Not when the loop goes to iterate again, `false == false`, and it stops
lessThan5 = false;
}
}
I think given the above you should be able to solve the third problem. Please let us know if you have trouble with it, show us what you try, and we'll be happy to help some more :)
Let's take a deep breath and relax. I'm a very senior developer and can't tell -- from your examples -- what's going on here. Maybe that's because your instructor is terrible, maybe it's because you've missed some context in your class, and so it's omitted from the question.
I can answer the two questions you've been given. Hopefully it'll be helpful.
First:
I do not know why your materials claim that a while loop might be written this way. I've completed the assignment, but it seems very odd. But if they want you to complete it, here's a solution.
// Another way to write a while loop is to have a boolean variable
// where the condition goes and then test every time if you need to
// change the boolean to false.
// Below we have a variable lessThan5 and it is set to true.
// Create a loop that tests if our variable 'j' is less than 5.
// If it is less than 5 then Increment it by 1. If it is not
// less than 5 then set our lessThan5 variable to be false.
let lessThan5 = true;
let j = 0;
while(lessThan5) {
if (j >= 5) {
lessThan5 = false;
} else {
j++;
}
}
Moving on to the second snippet, the second snippet does not, to me, appear to be related to guessNumberGame in any way.
And the solution to "Problem 3" seems useless to me. A loop that doesn't do anything is not useful in real life.
That said, the solution to "Problem 3" is as follows:
// Problem 3
// We will give you a number through the 'num' parameter
// Create a while loop that will loop 'num' amount of times.
// For example if num is 3 then your while loop should loop 3 times
// If num is 20 then the loop should loop 20 times.
// Increment k every loop.
let k = 0;
function keepLooping(num) {
while(k < num) {
k++;
}
}

closure and for loops consuing me

alright guys. every singe time i think i understand fundamental JS quirks i go insane and realize i don't at all... while the part of this that usually stumps people DOES NOT for me... i am so confused as to why this console.logs '10' ten times. WHY is it not '9' 9 times... the loop clearly says i < 10.... i don't understand why the loop runs an extra time to ten here...
for (var i=0; i < 10; i++){
setTimeout(function(){
console.log(i);
}, 1000);
}
to add to that why does this loop below respect the i<10 thing and produce 1,2,3,4,5,6,7,8,9.. clearly in the example below the loop respects the 'until i is less than 10 (which is 9) why does it not do that in the first example and run until i is 10?
for(var i=0; i<10; i++){
console.log(i)
}
everytime i think i understand this stuff i don't its actually starting to drive me a bit insane. ive been coding over a year now and still am confused by this. i understand the call stack stuff and the closure to a degree. most people get stumped and say it will print 9 every second etc... i get that part. but why is it 10 and not 9?! also plz in layman's terms as best you can. i understand that the ++ part actually runs at the beginning of each iteration (except for the first) but i still am so confused as to why ANYTHING with closure or call stack etc would create an extra run of the loop.
also if you are REALLY up for it too... why THE F*** does this produce '1' and not '2' lol...... please answer the first question though. that is my primary confusion right now
for(let i=0; i<2; i++){
setTimeout(()=>console.log(i))
i++
}
actually at last iteration the for loop increment i value to 10. then the for loops evaluates the condition i < 10. since i is now 10 the block statement doesn't run again, but its current value is 10.
the reason the second one prints 1,2,3,4 and the first prints 10,10,10 is because the second one the code is sync, while the first one is async (setTimeout). setTimeout will be only be executed after the callstack empties. by that time i will be 10. since i is defined as var, which is not blocked scoped like let, all console.log(i) prints 10.
the second goes until the 9 because once it reaches the last iteraction i is 9 and prints 9. Then i is updated to 10 and the next block doesn't run because now i < 10 is no more valid. i is now 10 but there is no more console.log to be executed. if you console.log(i) after the for loop will print 10.
Meanwhile the async code, each setTimeout can only execute console.log once the callstack from the event loop is clear. when the event loop is clear, the for loop already has finished its execution and i is now 10. now each console.log will be executed and the value they find for i is 10.
A for loop is (more or less) the same to a while loop, and when looking at that we might find the answer:
let i = 0;
while(i < 10) {
console.log("inside loop", i); // 0,1,...,9
i++;
}
// at this point, the loop exited with i = 10
console.log("after loop", i);
On the last iteration, i is 9 when passing the body, then it gets incremented to 10, then 10 < 10 evaluates to false and the loop exits. Then somewhen the timeout calls back and 10 gets logged.

Beginner query: Using function parameters with a for loop, skipping the loop for some reason

I imagine this is something pretty simple but I'm stumped and think this could be a good learning moment for me.
Here's the code:
var sumAll = function(lowRange, highRange) {
var sumOf;
var i;
for (i = lowRange; i > highRange; i++) {
sumOf += i;
}
return sumOf;
}
module.exports = sumAll
I'm working my way through the odin project, currently doing TDD section. So the function skeleton and final line of code was premade. The function parameters in this case are 1, 4. Expected result of 10.
Instead my test is throwing back undefined. I checked and this changes depending on what I define it as at the top.
It is as if it's skipping the loop all together, I've no idea why this would be.
A for loop's 3 major pieces can typically be understood like this.
Initialize the variable
Continue looping for as long as the condition is true
Change the variable's value after every iteration
During step two of the list above, your code is running i > highrange. This will immediately test false and skip your loop, because i has a value of lowrange, and I assume lowrange > highrange will never be true. What you want in its place is i <= highrange, "less than or equal to."
For loops are tricky, these little mistakes will follow you even into advanced territories. :o
Your for loop never executes because you set i equal to lowRange and the execute condition is i > highRange. I assume lowRange < highRange so it terminates without entering the loop, since it will run while i is greater than highRange, but it never is.
initialize your accumulator
var sumOf = 0;
and change your loop condition
for (i = lowRange; i <= highRange; i++) {

arr.splice() is timing out in loop - better way to replace arr[i]?

So I am having an issue with my solution, and I may be entirely off on what needs to be done. I keep timing out which makes me believe I have the .splice() in an incorrect location.
The problem:
You are given an array of integers. On each move you are allowed to increase exactly one of its element by one. Find the minimal number of moves required to obtain a strictly increasing sequence from the input.
Example
For inputArray = [1, 1, 1], the output should be
arrayChange(inputArray) = 3.
My Pseudo code
First check and see if the current index is greater than the next index. If not, continue check through the entire loop. If so, add one to the next index and test again until true. If you increment the next index by one, add one to a variable "moves". Return moves
function arrayChange(inputArray) {
for( var i = 0; i < inputArray.length; i++){
var addition = (inputArray[i+1]+1)
if(inputArray[i] >= inputArray[i+1]){
inputArray.splice(i,0, addition);
}
}
return inputArray;
}
My Error:
Execution time limit exceeded on test 1: Program exceeded the execution time limit. Make sure that it completes execution in a few seconds for any possible input.
Why your code fails:
for( var i = 0; i < inputArray.length; i++){//iterate until reaching end of array
var addition =(inputArray[i+1]+1);
if(inputArray[i] >= inputArray[i+1]){ //if its not increasing
inputArray.splice(i,0, addition);
}
}
Lets examine a sample input:
arrayChange([1,1]);
So inputArray[i] is 1, and inputArray[i+1] is 1.
Therefore it will go into the if, as 1>=1. So it will add 1+1 into the array,but not at the end but at i, so at position 0. It will look like this:
[2,1,1]
The loop will go on:
[2,2,2....,1,1]
It will never end.
To make it work, you must stop at array.length-1 :
for( var i = 0; i < inputArray.length-1; i++){
and you must insert at the right index,and also remove one:
inputArray.splice(i+1,1,addition);
Non array changing approach:
function numchanges(array){
var before=array[0],counter=0;
for(var i=1;i<array.length;i++){
if(before>=array[i]){
//we need to change array[i] to before+1, so:
counter+=(++before)-array[i];
}else{
before=array[i];
}
}
return counter;
}
console.log(numchanges([1,1,1]));//should return 3
How it works:
A proper strictly monotonically increasing function would have values like this:
[1,2,3,4,5,10]
So it might at least go one up, or it jumps up. So lets take one random array, and its valid counterpart:
[1,1,3,4,5,-1]
[1,2,3,4,5,6]
So the changes needed:
[0,1,0,0,0,7] => 8
So the upper code keeps the valid number ( before ) and the needed change while iterating from left to right. current starts with the first array item:
before=array[0];//1
But we dont need to change the first array element, so we start at i=1.If this number is valid, so
before<array[i]
we just go on:
before=array[i];
i++;//due the for loop
If not, its not valid and we need a correction.
result+=before+1-array[i];
So if the last was 5 (=before) and now weve got -10 (=array[i]), we need to correct it to 6 (=before+1);
result+=6--10//==16
So we need another 16 corrections...

Why doesn't this loop return to the first index?

I'm confused here, when the if is true it does not go back to the first index. I don't know why I have done it before, but I did not save in a safe place. Now I have spent a lot of time looking for the solution, can someone help me?
var digital = document.getElementById("placeDiv").style;
var abc = ["red","blue","green"];
for(var i=0;i<3;i++){
digital.backgroundColor=abc[i];alert(i);if(abc["green"]){i=0};
};
Try this:
if(abc[i] === "green")
I don't know what you are planning to do. But your code will be in a infinite loop.
The result of this will be an infinite loop because when the loop reaches the 3rd object in the array it will start again from the 1st.
If you want an infinite loop it is cleaner to use while(true){}
var digital = document.getElementById("placeDiv").style;
var abc = ["red","blue","green"];
for(var i=0;i<abc.length;i++){
digital.backgroundColor=abc[i];
alert(i);
if(abc[i]=="green"){
i=0;
}
}
Not sure what you are trying to do, but maybe what you want is:
if (abc[i] === "green") {
But keep in mind that even though i gets reset to 0 when this condition is met, it immediately gets bumped up to 1 at the top of the loop. You would then be in an infinite loop with i going from 1 to 2 and then back again.
You need to switch to a while loop. Currently you will end up with a loop counter that will never be lower than 1 after the first execution. You are setting i to 0 but when then loop finishes it is incremented. I changed your code to a while loop with an if-then test to either increment the loop counter or set it to zero. It works fine for me now.
var i=0;
while (i<3){
digital.backgroundColor = abc[i];
//alert(i);
if(abc[i] === "green"){
i=0
} else {
i++;
}
}

Categories

Resources