Reputation: 950
Code Sample A
var isPrime = function (num) {
//for(i = 1; i <= num; i++) {}
if(num === 2){
return true;
}
return false;
};
var sumPrimesUpTo = function (num) {
for(i = 1; i <= num; i++) {
console.log(isPrime(i));
}
};
sumPrimesUpTo(5);
So we have a function that supposedly checks for a prime number and a second function that sums prime numbers up to a provided number. When you run this it outputs.
false
true
false
false
false
Now we have the same code sample but with the for loop in isPrime uncommented.
var isPrime = function (num) {
for(i = 1; i <= num; i++) {}
if(num === 2){
return true;
}
return false;
};
var sumPrimesUpTo = function (num) {
for(i = 1; i <= num; i++) {
console.log(isPrime(i));
}
};
sumPrimesUpTo(5);
This outputs
false
false
false
I don't seem to get why the for loop changes the output?
Upvotes: 0
Views: 54
Reputation: 9303
i
is scoped globally, you should use let
to keep i
scoped to the for
loop.
You could use var
as well but let
is a better choice because it will give you the scope you want and also not allow it to be re-assigned in this block.
var isPrime = function (num) {
for(let i = 1; i <= num; i++) {}
if(num === 2){
return true;
}
return false;
};
var sumPrimesUpTo = function (num) {
for(let i = 1; i <= num; i++) {
console.log(isPrime(i));
}
};
sumPrimesUpTo(5);
Upvotes: 5