Expressions and operators

Objectives

  • Explain what an expression is
  • Use operators in JavaScript
  • Explain operator precedence

Expressions

Expressions in JavaScript are any code that resolves to a value. There are two types of expressions in JavaScript. Expressions may simply evaluate to a value, such as 8, "Hello", and 7 + 2. There are also assignment expressions that set a variable to a value and which evaluate to that value. Examples of the second type of expression are num = 7 + 2 and greeting = "Hello".

Operators

Operators are used to form expressions that include arithmetic, comparison, and many other functions. Operators in Java can be divided into three types and seven categories. Operators also have a precedence, which means that some operations will take precedence over other operations. For example, multiplication takes precedence over addition and subtraction. You can use parentheses to change the order of evaluation. Mozilla has a good reference for operator precedence.

Operator types:

  • unary: one operand and one operator; Examples: n++, ++n
  • binary: two operands with one operator in-between; Examples: 5 + 7, 2 * n
  • ternary: three operands separated by ? and : (?: is the ternary operator); Example: a > b ? a : b

Operator categories:

  • assignment: assigns a value to a variable
  • comparison: return true or false depending on comparison
  • arithmetic: perform standard arithmetic operations
  • bitwise: used to manipulate individual bits of an operand
  • logical: operate on Boolean values and return true or false
  • string: used to concatenate strings
  • special: a catch-all for other operators

Operator precedence table

PrecedenceOperators
1. []
2()
3++ --
4! ~ (unary) + (unary) - typeof void delete
5* / %
6+ -
7<< >> >>>
8< <= > >= in instanceof
9== != === !==
10&
11^
12|
13&&
14||
15?:
16yield
17= += -= *= /= %= <<= >>= >>>= &= ^= |=
18,

Useful resources for expressions and operators