Variables & Data Types
What Are Variables?
Imagine you have a bunch of labeled jars in your kitchen. One says "sugar," another says "flour." You can peek inside any jar to see what's in it, swap the contents, or empty it out. Variables are exactly like those jars — they hold a piece of data and give it a name you can use later.
In JavaScript, you create a variable with one of three keywords: let, const, or var.
let— your go-to choice. You can change what's inside later.const— a locked jar. Once you put something in, you can't swap it out.var— the old-school way. It still works, but it has some quirky behavior that can trip you up. Preferletandconstinstead.
Creating Variables
JavaScript's Data Types
Every value in JavaScript has a type — it's how JS knows whether you're dealing with a number, some text, or something else entirely. There are 7 primitive types (simple, single values) and 1 object type (complex, can hold many values).
Here are the primitives you'll use every day:
- Number — any numeric value:
42,3.14,-7. JavaScript doesn't separate integers and decimals — they're all just "numbers." - String — text wrapped in quotes:
"hello",'world', or backticks`hi`. - Boolean — only two possible values:
trueorfalse. Think of it as a light switch. - Undefined — a variable that exists but hasn't been given a value yet. Like an empty jar with a label on it.
- Null — you intentionally say "this jar is empty." It's your way of saying "nothing here on purpose."
- BigInt — for really, really huge numbers beyond what
Numbercan handle. - Symbol — a unique identifier. You probably won't need these until later.
typeof — Checking What Type Something Is
The Weirdness of NaN and null
NaN stands for "Not a Number," but typeof NaN returns "number". Wild, right? It shows up when a math operation goes wrong — like trying to multiply a word by a number.
null is supposed to mean "no value," yet typeof null returns "object". This is actually a bug from 1995 that was never fixed because too much code already depended on it. Welcome to JavaScript!
To check for NaN, use Number.isNaN(). To check for null, just use === null.