Skip to content Skip to sidebar Skip to footer

Javascript If Else Statement With Multiple Or Following Condition

I'm detecting extensions then taking actions based on the extension. So my question is why doesn't this work, seems logical enough eh? var ext = url.split('.').pop().toLowerCase();

Solution 1:

The line ext == 'avi' || 'mpg' || 'mpeg' || 'mp4' || '3gp' will always be true as you are comparing if ext is avi or if any of 'mpg' || 'mpeg' || 'mp4' || '3gp' are truthy.

The == operator only compares a single variable for future reference.

Another way you can write this comparison with a switch is as follows:

switch(ext) {//switch with fall throughscase'avi':
    case'mpg':
    case'mpeg':
    case'mp4':
        //we got a videobreak;
    case'jpg':
    case'jpeg':
    case'gif':
    case'png':
        //its a picturebreak;
    default:
        //this extension isn't suupported
}

Solution 2:

You first if condition is always truthy.

If you have a lot of values to check then I would suggest something like

var video = ['avi', 'mpg'];
var audio = ['mpg', 'mpeg'];
if($.inArray(ext, video)){
    //video
} if($.inArray(ext, audio)){
    //audio
} else {
}

Solution 3:

"So my question is why doesn't this work"

Because that's just not what the || operator does.

The shortest syntax I can think of to implement your concept is to use a regex test for each condition:

if (/^(avi|mpg|mpeg|mp4|3gp)$/.test(ext)) {

Or you can use an array:

if (['avi', 'mpg', 'mpeg', 'mp4', '3gp'].indexOf(ext) != -1) {

(Assuming you're not worried about IE<=8, or are using a shim, or use jQuery's $.inArray() instead of .indexOf().)

Or this seems an obvious place to use a switch statement:

var ext = url.split('.').pop().toLowerCase();
switch(ext) {
    case'avi':
    case'mpg':
    case'mpeg':
    case'mp4':
    case'3gp':
       //  This is a video (this always returns true...?)break;
    case'jpg':
    case'jpeg':
    case'gif':
    case'png':
    case'bmp':
       // This is a picturebreak;
    default:
       //  This extension isn't supported herebreak;
}

Post a Comment for "Javascript If Else Statement With Multiple Or Following Condition"