|
|
|
|
|
by esrauch
4067 days ago
|
|
A bunch of that is wrong or at least misleading. > {} + []
> 0 (The number zero) This is wrong, it is only true in the weird scenario that you type it into the jsconsole and don't use the result. It parses as an empty block ({}) and then an unrelated unary +[] after that. var x = {} + []; gives you a string and it is the same as var x = [] + {}. There is more logic than it seems here: Unary plus:
> always gives a number (a double: NaN is a double)
> on array: +a -> if len>=2: NaN else +a[0] (recursively)
> on object: NaN
> on string: parseNumber, or NaN if that fails
> on bool: 0 for false, 1 for true
> on null: 0
> on undefined: NaN
binary plus (addition):
> order doesn't matter except for the jsconsole pseudo-bug
> if both sides are number or boolean, add them
> else, toString() both sides and concat them
boolean negate (not):
> false for 0, false, "", null, undefined
> true otherwise
binary - (subtraction)
> x-y coerces x and y to number and subtracts them.
> Most mainstream languages that use + for string concat don't use - for some sort of string unconcat so its not too crazy.
> typeof [] === typeof {}
This isn't so crazy, typeof any non-primitive gives you "object".
[] is pretty much just an object plus magic .length property,
var x = []; x.blah = 7; console.log(x.blah) works. It doesn't work on number or bool.
|
|