Created
August 3, 2017 14:24
-
-
Save himalay/d0e234ecf8d4eb7fc08c1f2c70c3b1cf to your computer and use it in GitHub Desktop.
Coercion in JavaScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| function isNeg0 (n) { | |
| return n===0 && (1/n)===-Infinity | |
| } | |
| if (!Number.isNaN) Number.isNaN = num => num !== num | |
| // best way to do it in es6+ | |
| Object.is(0, -0)// false | |
| Object.is(NaN, NaN)// true | |
| var a = [1,5,3,4,8] | |
| if (~a.indexOf(4)) console.log('Found 4 in a') | |
| // ~N -> -(N+1) | |
| var now = Date.now()// do not use +new Date() | |
| var a = '42424' | |
| var aNumber = Number(a) | |
| var aString = String(aNumber) | |
| var aBoolean = Boolean(aString) | |
| // avoid calling new on String, Number, Boolean, Array, Object all times | |
| // NEVER use == false or == true | |
| '0' == false// true -- UH OH! | |
| false == 0// true -- UH OH! | |
| false == ''// true -- UH OH! | |
| false == []// true -- UH OH! | |
| '' == 0// true -- UH OH! | |
| '' == []// true -- UH OH! | |
| 0 == []// true -- UH OH! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment