Hacker News new | ask | show | jobs
by tzs 5250 days ago
The Ruby stuff apparently isn't bizarre. From what I've read, Ruby creates variables as it encounters an assignment to them when parsing the code. So, when you have

   a = a
in your code, Ruby creates the variable a before it ever tries to actually execute the assignment. If later, when it has finished parsing everything, and starts executing, that statement fails because b is not defined, you still end up with variable a being defined, and since it has not had anything successfully assigned to it, it has a value of nil.

The JavaScript stuff, I think, comes from operator overloading. The plus operator is overloaded to allow adding strings to concatenate them, and it will do type conversion to get compatible types, so "wat"+1 results in the 1 being converted to a string, and then the strings are concatenated. Since the minus operator is not so overloaded, "wat"-1 instead is treated as numerical subtraction. JavaScript allows string to be used as numbers, so "123"-1 gives 122. However "wat" is not a string that represents a number, so gives NaN when forced to be treated as a number, and "wat"-1 is thus NaN.

1 comments

Thanks for that. I was curious the reason, it seems obvious though after an explanation.