Javascript if statement with multiple permissible conditions [duplicate]

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
        break;
    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.

Leave a Comment