why does 2length return 33 in javascript?

+, when either operand is not a number, will concatenate the string versions of both operands. So {}+{} will turn {} into a string on both sides, and concatenate them together. You get [object Object] concatenated with [object Object], which is 30 characters long.

+ operates left-to-right, and * has higher operator precedence. So

({}+{}+{}*2).length

is equivalent to:

({}+{}+{}*2).length
({}+{}+({}*2)).length
(({}+{})+({}*2)).length
(({}+{}                           )+({}*2)).length // same as above, but spaced out
(('[object Object][object Object]')+({}*2)).length

The {} * 2 tries to multiply something which cannot be meaningfully converted to a number, so NaN is the result:

(('[object Object][object Object]')+({}*2)).length
(('[object Object][object Object]')+(NaN )).length
('[object Object][object Object]' + NaN).length

+ will concatenate when either side is a string, so you get:

'[object Object][object Object]NaN'.length

which is 33.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top