Created
July 6, 2012 02:58
-
-
Save getify/3057796 to your computer and use it in GitHub Desktop.
exploring javascript type auto-coercion (and its pitfalls)
This file contains 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
// ********** | |
// NOTE: this is a stupid trivial example illustrating automatic | |
// type-coercion, not an example of the kind of data-structure logic | |
// you'd ever actually use. don't miss the forest for the trees. | |
// Read down in the comment thread for 'myCoolString' for a slightly | |
// more sensible example. | |
// | |
// NOTE #2: this gist thread was spawned from a twitter discussion | |
// about `parseInt(0/1,19)==18`: | |
// https://twitter.com/getify/status/221009838006747136 | |
// ********** | |
var myObj = { | |
_val: [10,5,7,9,-1,4,13,6], | |
toString: function(){ | |
return ""+Math.max.apply(this,this._val); | |
} | |
}; | |
parseInt(myObj); // 13 ==> this is part of what makes javascript awesome |
I woud use valueOf here instead of toString.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@bhudgeons
parseInt(1/0,19)==18
is clearly a semantic WTF... for pretty much everyone, myself included. There's never been an argument about that.There are plenty of other semantic WTFs too. My personal "favorite" is
typeof NaN == "number"
.The question has been, is the language "flawed" by allowing that (or rather, not ensuring some yet-to-be-well-defined alternative)? And more importantly, if we were to consider changing the language to "fix" the "flaw", would we REALLY be better off, or is that just a "grass is always greener" conundrum?
I've been trying to illustrate that all the alternatives are worse. You're not in the "darkness of stupidity" because you disagree. You just value different things from the language than I do.
:)