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

2 Answers2

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
  • 31,174
  • 5
  • 48
  • 73
0
if (x === 'foo' || x === 'bar')

Like that... ;)

Thomas
  • 2,431
  • 17
  • 22