JavaScript Operators

The JavaScript operators are used to manipulate operands and build expressions. They are used for assignment expressions, arithmetic expressions, logical expressions, relational expressions and a few other expressions.

What is Operand and Operator

Expressions are made up of operators and operands. For instance, the expression 2 + 3 resolves to 5. In this case 2 and 3 are operands and + is an operator. The operands can be of any of the JavaScript data types, objects or arrays. It could be a constant, a variable or a function result.

What is Unary Operator and Binary Operator

The operators which perform operation using two operands are called binary operators, on the other hand operators which need one operand are called unary operators. JavaScript also supports one ternary operator, the conditional operator ?:. The ternary operator uses three expressions to produce a single expression.

Operator Precedence

In general, expressions are evaluated from left to right. But some operators have higher precedence over the other operators. The precedence determines the order in which expressions are evaluated.

For instance, in the expression 2 + 5 * 3, the result is 17 and not 21 because the multiplication operator * has a higher precedence than the addition operator +. Multiplication is performed before addition.

For more details about JavaScript operators and their precedence order visit list of JavaScript operators.

Operator Associativity (Order of Evaluation)

The associativity of an operator is also important, as it determines whether operations are performed from left to right or right to left. The associativity of an operator also affects the order in which operations of the same precedence are performed.

For instance - is left-to-right associative, so 2 - 3 - 4 is grouped as (2 - 3) - 4 and evaluates to -5. On the other hand = is right-to-left associative, so i = j = k is grouped as i = (j = k).

For further details about operators and their associativity, please visit list of JavaScript operators.

Operators as Keywords

Most of the operators are represented by characters and symbols such as *, + and =. But there are few operators which are represented by keywords, such as typeof and delete.

Operator Side Effects

Some expressions never affect the state of the program. On the other hand, some expressions have side effects. For instance,

  • The expression 2 + 3 resolves to 5. It has no effect on the state of the program.
  • The assignment operator = is one of the examples, which has side effects. For instance, the expression x = 10, it assigns the value 10 to variable x and it changes the value of the expression that uses the variable x.

There are few more examples of such expressions, we will discuss later in next sections.