Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does "typeof" not need parentheses? [closed]

Is there any difference between typeof (myVariable) compared to typeof myVariable?

Both work, but coming from PHP, I don't understand why this function can use parenthesis or not.

like image 640
Don P Avatar asked Apr 05 '13 21:04

Don P


People also ask

Why is typeof not a function?

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!).

What is the use of typeof () function?

In JavaScript, the typeof operator returns the data type of its operand in the form of a string. The operand can be any object, function, or variable. Note: Operand is an expression representing the object or primitive whose type is to be returned.

Why is typeof an operator?

The typeof operator is not a variable. It is an operator. Operators ( + - * / ) do not have any data type. But, the typeof operator always returns a string (containing the type of the operand).


1 Answers

The typeof keyword represents an operator in Javascript programming.

The correct definition for typeof operator in the specification is :

typeof[(]expression[)] ; 

This is the reason behind the use of typeof as typeof(expression) or typeof expression.

Coming to why it has been implemented as such is probably to let the developer handle the level of visibility in his code. As such, it is possible to use a clean conditional statement using typeof :

if ( typeof myVar === 'undefined' )   // ... ; 

Or defining a more complex expression using the grouping operator :

const isTrue = (typeof (myVar = anotherVar) !== 'undefined') && (myVar === true); 

EDIT :

In some cases, using parentheses with the typeof operator makes the code written less prone to ambiguity.

Take for instance the following expression where the typeof operator is used without parentheses. Would typeof return the type of the result of the concatenation between an empty string literal and a number, or the type of the string literal ?

typeof "" + 42 

Looking at the definition of the operator stated above and the precedence of the operators typeof and +, it appears that the previous expression is equivalent to :

typeof("") + 42 // Returns the string `string42` 

In this case, using parentheses with typeof would bring more clarity to what you are trying to express :

typeof("" + 42) // Returns the string `string` 
like image 61
Halim Qarroum Avatar answered Sep 23 '22 09:09

Halim Qarroum