Javascript if statement with multiple permissible conditions [duplicate]

Possible Duplicate:
Javascript: The prettiest way to compare one value against multiple values
Javascript If statement used to check file extensions not working

In JS I'm trying to check whether an extension ends in "png" "jpg" or "gif". I'm aware this can be done with a switch statement, but I'm wondering if there's a simpler way to throw it all in the if conditional. Like:

    if (aExtensions[i].toLowerCase() == ('jpg' || 'png' || 'gif')) {}

What's the best way to achieve this?



What about a regex?

if ( /jpg|png|gif/i.test( aExtensions[i] ) ) {

You could use a variable and triple comparison, but that's ugly.

Or you could just use an array and check if the string is contained in it.

if (~ ["jpg", "png", "gif"].indexOf(aExtensions[i].toLowerCase()) …

Yet, for the complicated != -1 comparison and the lack of native indexOf in older IEs, people tend to use regexes:

if (/jpg|png|gif/i.test(aExtensions[i])) …

You could use an array like this:

var extensions = ["jpg", "png", "gif"];

if (extensions.indexOf(aExtensions[i].toLowerCase()) > -1) {
    // match

In this case, you store the "valid" extensions. Then, you can use the indexOf method of Array to find if any of the items in the array match the specific extension you're looking at - checking for a value that is 0 or greater.

indexOf isn't supported on older browsers, so you'd need to include a polyfill to back it up. There are several solutions for that.

Of course, if you wanted to only use if statements, you could use this format:

var ext = aExtensions[i].toLowerCase();
if (ext == "jpg" || ext == "png" || ext == "gif") {
    // match

Another possibility I can think of is a switch statement, like:

var ext = aExtensions[i].toLowerCase();

switch (ext) {
    case "jpg":
    case "png":
    case "gif":
        // match
    case default:
        // No match

I might as well include it (other answers had it first, definitely), but one more I can think of is using a regex, like:

if (/jpg|png|gif/i.test(aExtensions[i])) {
    // match

But note that you will never be able to individually get the extensions back, and that's why I would prefer one of the first two options I gave.


Yet another way to do this is by using an object literal like this,

if ({'jpg':1,'png':1,'gif':1}[aExtensions[i].toLowerCase()]) {
    // ...

This way you're looking to see if the anonymous object {'jpg':1,'png':1,'gif':1} has a property which will be true by the if. 1 meets this, undefined doesn't.

If you're using an object, you could also make use of the in operator (as pointed out by Ian) which gives true if the object has such a key irrelevant of it's value.

if (aExtensions[i].toLowerCase() in {'jpg':0,'png':1,'gif':2}) {
    // ...

Note this time how 'jpg' still passes even though 'jpg':0.


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.