Why is typeof's result different than the evaluated result of the expression passed in?

爱⌒轻易说出口 提交于 2019-11-29 13:04:15
Felix Kling

{} + {} is an empty block ({}) followed by a type conversion from object to number (+{}). It basically reads as

{} // empty block (a statement)
;  // empty statement (just for clarity)
+{}; // expression statement (unary plus, object literal -> conversion to number)

However if you use typeof ({} + {}), then {} + {} will be evaluated as expression in which case both {} can only be object literals and the + is the concatenation operator.

You can also just use the grouping operator to force the construct to be evaluated as expression:

({} + {}) // expression statement (string concatenation with two objects)

See also Why {} + {} is NaN only on the client side? Why not in Node.js? and other questions related to [javascript] "{} + {}".

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!