Search code examples
javascriptbit-manipulationbitwise-operatorsbitwise-or

Using false with the bitwise OR operator


My IDE says var x = false | isIE; can be simplified to var x = isIE;.

Is it true?

Is there any tricky JavaScript business I should know about?

isIE is defined as:

function ms_ie() {
    var ua = window.navigator.userAgent;
    var old_ie = ua.indexOf('MSIE ');
    var new_ie = ua.indexOf('Trident/');
    var edge = ua.indexOf('Edge/');

    if ((old_ie > -1) || (new_ie > -1) || (edge > -1)) {
        return true;
    }
    return false;
}

Solution

  • In boolean algebra 0 | 0 == 0, 0 | 1 == 1 which can be translated to false | false == 0 or false | true == 1

    This is JavaScript so if isIE is a Boolean, null or undefined this will do a cast to Integer and you'll always end with 0 or 1