0

Any direction on this block of code would be appreciated:

Variation One:

    var x = 'bar';

    function myFunction(){

        if (x === ('foo' || 'bar')) {
        
           return 'Match';
    
        } else if (x === 'nofoo'){
      
          return 'No Match';

        } else
    
          return 'Blank field';
    }

    console.log(myFunction());

The console spits out 'Blank field' when I have the string bar for var x.

The console displays 'Match' when I have var x = 'foo'

Variation Two:

If I remove the brackets for the following line:

if (x === 'foo' || 'bar')

Then everything keyed into the var x = '[here]'; becomes a Match.

How does a competent programmer code this so that if x is 'foo' or 'bar' it returns a true statement.

Community
  • 1
  • 1
Jack
  • 11
  • 5
  • `('foo' || 'bar')` returns 'foo' `x === ('foo' || 'bar')` checks if x === 'foo' – James Nov 07 '18 at 16:34
  • As an alternative to posted answers you could also use `Array.includes` like `const arr = ['foo', 'bar']; if (arr.includes(x)) {//do something if 'x' is foo/bar }` – pmkro Nov 07 '18 at 16:38

3 Answers3

1

That not how || is used. You should check if x equals foo or if x equals bar;

if (x === 'foo' || x === 'bar')

In your first code, x === ('foo' || 'bar') means: if x equals the result of 'foo' || 'bar' which is 'foo' because || yields the first truthy element. So in this case, the code is equivalent to if(x === 'foo').

In your second code, x === 'foo' || 'bar' means: if x equals 'foo' or if 'bar' is truthy due to the priority of === over ||. Since 'bar' is truthy, the code is equivalent to if(true).

ibrahim mahrir
  • 29,774
  • 5
  • 43
  • 68
  • 1
    Thank you for your help. I don't know why I thought it would just take each value on it's own. – Jack Nov 07 '18 at 17:00
0
if (x === 'foo' || x === 'bar')

Like that... ;)

Thomas
  • 2,311
  • 18
  • 21
-3

You should probably separate 'foo' and 'bar' comparison like so:

if (x === 'foo' || x === 'bar')

And please use const or let for variable declarations. var would yield different bugs.

nrion
  • 3,117
  • 3
  • 14
  • 32