Emilio
Emilio

Reputation: 1354

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;
}

Upvotes: 0

Views: 498

Answers (2)

Pablo Recalde
Pablo Recalde

Reputation: 3571

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

Upvotes: 1

mdziekon
mdziekon

Reputation: 3627

Most likely you want to use a logical OR operator, which is || (double pipe) not | (which, as you've pointed, is a bitwise OR operator). In that case the answer is YES, as the operation will always skip the false value (false || something === something).

In terms of bitwise operators, you should be aware that they operate on 32-bit values, so if you use bigger values than a 32-bit number can hold, your data will be truncated. You can read more about this on MDN article about Bitwise Operators. Edit: to clarify - bitwise operators will cast any value to a Number value (to 32-bit Integer, to be specific).

Upvotes: 4

Related Questions