Skip to content

Operators and Expressions

Operators are symbols used to perform some action on values (these values are called operands).

An expression is simply a mix of values, variables, and operators that together produce a result.

let result = 10 + 5;
  • + -> this is the operator
  • 10, 5 -> these are the operands
  • 10 + 5 -> this whole thing is the expression
graph LR A[Operands] --> B[Operator] B --> C[Evaluation] C --> D[Result]

Arithmetic

These are used to do math operations like addition, subtraction, and so on.

Assignment

These are used to give (assign) values to variables.

Comparison

These compare two values and give back a true or false result.

Logical

These are used to combine more than one condition together.

  1. Addition (+) This adds two values together. Example: 10 + 5 = 15

  2. Subtraction (-) Example: 10 - 5 = 5

  3. Multiplication (*) Example: 10 * 5 = 50

  4. Division (/) Example: 10 / 5 = 2

  5. Modulus (%) This gives back the remainder left over after division. Example: 10 % 3 = 1

  6. Exponentiation ()** Example: 2 ** 3 = 8

let a = 10;
let b = 3;
console.log(a + b); // 13
console.log(a % b); // 1

These are used to assign (give) values to variables.

let x = 10;
x += 5; // x = x + 5
x -= 2;
x *= 3;
x /= 2;
graph TD A[Variable] --> B[Operator] B --> C[New Value]

These give back either true or false.

10 > 5; // true
10 < 5; // false
10 >= 10; // true
10 <= 5; // false
"5" + 2; // "52"
"5" - 2; // 3

Type coercion is when JavaScript automatically converts a value from one type to another, on its own, while running your code. This is why "5" + 2 becomes the text "52", but "5" - 2 becomes the number 3.

These are used to combine more than one condition together.

  1. AND (&&) This is true only if both conditions are true.

  2. OR (||) This is true if at least one of the conditions is true.

  3. NOT (!) This simply flips a boolean value to its opposite.

let age = 20;
console.log(age > 18 && age < 30); // true
console.log(age > 18 || age < 10); // true
console.log(!(age > 18)); // false

This means JavaScript stops checking the rest of the condition early, if it already knows the final answer.

true || console.log("Won't run");
false && console.log("Won't run");

In the first line, since the value before || is already true, JavaScript does not even bother checking the second part. The same thing happens in the second line with &&, since the first value is already false.

graph LR A[Condition 1] -->|Short Circuit| B[Skip Next]

These work on just a single value (operand).

let x = 5;
x++; // increment
x--; // decrement
typeof x; // type check

This decides the order in which operations actually happen.

let result = 10 + 5 * 2; // 20, not 30

Here, multiplication happens first, even though addition is written first in the line. This is why the result is 20 and not 30.

graph TD A[Multiplication] --> B[Addition] B --> C[Final Result]