Home >Web Front-end >JS Tutorial >What's the Most Efficient Way to Check Variable Equality Against Multiple Values in JavaScript?

What's the Most Efficient Way to Check Variable Equality Against Multiple Values in JavaScript?

Barbara Streisand
Barbara StreisandOriginal
2024-12-24 09:08:411000browse

What's the Most Efficient Way to Check Variable Equality Against Multiple Values in JavaScript?

Efficient Variable Equality Check against Multiple Values

When comparing a variable to multiple predetermined values, a straightforward method is to use a series of logical OR operators:

if( foo == 1 || foo == 3 || foo == 12 ) {
    // ...
}

Although this approach works, it can become cumbersome for a large number of values. An alternative solution is to utilize an object as follows:

if( foo in {1: 1, 3: 1, 12: 1} ) {
    // ...
}

However, this method also introduces redundancy by requiring the repetition of values within the object.

Fortunately, in ECMA2016, a more elegant and performant solution is available: the includes method. This method allows you to efficiently check if a value is contained within an array:

if([1,3,12].includes(foo)) {
    // ...
}

This syntax provides a concise and efficient way to perform equality checks against multiple values. Supported by all major browsers, it is the recommended approach for such comparisons.

The above is the detailed content of What's the Most Efficient Way to Check Variable Equality Against Multiple Values in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn