Majo0od Majo0od - 4 days ago 5
Javascript Question

Efficiency in multiple instances of === parameter?

Is there a more efficient way to display this:

$(this).text() === "something" || $(this).text() === "somethingelse"


as something like this:

$(this).text() === ("something" || "something else")





Clarity's sake: I'm not suggesting it should be exactly as I displayed, but I'm wondering if there is an easier way to do what I'm suggesting so I'm not repeating the same command if I'm just trying to compare certain text, for instance.

Answer

There are several methods which can achieve the desire result

Method 1 - using indexOf()

var myList = ["something", "somethingElse"];
if (myList.indexOf($(this).text()) !== -1) {
    //ok
} else {
    //nok
}

Method 2 - using jQuery.inArray

//This yields to false
$.inArray( 5 + 5, [ "8", "9", "10", 10 + "" ] );
//This yields to true
$.inArray( 5 + 5, [ "8", "9", "10", 10 ] );

The reason this happens is because JavaScript treats 0 as loosely equal to false

Method 3 - using includes()

var a = [1, 2, 3];
a.includes(2); // true 
a.includes(4); // false

Method 4 - switches

switch (expression) {
  case value1:
    //Statements executed when the result of expression matches value1
    [break;]
  case value2:
    //Statements executed when the result of expression matches value2
    [break;]
    default:
    //Statements executed when none of the values match the value of the expression
    [break;]
}
Comments