JavaScript Variables
What are Variables?
Variables are containers for storing data values. Think of them as labeled boxes where you can store information and retrieve it later.
Three Ways to Declare Variables
JavaScript has three keywords for declaring variables: var,
let, and const.
let (Recommended)
Modern way to declare variables that can be reassigned
let score = 0;
score = 10; // ✅ Can reassign
const (Recommended)
For values that won't be reassigned (constants)
const PI = 3.14159;
// PI = 3; // ❌ Error! Cannot reassign
var (Old Way)
Legacy way, avoid in modern code
var oldStyle = 'avoid this';
// Has weird scoping issues
let vs const - When to Use Each?
const by
default. Only use let when you know the value will
change. Avoid var.
Variable Naming Rules
✅ Valid Names
let userName = 'Alice';
let user_age = 25;
let $price = 99.99;
let _private = 'secret';
let camelCaseStyle = 'recommended';
❌ Invalid Names
let 123name = 'error'; // Can't start with number
let user-name = 'error'; // No hyphens
let let = 'error'; // Can't use keywords
let my name = 'error'; // No spaces
Variable Scope
Scope determines where variables can be accessed in your code.
Reassigning Variables
Summary
- Variables store data values
- Use
constby default for values that won't change - Use
letfor values that will be reassigned - Avoid
varin modern JavaScript - Variable names must start with a letter, $, or _
- Use camelCase for variable names
letandconsthave block scope
Quick Quiz
Which keyword should you use for a value that won't be reassigned?
Enjoying these tutorials?