Javascript returns string for OR(||) operation

后端 未结 2 1633
逝去的感伤
逝去的感伤 2021-01-23 11:12

I am unable to understand this.

Following is expression uses OR operator

var subCond1 = adj.getData(\'relationEnabled\') == \'true\' || adj.getData(\'unh         


        
相关标签:
2条回答
  • 2021-01-23 11:47

    Javascript returns the first operand that has a truthy value, whatever that truthy value is or the value of the last operand if none before are truthy. That is a designed feature of Javascript (yes it is different than other languages).

    You can turn that into a boolean by comparing to see if it is == true if you want or it is sometimes done with !!.

    0 讨论(0)
  • 2021-01-23 11:50

    Yup, that's just one of the features of || in JavaScript, and it's deliberate. It doesn't return a boolean (necessarily), it works like this: It evaluates the left-hand operand and if that operand is truthy, it returns it; otherwise, it evalutes and returns the right-hand operand.

    So what's "truthy"? Anything that isn't "falsy". :-) The falsy values are 0, "", null, undefined, NaN, and of course, false. Anything else is truthy.

    If you need a boolean, just !! the result:

    var subCond1 = !!(adj.getData('relationEnabled') == 'true' || adj.getData('unhideIfHidden') || adj.getData('hlFixed') == 'true');
    

    ...but you frequently don't need to bother.

    This behavior of || is really useful, particularly (I find) when dealing with object references that may be null, when you want to provide a default:

    var obj = thisMayBeNull || {};
    

    Now, obj will be thisMayBeNull if it's truthy (non-null object references are truthy), or {} if thisMayBeNull is falsy.

    More in this article on my blog: JavaScript's Curiously-Powerful OR Operator (||)

    Just to round things out: The && operator has a similar behavior: It evaluates the left-hand operand and, if it's falsy, returns it; otherwise it evaluates and returns the right-hand operator. This is useful if you want an object property from a variable which may be null:

    var value = obj && obj.property;
    

    value will be the value of obj if obj is falsy (for instance, null), or the value of obj.property if obj is truthy.

    0 讨论(0)
提交回复
热议问题