Diego De Santiago
Diego De Santiago

Reputation: 67

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(typeof(1));

Upvotes: 4

Views: 527

Answers (4)

Morgan Gethin Barrett
Morgan Gethin Barrett

Reputation: 91

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.

Upvotes: 1

Alex
Alex

Reputation: 11255

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"

Upvotes: 0

paulsm4
paulsm4

Reputation: 121881

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

Upvotes: 1

raina77ow
raina77ow

Reputation: 106483

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.

Upvotes: 8

Related Questions