As far as I can tell, typeof foo and typeof(foo) behave the same, and the latter is much more intuitive because I can just think of it as a function.
The same for delete() .
So, is there a difference? If not, why do we need both forms?
The parentheses are optional. typeof
is an operator, not a function. That's like asking why do 5 + 3
and not 5 + (3)
.
In most cases it will not make a difference however, it becomes useful when you are using typeof to evaluate the type of an expression.
typeof(1 + ' some text');
returns
string
However
typeof 1 + ' some text';
returns
"number some text"
Both typeof
and delete
are unary operators but with a big difference between the two: typeof
evaluates its operand and delete
does not. Operator precedence ( MDN reference ) is useful for discussion.
delete
UnaryExpression
The delete operator does not evaluate its operand and ignores grouping operators '(' and ')' around it because they have higher precedence than delete
. Hence delete
could never be written as function call using the same syntax because a function call would evaluate function arguments. Delete can use property short cut or lookup syntax:
delete objectIdentifier.property name; // is equivalent to
delete objectIdentifier["propertyName"]
In strict mode a syntax error is generated if you try using delete
on anything that is not a reference to an object property that includes both the property name and object.
typeof
UnaryExpession
The typeof operator evaluates its operand. If the operand expression is enclosed in parentheses, the entire expression between the parentheses is evaluated before applying typeof
to the result. Using parentheses around an operator that can be identified using rules for operator precedence alone is redundant.
Summary
Using parentheses around an operand for delete
doesn't help and is probably best avoided.
Use parentheses around a typeof
operand to obtain the type of an expression result.
Placing parentheses around typeof
and its operand, as in (typeof operand)
can be useful in debugging a complex expression if operator precedence or automatic type conversions are not working as expected.
The use of parentheses around operands for delete
and typeof
does not create two kinds of syntax for the operators - the parentheses follow normal rules for parsing an expression.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.