simple do/while loop infinite loop issue - javascript

Okay first off, im very new to javascript and doing some tutorials to try and learn the language. My problem is probably something incredibly simple, but i can't figure it out!
Okay so ive made a very simple do/while loop. All this should do is print "do condition, only once" a single time to the console and print "do" 5 times to the console.
However it goes into an infinite loop.. probably because im defining the variable "doCondition" in the wrong place, but i cant figure out where else logically i should place it.
Any help gratefully recieved! If you could also explain where i went wrong too, i would really appreciate it.
Many thanks,
var doWhileLoop = function(text){
var doCondition = 5;
do {
console.log("do condition, once only");
};
while(doCondition > 0){
console.log(text);
doCondition--;
}
}
doWhileLoop("do");

do.. while syntax is incorrect, in your case, it goes like
var doWhileLoop = function(text) {
var doCondition = 5;
//beginning of loop
do {
console.log(text, doCondition);
doCondition--;
} while (doCondition > 0); //end of loop
};
doWhileLoop("do");
open console....
EDIT
while loop body won't execute as condition fails
var whileLoop = function(text) {
var condition = 0;
//beginning of loop
while (condition > 0) {
console.log(text, condition);
condition--;
} //end of loop
};
whileLoop("while");
open console....
do while loop body will execute once even if condition fails
var doWhileLoop = function(text) {
var condition = 0;
//beginning of loop
do {
console.log(text, condition);
condition--;
} while (condition > 0); //end of loop
};
doWhileLoop("do while");
open console....

This is not because of variable doCondition. It is because you are writing your do-while wrong. Check this out.
var doWhileLoop = function(text){
var doCondition = 5;
do {
console.log("do condition, once only");
doCondition--;
}while(doCondition > 0)
}
doWhileLoop("do");

This is the difference between a pre-conditioned loop (while(condition) {...}) and a post-conditioned loop (do{...}while(condition);).
The main difference is that a post-conditioned loop will always run the code block at least once before evaluating the condition, whereas a pre-conditioned loop will first attempt to evaluate the condition before running its code block
In your examples you've forgotten the condition in your post-conditioned loop, so it loops for ever.
References:
do...while (post-conditioned loop)
while.... (pre-conditioned loop)

