wondering if I can make my javascript more efficient.
I have a var JSP = “the jsp’s name”
And I have statements in a javascript validation file:
if(( JSP == "test.html" ) || ( JSP == "test1.html") || ( JSP == "test2.html" )) then blah blah blah.
Is there a more efficient way to do this?
If you know that
JSPcontains a string, it’s slightly more efficient to use===rather than==. Also note that you don’t need all those parens:You could also use a regular expression:
…but it depends what you mean by “efficient.” The series of
===will be very efficient at runtime.Separately, you could use a
switch:…but I wouldn’t call it more efficient.
I definitely would not put the options in an array, because searching through the array will not be efficient. But you can use a map:
…and then this test:
…which results in a fairly efficient property lookup. That’s only reasonable if you create the object once and reuse it.
(You might have people say “Or just use
if (pages[JSP]) { ... }. But that fails if JSP happens to contain “toString” or “valueOf” or any of several other inherited properties blank objects get fromObject.prototype. It’s fine if you’re certain it won’t have any of those values, though.)