Variables and types
โ Report an issue with this lessonDeclare variables with let (can change) or
const (can't be reassigned). Default to const and
switch to let only when you know a value needs to change.
const name = "Ada";
let age = 28;
age = 29; // fine, age was declared with let
Core types:
typeof "hello" // "string"
typeof 42 // "number"
typeof true // "boolean"
typeof undefined // "undefined"
typeof null // "object" (a well-known JS quirk)
Template literals (backticks) let you embed variables in strings, like Python's f-strings:
const greeting = `Hello, ${name}! You are ${age}.`;
Template literals can also span multiple lines without any special escape character -- something regular quoted strings can't do:
const message = `Hi ${name},
Thanks for signing up.
See you soon.`;
let vs. const vs. var
You'll sometimes see a third keyword, var, in older code or
tutorials. Avoid it in new code: var ignores block scope (a
variable declared inside an if block with var
"leaks" outside of it) in a way that causes real bugs, while let
and const are scoped to the nearest { } block,
matching what most people expect:
if (true) {
let x = 1;
var y = 2;
}
console.log(y); // 2 -- leaked out of the block
console.log(x); // ReferenceError -- x doesn't exist here
const doesn't mean "unchangeable"
A common misconception: const only prevents
reassigning the variable itself. If the value is an object or
array, its contents can still be changed:
const student = { name: "Ada" };
student.name = "Grace"; // fine -- mutating the object, not reassigning it
student = {}; // TypeError -- can't reassign a const
Type coercion: JavaScript's quirky auto-conversion
JavaScript will often convert between types automatically rather than raising an error, which can be surprising:
"5" + 1 // "51" -- number gets converted to a string
"5" - 1 // 4 -- string gets converted to a number
1 + true // 2 -- true becomes 1
+ prefers to concatenate as text if either side is a
string; other math operators prefer to convert to numbers. When in doubt
about what type you're working with, use typeof to check, or
convert explicitly with Number(value) or String(value)
rather than relying on automatic coercion.
Try it yourself
Run your code and get it working before marking this lesson complete.
8 more lessons โ including Project: build a simple calculator โ plus a certificate are waiting.
Unlock the full course โ $29.99