I'm working on an assignment where a boolean has to switch after a variable is matched to a value in an array. The variable has to be matched with the value in the array using a for loop. However, I'm able to switch the boolean before I introduce the for loop. But after I introduce the for loop, the boolean is stuck to its original value of false.
Can somebody explain why this is happening?
Can I also request, I'm not looking for 'how to do this' but rather an explanation as to why is it happening - so I will appreciate if you do not recommend to me 'another better way' of achieving this - I just want to understand the concept as I'm a beginner.
The code I'm using before the for loop (which changes the boolean correctly) is:
var c = 3;
var w = [];
var m = false;
w.push(3,4);
if (c === w[0]){
m = true;
}
alert (m);
However after I add the for loop counter and also change the if condition from c===w[0] to c===w[i], I only get the 'false' alert using the below code:
var c = 3;
var w = [];
var m = false;
w.push(3,4);
for (i=0; i<2 && c!==w[i]; i++){
if (c === w[i]){
m = true;
}
}
alert (m);
i < 2 && c !== w[i]isfalseat the beginning of the loop (see:c = 3,w = [3, 4]-->w[0] === 3andc === 3).