Prem
Prem

Reputation: 5987

Order of precedence of mixed operators in javascript

What would be the order of precedence if different kind of operators are used in same expression without parantheses?

For example, consider the following example. Why it has to be from left-to-right instead of right-to-left having the facts such as typeof operator has right-to-left order of precedence and + has left-to-right precedence.

typeof 99 + 'foo' // 'numberfoo'
typeof (99 + 'foo') // 'string'

Why the output of typeof 99 + 'foo' has to be 'numberfoo' instead of 'string' ?

Any reference to the documentation would be helpful.

Upvotes: 0

Views: 173

Answers (1)

Scott Marcus
Scott Marcus

Reputation: 65808

Most non-assignment expressions in JavaScript (as with many other languages and in mathematics) are evaluated from left to right, however the types of operators used in the expression can alter this default behavior.

The key thing to understand in this example is that typeof is a JavaScript operator, not a keyword, so it has a place in the order of operations.

In your first example: typeof 99 + 'foo'

The expression begins (left-to-right) with typeof 99. typeof is right-to-left associative, so the 99 goes to typeof and the result is "number".

Then the evaluation continues on (from left-to-right) with + 'foo'. + is left-to-right associative, so "number" and "foo" are concatenated to each other and "numberfoo" is outputted.

In your second example, you introduce the grouping operator (), which changes the normal order of operations and the expression inside the group is evaluated first. In that case you have a number and a string, with the + operator between them. Whenever you have the + operator and either one of its operands are a string, the other will automatically be converted to a string, so the result there is typeof string, which produces string.

Here are the general order of operations:

  1. Parenthesis
  2. Exponenents
  3. Multiplication
  4. Division
  5. Addition (either string or numeric)
  6. Subtraction

See the documentation for more including an associativity table showing which operators have what associativity.

Upvotes: 1

Related Questions