J Castillo
J Castillo

Reputation: 3357

multiple OR in IF statement in Coffeescript

Am trying to validate multiple statements in Coffeescript before I continue.

I have something basic like this:

 if ext != 'jpeg' || ext != 'pdf' || ext != 'jpg'

     alert('extension must be jpg, pdf, jpeg')

What am I doing wrong here? am new to Coffee and thought something as basic as this shouldn't be hard to do.

Upvotes: 1

Views: 7688

Answers (2)

mu is too short
mu is too short

Reputation: 434785

CoffeeScript has an in operator so you can say element in array to make the logic more compact:

You can use in to test for array presence, [...]

In your case:

if ext !in ['jpeg', 'pdf', 'jpg']
    alert('extension must be jpg, pdf, jpeg')

The current CoffeeScript compiler is smart enough to recognize that pattern and produces this JavaScript:

if (ext !== 'jpeg' && ext !== 'pdf' && ext !== 'jpg') {
  alert('extension must be jpg, pdf, jpeg');
}

rather than something more expensive.

Upvotes: 7

Pavan
Pavan

Reputation: 18528

You forgot to add &&.

if ext != 'jpeg' && ext != 'pdf' && ext != 'jpg'
     alert('extension must be jpg, pdf, jpeg')

Upvotes: 2

Related Questions