Reputation: 373
I'm writing a for loop for a project that prompts the user to input a number and keeps prompting, continually adding the numbers up. When a string is introduced, the loop should stop. I've done it with a while loop, but the project states that we must do it with a for loop also. The problem is that the prompt keeps running even when 'a = false'. Could someone explain javascript's thinking process? I want to understand why it keeps running back through the loop even though the condition isn't met. Thank you
var addSequence2 = function() {
var total = 0;
var a;
for (; a = true; ) {
var input = prompt("Your current score is " +total+ "\n" + "Next number...");
if (!isNaN(input)) {
a = true;
total = +total + +input;
}
else if (isNaN(input)) {
a = false;
document.write("Your total is " + total);
}
}
};
Upvotes: 1
Views: 1842
Reputation: 29431
Here's your fixed code :
var addSequence2 = function() {
var total = 0;
var a = true;
for(;Boolean(a);) {
var input = prompt("Your current score is " +total+ "\n" + "Next number...");
if (!isNaN(input)) {
total = total + input;
}
else{
a = false;
document.write("Your total is " + total);
}
}
};
Upvotes: 0
Reputation: 857
There is a difference between a = true
and a == true
.
Your for-loop is basically asking "can I set 'a' to true?", to which the answer is yes, and the loop continues.
Change the condition to a == true
(thus asking "Is the value of 'a' true?")
To elaborate, in most programming languages, we distinguish between assignment ("Make 'x' be 4") and testing for equality ("Is 'x' 4?"). By convention (at least in languages that derive their syntax from C), we use '=' to assign/set a value, and '==' to test.
If I'm understanding the specification correctly (no guarantee), what happens here is that the condition condenses as follows:
Upvotes: 3
Reputation: 583
for (; a = true; ), you are assigning the value to the variable "a" and it will always remain true and will end up in infinite loop. In JavaScript it should a===true.
Upvotes: 1
Reputation: 323
You should use a == true instead of a = true......= is an assignment operator
Upvotes: 1
Reputation: 677
for (; a = true; ) <-- this is an assignation
for (; a == true; ) <-- this should be better
Upvotes: 0
Reputation: 71
a == true
. The double equal sign compares the two. Single equal assigns the value true
to a so this always returns true.
Upvotes: 0
Reputation: 3717
I suspect you want your for to look like this :
for(;a==true;)
as a=true is an assignment, not a comparison.
Upvotes: 0
Reputation: 544
Try using the equal to operator, i.e. change
for (; a = true; ) {
to
for (; a == true; ) {
Upvotes: 2