Variables: let, const, var
A variable is a named container for a value. JavaScript gives you three ways to declare one: let, const, and var. let name = "Ali"; creates a variable that can be reassigned later: name = "Sara"; is valid. const age = 16; creates a variable that cannot be reassigned trying age = 17; later causes an error. Use const by default, and switch to let only when you genuinely need to change the value later. var is the oldest way to declare a variable, from before let and const existed. It behaves differently in ways that cause real bugs (covered briefly in scope, later in this course) modern JavaScript almost always prefers let and const instead. Variable names can contain letters, numbers, underscores, and dollar signs, but can't start with a number. JavaScript convention uses camelCase for variable names, like studentAge, not student_age.
Why this matters
- ·const communicates clearly that a value shouldn't change, which helps prevent accidental bugs.
- ·let gives you a variable you can safely reassign as your program runs.
- ·Meaningful variable names make code far easier to read later, including by you.
Common mistakes
- ·Trying to reassign a const variable causes an error use let if a value genuinely needs to change.
- ·var has confusing scoping behavior compared to let and const, and is best avoided in new code.
- ·Using unclear names like x or data1 makes code hard to understand later.
Frequently asked questions
Use const by default. Only switch to let if the value genuinely needs to be reassigned later in your code.
Practice questions
Question 1
Create a const called city with your city's name, and display it in the page.
Question 2
Create a let variable called score starting at 0, then reassign it to 10, and display it.
Quick check
Just for this topic answer honestly, then check yourself.
1 / 3
