Created
April 20, 2024 20:52
-
-
Save coder0107git/f5695e1e3a6d1e38baf24d82add74da9 to your computer and use it in GitHub Desktop.
The Horrors of Javascript Numbers
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
console.log(5) // prints: 5 | |
Number.prototype._ = function() { | |
alert("Boo!"); | |
return this; | |
} | |
Number.prototype.__ = function() { | |
alert("Boo!"); | |
return this * 2; | |
} | |
console.log(5["_"]()) // prints: 5 | |
// 😱 | |
console.log(5["__"]()) // prints: 10 | |
// What do you think this does? | |
console.log(5["constructor"]("6")) | |
// `6` Wut?! | |
// And then what does this do? 😈 | |
console.log(5["constructor"](-+-+-+-+"1.87e-12")) | |
// `1.87e-12` Wut?! | |
// Then this must be the same right? | |
// Right? | |
console.log(5["constructor"](+-+-+-+"1.87e-12")) | |
// `-1.87e-12`! What's going on here? | |
// Basicly `+` is being parsed as a unary `+` which just converts a string | |
// to a number and `-` is negating the number. A slightly clearer example | |
// of what's happening is: | |
console.log( | |
Number( | |
-1 * Number( | |
-1 * Number( | |
-1 * Math.abs(Number("1.87e-12")) | |
) | |
) | |
) | |
) | |
// Well what's up with the `5["constructor"]`? | |
// Numbers don't support dot syntax but they do support dynamic object | |
// accessor notation. So `5["constructor"]()` is equivalent to `Number()`. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment