0

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);
1
  • That happens because the loop will never be run, i < 2 && c !== w[i] is false at the beginning of the loop (see: c = 3, w = [3, 4] --> w[0] === 3 and c === 3). Commented Nov 4, 2018 at 19:23

2 Answers 2

3

Instead of using for loop, if you only wish that the boolean variable must be switched on satisfying only one condition, you can use some() method. Using this, the loop will not iterate through all the objects and will stop once your condition is satisfied. Example shown below:-

var arr = [3,4,5];
var m = 4;
var bool = false;

array.some(function(item) {
if (m === item){
bool = true;
}
});
alert(bool);

So this will basically give you alert true once you get the matching object from an array.

Sign up to request clarification or add additional context in comments.

Comments

0

The condition from for is checked also before first iteration, so the if is not fired. Check out code like this:

var c=3;
var w=[];
w.push(3,4);
var m=false;
for (var i=0;i<2 && c!==w[i];i++){
    console.log('In loop')
    if (c===w[i]){
        m=true;
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.