What you have isn't a single loop, but two separate loops. A do {} while() loop and a while() {} loop only differ in whether the condition is evaluated before or after each iteration.
There is no initial "do once" step in a do...while loop. Just put the code that you want to execute once before the loop:
var doWhileLoop = function(text){
var doCondition = 5;
console.log("do condition, once only");
do {
console.log(text);
doCondition--;
while (doCondition > 0);
};
doWhileLoop("do");

Related

for loops with if statement in JavaScript

I'm new to javascript so please bear with me. I was playing around with for loops and I wrote a loop that is supposed to loop if a variable is less than the specified amount and if the variable is greater than or equal to the specified amount the loop breaks out and console logs that the loop is done but the code is only running and displaying what the for loop condition met is it does not display if the if statement condition is met. Where did I go wrong. Any help is appreciated. Thanks in advance.
var ran;
function test(){
//runs a program that counts a line
const ran = lineCount;
for (ran;ran < 20;) {
if (ran >= 20){
console.log("loop is done")
}
console.log("loop is running")
test()
}
It's hard to decipher what you are trying to do. But I mainly changed:
Change from const ran to let ran.
Use a conventional setup for for-loop which includes, variable declaration and variable increment
Removed recursively
function test() {
for (let ran = lineCount; ran < 20; ran++) {
if (ran >= 20) {
console.log("loop is done");
}
console.log("loop is running");
}
}

How do I make this continue iteration through the FOR loop. Stuck on index 5

I'm building Connect Four per my beginner's project for the course I'm taking. I can't get it to move on past index 5. It seems to still return true that index 5 is undefined, even though after I click it the first time, it has turned red. I thought it would, per following click, run the for loop, starting with 5 again, but that it would then return False, and go back to the next index, 4, checking that one, and so forth. I have looked up a lot and I am just stuck. I can't figure it out.
I know that the code is not complete for the long run of the game; I'm just trying to understand this step, however ugly the code might be, so that I can move on to another piece.
var gClass = $(".G")
function returnBackgroundColor(rowIndex,colIndex){
// console.log($(colIndex[rowIndex]).prop("background-color"));
// console.log(rowIndex);
return($(colIndex[rowIndex]).prop("background-color"));
}
function changeColor(row, someClass){
someClass.eq(row).css("background-color","red");
}
function checkColor(someClass){
someClass.click(function() {
for (var row = 5; row > -1; row--) {
if (returnBackgroundColor(row, someClass) === undefined){
console.log(row);
return changeColor(row, someClass);
}else {
console.log("False");
}
}
})
}
checkColor(gClass)
You can use increment instead of decrement. And it is better to use dynamic endpoint in the loop
That's because of return changeColor(row, someClass);, here you are returning from the function overall. and ending the for loop.
If you want to go to the next index just use continue, but this isn't necessary since your scope is already done
for(let i =0; i < 5; i++)
for (var row = 5; row > -1; row--) {
if (returnBackgroundColor(row, someClass) === undefined){
console.log(row);
changeColor(row, someClass);
} else {
console.log("False");
}
}
You are misusing .prop in your returnBackgroundColor function. $.prop returns html properties and will not work directly on styles. You may try something like this to compare against instead: $(colIndex[rowIndex]).css('background-color')

javascript node.js How to avoid While(true) in this situation?

I have read that use of 'while(true)' is a big no-no and use of 'while(condition)' or 'do...while(condition)' is recommended(1).
Can you tell me how to do that here -
while (true){
get some data;
if(condition based on data above), do something;
else(break);
} //repeat until break reached
I could use 'do...while' (see below) but that repeats the 'if' condition so this doesn't seem to be the best option -
do{
get some data; //must happen first to get info to create condition
if(condition based on data above), do something;
} while(condition based on data above);
It can be more simple like this, with an example:
var x = 0;
console.log("Entering loop");
while(true){
// always make sure to update something in your condition
// so you dont fall into an infinite loop
x++;
console.log(x); // mostly demostrative
if(x===3) break; // condition to determine when should the loop stop
}
console.log("Out of the loop");
There is no problem using while(true).
The no-no you read is because it is a potential issue that can be resulted into an infinite loop.
So if this is the case, you can use a counter to break the loop if nothing happens until that. for eg, max_attempt = 100.
Why not just do:
for(get some data; condition based on data above; get some data;) {
do something;
}
E.g.:
for(var i = Math.random(); i < .8; i = Math.random()) {
console.log(i);
}
I would use something like this:
while (condition based on data above){
get some data;
do_something;
}
Example:
while (variable_boolean == false && variable_num <= 10){
variable_2 = variable_num * 5;
}

Missing a ; after a for loop: Error found in JS Lint and with appendChild

I'm trying to remove a appendChild and keep getting the error -
SyntaxError: missing ; after for-loop initializer
I've never seen this error before. Here is the code that I have.
What is missing here?
var allChildren = document.getElementById("box").children;
var moving = document.getElementById("box2");
var newLocation = parseInt(moving.style.top, 0);
var newLocation2 = parseInt(moving.style.left, 0);
for (imageCheer); {
if (newLocation2 = moving.style.left && newLocation = moving.style.top)
{
return x;
allChildren.removeChild(list.childNodes[0]);
}
for (imageMarsh); {
if (newLocation2 = moving.style.left && newLocation = moving.style.top)
{
return x;
allChildren.removeChild(list.childNodes[0]);
}
}
I think for (var i in imageCheer) {..} would work
You for loops are syntactically incorrect. Typically they have the form for (init; condition; step). EG for (var i = 0; i< 10; i++) . your loops are missing condition and step.
You also should remove the semicolon after for(); because otherwise your loop body won't be executed.
And your loop bodies are wrong too. What do you want to achieve with return x? Consider if you use return inside a function, it will immediately stop the execution of the function, the remaining statements won't be executed.
Also consider that an equality check in JavaScript is done with == or even better ===. A single = is an assignment.
And, finally you are missing some closing braces for the loop bodies.

Iterating through an array until random value isn't equal to anything

First of all, I am very new to programming so apologies in advance.
This is what I am trying to do:
1) Generate a random value into a variable using
questionNr = Random.Range(0, nNodes);
2) Compare that variable to an array by iterating through all its values
for(var i=0; i<usedQuestionList.length(); i++){
if(questionNr == usedQuestionList[i]){
//stuff
}
}
3) If any value of the array is equal to said variable's value, start from the beginning by generating a new random value and loop through the array again. The only way to pass/end the loop is when the random value is NOT equal to any of the values in the array.
The problem is that if I do this simple for loop, there's no way for me to go back and do everything again when the conditions are not met.
I'm pretty sure I'm just approaching the logic wrong and there's a simple way to do this that hasn't occurred to me, that's why I'm not adding any of the code from my failed for and while loop attempts. Any help appreciated, thanks!
You can set a flag that you can check after the loop has finished, maybe something like this:
//A function that will take a number and check against the array
var loopRandomNumber = function(number){
//A flag to be used if match is found
var foundMatch = false;
//Your simple loop
for(var i=0; i<usedQuestionList.length(); i++){
//Checking if match
if(number == usedQuestionList[i]){
foundMatch = true; //Match found
break; // Jumps out of the for-loop to be a little faster
}
}
//Calling this function again with a new random number if match found
if(foundMatch){
loopRandomNumber(Random.Range(0, nNodes));
} else {
//Handle your condition for if no match was found here
}
}
loopRandomNumber(Random.Range(0, nNodes));

Categories