Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
614 views
in Technique[技术] by (71.8m points)

syntax - Why does Javascript's OR return a value other than true/false?

I saw this construction in order to get the browser viewport width:

function () { return window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth; }

I understand the browser quirks involved. What I don't understand is why || returns the value. So I tried this alert(undefined || 0 || 3); and sure enough, it alerts 3. I find this bizarre, because I expect true or false. Could anyone explain what's going on?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The JavaScript operator || is defined to return the left value if it evaluates to a truthy value, otherwise the right value instead of returning true itself. That's just how it's defined in the spec.

I know it can be annoying at times, you might accidentally end up holding a reference to something you don't want to hold on to, but it also allows for the handy trick your example has. Everything has its pros and cons.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...