Chapter 1 Chapter 2 Chapter 3 Chapter 4 Chapter 5 Chapter 6 Chapter 7 Chapter 8 Chapter 9 Chapter 10 Chapter 11 Chapter 12 Chapter 13 Chapter 14
Chapter 5

Expressions & Operators

Arithmetic, assignment, comparison, logical and string operators — and type coercion.


Expressions & Operators

An expression is any combination of values, variables and operators that computes to a value.

Operator typePurpose
ArithmeticMathematical calculations on numeric values (+ - * / %).
AssignmentAssign values to variables (= += -=).
ComparisonCompare values, returning true/false (== === != < >).
LogicalCombine boolean expressions (&& || !).
String+ (concatenation) joins strings together.

Operator examples

// String concatenation with "+"
var txt1 = "John";
var txt2 = "Doe";
var txt3 = txt1 + " " + txt2;   // "John Doe"

// Assignment operator "+="
var txt = "What a very ";
txt += "nice day";              // "What a very nice day"

// Mixing numbers and strings
var x = 5;
var y = 5;
var z = x + y;        // 10 (number + number)
var s = x + "5";      // "55" (number + string)
var h = "Hello" + x;  // "Hello5"

Type coercion: when you add a string and a number, JavaScript converts the number to a string and concatenates them — a common source of bugs!

Activity — complete the code

Complete the code correctly to mark this lesson as complete automatically.

Complete the operators.

// String concatenation
var txt3 = txt1 " " + txt2; // "John Doe"
 
// Assignment (append)
txt "nice day";
 
// Arithmetic
var z = x y; // add
 
// Strict equality (value AND type)
if (age 18) { }