Skip to main content

What are variables?

Variables store data that you’ll use throughout your program - user input, API responses, calculation results, and more. JavaScript has two ways to declare variables: let for values that change, and const for values that don’t.

Declaring variables

const prevents reassignment - once you set a value, you can’t change it. let allows the value to be updated later.
Default to const unless you know the value needs to change. This prevents accidental reassignments and makes your code easier to understand.

Updating variables

With let, you can reassign the variable as many times as needed. Use +=, -=, *=, /= for arithmetic shortcuts.

Naming conventions

Start with a lowercase letter, then capitalize the first letter of each new word. For true constants (values that never change across your entire app), use UPPER_CASE with underscores.
JavaScript variable names can contain letters, numbers, underscores, and dollar signs - but they can’t start with a number.

Variable scope

Variables declared with const and let are “block-scoped” - they only exist within the nearest set of curly braces {}.
Keep variables in the smallest scope possible. This makes your code easier to debug and prevents naming conflicts.

Comparing to Python

Python doesn’t distinguish between changeable and unchangeable variables - everything can be reassigned. JavaScript’s const helps you catch bugs by preventing accidental reassignments.

Common mistakes

const prevents reassignment, but it doesn’t make objects or arrays immutable. You can still modify properties or add items - you just can’t reassign the entire variable.
const only prevents reassigning the variable itself. You can still modify the contents of objects and arrays.
var is the old way of declaring variables. It has weird scoping rules and can cause bugs. Pretend it doesn’t exist - always use let or const.

What’s next?

Now that you can store data in variables, let’s learn about the different types of data JavaScript can handle.

Data types

Numbers, strings, booleans, and more