开发者

Difference between or and || when setting variables

开发者 https://www.devze.com 2022-12-09 05:38 出处:网络
I was under the impression that || and or were synonymous. Setting variable with or does not hold value; why?

I was under the impression that || and or were synonymous.

Setting variable with or does not hold value; why?

>> test = nil or true
=> true
>> test
=> nil

>> test = false or true
=> true
>> test
=> false

Work开发者_JS百科s 'as expected' with ||

>> test = nil || true
=> true
>> test
=> true


or has lower precedence than =.

test = nil or true

is the same as

(test = nil) or true

which is true, while setting test to nil.

|| has higher precedence than =.

test = nil || true

is the same as

test = (nil || true)

which is true, while setting test to true.


Same between and and &&. I was once bited by this gotcha, then I realize that although and is more readable than &&, that does not mean it always more suitable.

>> f = true && false
=> false
>> f
=> false
>> f = true and false
=> false
>> f
=> true
>> 
0

精彩评论

暂无评论...
验证码 换一张
取 消