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.
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.
The
typeof
keyword represents an operator inJavascript
programming.The correct definition for
typeof
operator in the specification is :This is the reason behind the use of
typeof
astypeof(expression)
ortypeof 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 :
Or defining a more complex expression using the grouping operator :
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. Wouldtypeof
return the type of the result of the concatenation between an empty string literal and a number, or the type of the string literal ?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 :In this case, using parentheses with
typeof
would bring more clarity to what you are trying to express :