Skip to content Skip to sidebar Skip to footer

Why Is "typeof" The Same As "typeof()"?

I'm learning JavaScript, and i saw in the code that is the same to use typeof and typeof(), for example: The result is number in both cases: console.log(typeof 1); console.log(typ

Solution 1:

typeof is, according to ES5 spec, an unary operator - the same as void and delete, for example. Wrapping its expression with grouping () is only done for convenience (and - in theory - to override the default precedence), but never it's treated as a function call.

Solution 2:

Because "typeof" is an operator (not a function, not an object), and an operator can be used in an expression with parenthesis:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof

http://www.ecma-international.org/ecma-262/5.1/#sec-11.4.3

Solution 3:

typeof is an operator, just like +, -, %, && etc. It is not a method and "1" is not a parameter being passed, brackets are not required. However it will accept brackets as they just specify the order of operation, just like (1) + (2) is acceptable even though the brackets are not necessary. So the example you gave is acceptable in both cases.

Solution 4:

The typeof operator is not a function. You can surround the operand with parentheses so that the expression looks like a function call, but the parentheses will simply act as a grouping operator (second only to the comma operator in the obscurity pecking order!). In fact you can decorate the operand with all manner of punctuation without derailing the operator.

typeof (2) //"number"typeof(2) //"number"typeof ("a", 3) //"number"typeof (1 + 1) //"number"

Post a Comment for "Why Is "typeof" The Same As "typeof()"?"