Lesson 27 min read
Operators & Expressions
The math and logic superpowers that make your code actually do things
Arithmetic Operators β Math Class, But Fun
JavaScript can do all the math you'd expect, plus a few bonus tricks. Think of operators as action words β they tell JavaScript to do something with values.
+β addition (also concatenates strings!)-β subtraction*β multiplication/β division%β modulo (the remainder after division β super useful for checking even/odd)**β exponentiation (power of).2 ** 3means 2Γ2Γ2 = 8
The + operator is sneaky β when you use it with a string, it glues things together instead of adding them. This catches a lot of beginners off guard!
Arithmetic in Action
=== vs == β The Battle of Equality
This is one of the most important things to understand in JavaScript. There are two ways to check equality, and they behave very differently:
===(strict equality) β checks if the value AND the type are the same. No funny business. This is what you should use 99% of the time.==(loose equality) β tries to convert values to the same type before comparing. This leads to some truly weird results.
Same goes for !== (strict not-equal) vs != (loose not-equal). Always prefer the strict versions.
Strict vs Loose Equality β The Weirdness
Logical Operators & Modern Shortcuts
Logical operators let you combine conditions β they're the glue of if statements.
&&(AND) β both sides must be true||(OR) β at least one side must be true!(NOT) β flips true to false and vice versa
JavaScript also has two modern operators that experienced devs love:
??(nullish coalescing) β returns the right side ONLY if the left side isnullorundefined. Unlike||, it doesn't treat0,"", orfalseas "missing."?.(optional chaining) β safely access deeply nested properties without crashing if something in the chain isnullorundefined.
Logical Ops, Ternary, ??, and ?.
Note: Here's a mental shortcut: === asks "Are you the EXACT same thing?" while == asks "Could you maybe, possibly, if I squint hard enough, be the same thing?" Just always use === and you'll avoid an entire category of bugs.
Challenge