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
Software dev at Netflix | DC techie | Conference speaker | egghead Instructor | TC39 Educators Committee | Girls Who Code Facilitator | Board game geek | @laurieontech on twitter
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.
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
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
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.