Beginner20 min read

Operators & Expressions

Master arithmetic, comparison, logical, and assignment operators in JavaScript.

Arithmetic Operators

Arithmetic operators perform mathematical calculations on numbers:

OperatorNameExampleResult
+Addition5 + 38
-Subtraction10 - 46
*Multiplication3 * 721
/Division15 / 43.75
%Modulo (remainder)10 % 31
**Exponentiation2 ** 416

JavaScript follows the standard order of operations (PEMDAS): Parentheses, Exponentiation, Multiplication/Division, Addition/Subtraction. Use parentheses to make your intent clear.

There are also increment (++) and decrement (--) operators that add or subtract 1:

javascript
let count = 5;
count++;  // count is now 6
count--;  // count is back to 5

Comparison Operators

Comparison operators compare two values and return a boolean (true or false):

OperatorMeaningExampleResult
===Strict equal5 === 5true
!==Strict not equal5 !== '5'true
==Loose equal5 == '5'true
!=Loose not equal5 != '5'false
<Less than3 < 7true
>Greater than10 > 20false
<=Less than or equal5 <= 5true
>=Greater than or equal8 >= 10false

Always use strict equality (=== and !==). Loose equality (==) performs type coercion, which can lead to unexpected results:

javascript
0 == ''      // true (both coerced to falsy)
0 === ''     // false (number vs string)
null == undefined  // true (special coercion rule)
null === undefined // false (different types)

Logical Operators

Logical operators combine or invert boolean expressions:

OperatorNameDescription
&&ANDReturns true if both operands are truthy
||ORReturns true if at least one operand is truthy
!NOTInverts the boolean value
javascript
true && true    // true
true && false   // false
true || false   // true
false || false  // false
!true           // false
!false          // true

JavaScript uses short-circuit evaluation: with &&, if the first operand is falsy, the second is never evaluated. With ||, if the first operand is truthy, the second is never evaluated.

Truthy and falsy values: In a boolean context, these values are falsy: 0, "" (empty string), null, undefined, NaN, and false. Everything else is truthy, including [], {}, and "0".

Operators in Action

html
<div id="results"></div>

<script>
  const a = 10;
  const b = 3;

  const sum = a + b;          // 13
  const remainder = a % b;    // 1
  const power = a ** 2;       // 100
  const isEqual = a === b;    // false
  const isGreater = a > b;    // true
  const bothTrue = isGreater && !isEqual;  // true

  const results = document.getElementById('results');
  results.innerHTML = `
    <p>${a} + ${b} = ${sum}</p>
    <p>${a} % ${b} = ${remainder}</p>
    <p>${a} ** 2 = ${power}</p>
    <p>${a} === ${b} is ${isEqual}</p>
    <p>${a} > ${b} is ${isGreater}</p>
    <p>Both conditions: ${bothTrue}</p>
  `;
</script>

What does 5 === '5' return?

Ready to practice?

Create your free account to access the interactive code editor, run challenges, and track your progress.