DEV Community

Discussion on: Javascript ||, aka Why Doesn't This Work?!

Collapse
 
harithay profile image
harithay • Edited

I agree that this is a very confusing point that result in really bad code. TypeScript is in a quest to fix issues such as this. I don't think JavaScript || breaks any math logic. It is still commutative. Problem is that we sees "this" and "that" as two string, but for the || operator, they are both just two boolean 'true's. Your equation, a || b = b || a, turns in to true || true = true || true when both a and b is a string. When evaluating this logic with || operator, it doesn't matter which true value sends to the user so to be fast JS (or any other sane language) returns the first result. To avoid confusion, you could always use !! to get the boolean value before do the ||. i.e !!a || !!b

Collapse
 
laurieontech profile image
Laurie

Ah, but it doesn't return a boolean. It returns the value. So yes, the operation logic is reasonable, but the return structure breaks the concept. It's no longer commutative at that point.