Variables
Variables are containers for storing data. JavaScript has three ways to declare variables: var, let, and const.
var, let, const
var name = 'Alice' // old way (avoid in modern JS)
let age = 25 // block-scoped, can be reassigned
const PI = 3.14159 // block-scoped, cannot be reassigned
Naming Rules
- Use camelCase for variable names:
myVariable,firstName - Names can contain letters, digits,
_,$ - Names cannot start with a digit
- Names are case-sensitive:
myVar≠myvar
Reserved Words (28)
These words cannot be used as variable names:
break, case, catch, class, const, continue, debugger,
default, delete, do, else, export, extends, finally,
for, function, if, import, in, instanceof, let, new,
return, super, switch, this, throw, try, typeof, var,
void, while, with, yield
Examples
let firstName = 'John'
let lastName = 'Doe'
let fullName = firstName + ' ' + lastName
console.log(fullName) // John Doe
const MAX_SIZE = 100
// MAX_SIZE = 200 // Error! Cannot reassign const
💡 Best practice
Prefer const by default. Use let only when you need to reassign. Avoid var.