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 type | Purpose |
|---|---|
| Arithmetic | Mathematical calculations on numeric values (+ - * / %). |
| Assignment | Assign values to variables (= += -=). |
| Comparison | Compare values, returning true/false (== === != < >). |
| Logical | Combine 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 concatenationvar txt3 = txt1 " " + txt2; // "John Doe"// Assignment (append)txt "nice day";// Arithmeticvar z = x y; // add// Strict equality (value AND type)if (age 18) { }