Search code examples
javascriptbooleanlogical-operatorsoperator-precedenceboolean-operations

operator precedence in JavaScript : Can someone please explain why the if condition evaluates to true for all values of browser


if (browser == ‘chrome’||’firefox’||’safari’||’opera’)

Can someone please explain why the if condition evaluates to true for all values of browser?


Solution

  • First remove the curly quotes - those will cause a SyntaxError. Use straight quotes instead.

    == has higher operator precedence than ||, and || evaluates left-to-right, so fixing the quotes, your code is equivalent to:

    if ((((browser == 'chrome') ||'firefox') ||'safari') ||'opera')
    

    If the browser is chrome, this results in

    if ((((true) ||'firefox') ||'safari') ||'opera')
    if (true)
    

    Otherwise, this results in

    if ((((false) || 'firefox') ||'safari') ||'opera')
    if (((false || 'firefox') ||'safari') ||'opera')
    

    If the left-hand side of || is falsey, it will evaluate to the value on the right-hand side. Otherwise, if the left-hand side of || is truthy, it will evaluate to the value on the left-hand side. So it resolves to:

    if (((false || 'firefox') ||'safari') ||'opera')
    if ((('firefox') ||'safari') ||'opera')
    if ('firefox')
    

    And 'firefox' is truthy, so the if will always run.

    For what you're trying to do, use .includes instead:

    if (['chrome', 'firefox', 'safari', 'opera'].includes(browser))