JavaScript Fundamentals
Build a solid JS foundation: syntax, data types, control flow, functions, arrays, and objects.
Content
Operators and expressions
Versions:
Watch & Learn
AI-discovered learning video
Operators & Expressions: The Tiny Drama Engines of JavaScript
You gave JavaScript some nouns (values) and put name tags on them (variables). Now it wants verbs. Enter: operators — the action words that make your code do stuff.
We already set up our creative lab (Orientation and Setup), learned what kinds of stuff exist in JavaScript (Values and Data Types), and how to store that stuff (Variables with let and const). Today, we make those variables mix, mingle, and occasionally throw shade — using operators to build expressions.
What Are Operators? What Are Expressions?
- Operator: a symbol that tells JavaScript to do an operation. Example:
+,===,&&. - Operands: the values that an operator works on. In
a + b,aandbare operands. - Expression: anything that produces a value.
3 + 4is an expression. So ismouseX > 200 ? "hot" : "cool"in a p5.js sketch.
If a value is a noun, an expression is a whole sentence that ends with “here’s the result.”
Statements like if (...) { ... } control the flow, but expressions are where the math, logic, and mischief live.
The Operator Family (Meet the Drama Cast)
1) Arithmetic: The Gym Friends
+add,-subtract,*multiply,/divide,%remainder,**exponent.- Unary:
+value(coerce to number),-value(negate number).
Examples:
let w = 640;
let cols = 12;
let cell = Math.floor(w / cols); // 53, because / is real division, floor trims decimals
let spin = (frameCount % 360) * (Math.PI / 180); // degrees → radians
let scale = 2 ** 3; // 8
Heads-up: % is remainder, not a “modulo with always-positive result.” With negatives, results keep the sign of the left operand.
++and--exist. They change a variable by 1. But they’re clingy and can be confusing (x++vs++x). Preferx += 1unless you like chaos.
2) String-y Math: When + Turns Flirty
+concatenates strings. If one side is a string, JavaScript tries to make the other side a string too.
"3" + 2; // "32"
3 + "2"; // "32"
3 - "2"; // 1 (subtraction forces number conversion)
The
+operator is bilingual: number + number = math; string + anything = poetry.
Use template literals for sanity:
const score = 42;
const msg = `Your score is ${score}`; // nicer than "Your score is " + score
3) Assignment: Put It Somewhere
- Basic:
= - With flair:
+=,-=,*=,/=,%=,**= - Logical-ish:
||=,&&=,??=(set only if the left side meets a condition)
let name = "";
name ||= "Anonymous"; // if name is falsy ("" is falsy), set to "Anonymous"
let count = null;
count ??= 0; // set to 0 only if null or undefined
4) Comparison: The Judgy Ones
>,>=,<,<=— numeric and lexicographic comparisons.==vs===— the eternal debate.
| Operator | Meaning | Example | Result |
|---|---|---|---|
== |
loose equality (with coercion) | 0 == false |
true |
=== |
strict equality (no coercion) | 0 === false |
false |
!= |
loose inequality | "5" != 5 |
false |
!== |
strict inequality | "5" !== 5 |
true |
Wisdom bomb: use === and !== almost always. You want clarity, not vibes-based equality.
Also: NaN is never equal to anything, including itself. Use Number.isNaN(x) to check for it.
5) Logical: The Bouncers
&&(AND),||(OR),!(NOT)- They short-circuit and return the last evaluated operand, not just
true/false.
"hi" && 42; // 42 (both truthy → returns last)
0 || "fallback"; // "fallback" (0 is falsy → returns right)
!"ok"; // false
Use cases:
- Defaults:
speed = userSpeed || 5;(but careful:0is falsy) - Safer defaults:
speed = userSpeed ?? 5;(only null/undefined triggers default)
??is the “did you actually forget this?” operator;||is the “did you give me something truthy?” operator.
Note: mixing ?? with || or && requires parentheses: a ?? (b || c).
6) Ternary: The Pocket If
- Syntax:
condition ? exprIfTrue : exprIfFalse
const mood = mouseX > width / 2 ? "sunny" : "moody";
Perfect for quick decisions in p5.js:
fill(mouseIsPressed ? 255 : 0);
ellipse(width/2, height/2, mouseIsPressed ? 80 : 40);
7) Bitwise & Friends: The Low-Level Goblins
&,|,^,~,<<,>>,>>>- Treat numbers as 32-bit integers. Great for flags, masks, and looking impressive. We’ll high-five them later in the course.
Expression vs Statement: Know Your Lines
- Expression: produces a value. Can live inside other expressions.
- Statement: performs an action. Ends with a semicolon or wraps a block. Doesn’t inherently produce a value.
// Expression statements
x = 10; // assignment produces 10, also updates x
console.log(x + 2); // calls console.log with value 12
// Declaration (statement), not an expression
let y = 5; // the initializer (5) is an expression; the declaration is a statement
Rule of thumb: if you can put it on the right side of
=, it’s an expression.
Precedence & Associativity: Who Speaks First?
Operators don’t all yell at the same volume. Some cut the line.
- Multiplication/division beat addition/subtraction:
1 + 2 * 3is7. !runs before comparison; comparison runs before&&;&&runs before||.=happens last.- Associativity matters:
a = b = c = 0sets all to 0 (right-to-left).
When unsure, add parentheses. It’s not cheating; it’s kindness to Future You.
const hot = temp > 80 && humidity > 0.6; // ok
const ok = (temp > 60 && temp < 80) || breezy; // readable
Special case: don’t mix ?? with &&/|| without parentheses.
Real Talk: Coercion, Truthiness, and Why People Get Confused
- Truthy: basically everything except
0,"",null,undefined,NaN, andfalse. - Loose equality (
==) does type gymnastics. Strict equality (===) does not. +is both math and string concat. The order of operands matters.
Quick gut-check examples:
Boolean("0"); // true (non-empty string)
"0" == 0; // true (coerces string → number)
"0" === 0; // false (types differ)
When building UI logic (like in p5.js), prefer ===, ??, and explicit conversions: Number(input.value()).
Micro-Demo: Operators on Canvas (p5.js)
You’re sketching a reactive dot that changes size and mood with your mouse. Operators run the show.
let base = 20;
function setup() {
createCanvas(600, 400);
}
function draw() {
background(240);
// Arithmetic + assignment
let dx = mouseX - width / 2;
let dy = mouseY - height / 2;
let distFromCenter = Math.hypot(dx, dy);
// Ternary + comparison + logical
const near = distFromCenter < 100;
const vibe = near && mouseIsPressed ? "party" : "chill";
// Nullish coalescing for defaults (imagine external config)
const configuredSize = null; // could be undefined/null
let size = configuredSize ?? (base + distFromCenter / 10);
// Clamp with Math.min/Math.max (expressions!)
size = Math.max(10, Math.min(size, 120));
// Color: string template inside an expression
fill(near ? 255 : 30, near ? 120 : 180, 200);
noStroke();
circle(width / 2, height / 2, size);
// Label
fill(0);
textAlign(CENTER);
text(`${vibe.toUpperCase()} | size: ${Math.round(size)}`, width / 2, 30);
}
Spot the operators: -, /, <, ? :, &&, ??, +, Math.max/min calls, and the template literal. Expressions everywhere, moods controlled by math.
Quick Compare Table (Bookmark This)
| Need | Use | Why |
|---|---|---|
| default unless truly missing | x ?? fallback |
treats only null/undefined as missing |
| any truthy default | `x | |
| strict checks | ===, !== |
predictable, no surprise coercion |
| squishing math | +=, -=, *=, /= |
concise updates |
| tiny decision | cond ? a : b |
inline clarity |
Try These Thought Experiments
- If
score = 0, what doscore || 10andscore ?? 10return? Why? - What does
"5" + 5 - 3evaluate to? Explain the steps. - In
a && b || c, when doescget evaluated? What ifais falsy?
If you can narrate these like a sports commentator, you’ve internalized the vibe.
Wrap-Up: The Operator Manifesto
- Operators let values interact; expressions package that interaction into results.
- Prioritize clarity:
===over==, parentheses over puzzles,??for legit-missing values. - Know your cast: arithmetic for motion, comparison for logic, logical for flow, ternary for compact decisions, assignment for updates.
Code is just well-behaved drama. Operators are the stage directions; expressions are the scenes.
Next up, we’ll tame control flow with if, switch, and loops — the directors that decide which scene plays and when. For now, open your editor, poke a sketch, and let your variables get a little dramatic.
Comments (0)
Please sign in to leave a comment.
No comments yet. Be the first to comment!