-2

I don't know what is the missing code here it's giving me a headache because of the conditional statement.

Add the missing codes so that the condition below will evaluate to TRUE and print “it works!” in the console.

if (num == 100 && num== 200 && num==300) {
    document.write('it works!');
} else {
    document.write('it doesnt');
}
Jeremy Thille
  • 26,047
  • 12
  • 43
  • 63
NewProg
  • 37
  • 1
  • 1
  • 9

3 Answers3

2

If that's the real question you can do it using valueOf:

    var Num = function() {
      this.values = [100, 200, 300];
      this.index = -1;
    };
    Num.prototype.valueOf = function() {
      this.index++;
      return this.values[this.index];
    };
    var num = new Num();
    if (num == 100 && num == 200 && num == 300) {
      console.log('it works!');
    } else {
      console.log('it doesnt');
    }

It may look like num is 100, 200 and 300 at once but the if statement has 3 expressions: num == 100 then num == 200 and then num == 300. Each time you compare num to a number with type coercion (using == instead of ===) the valueOf will be invoked, that changes inner state of the num object instance so next time you compare it'll produce a different value.

I would not use type coercion comparing == and instead use ===, when you use a linter it will usually complain when using == as it can cause some unexpected behavior and makes your code less predictable.

HMR
  • 37,593
  • 24
  • 91
  • 160
1

You need to use logical OR ||, because with logical AND && the condition is never true, if you take the same value of num.

if (num == 100 || num== 200 || num == 300) {

But in Javascript everything is possible, like: Can (a== 1 && a ==2 && a==3) ever evaluate to true?

Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

It will not satisfy the condition at a time and print "it doesn't". So the solution would be like this. if(num==100 || num==200 || num==300)

Ajay
  • 23
  • 6