Kashan
Kashan

Reputation: 1

BOOLEAN not working after adding FOR LOOP JavaScript

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);

Upvotes: 0

Views: 2107

Answers (2)

Sunny Parekh
Sunny Parekh

Reputation: 983

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.

Upvotes: 3

Alien11689
Alien11689

Reputation: 471

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;
    }
}

Upvotes: 0

Related Questions