JavaScript Tutorial: Variables
let, const, var — store data, change it, and understand why var is a trap.
Give your data a name
In Chapter 1 you printed literals directly. But what if the same value is used in ten places? Change it once and it updates everywhere — that's variables.
JavaScript has three ways to declare them: `const`, `let`, and `var`. You will learn why `const` is the right default and when to reach for the others.
What you'll learn in this JavaScript variables tutorial
This interactive JavaScript tutorial has 10 hands-on exercises. Estimated time: 18 minutes.
- const — your go-to variable — In Chapter 1 you typed `"JavaScript is awesome!"` directly in console.log. What if you need that value in ten places?
- Create your own const — Create two `const` variables — `name` with your name and `city` with your city. Then print them with a template literal.
- const cannot be reassigned — The 'const' in `const` stands for constant. Once set, you cannot reassign it.
- let — when you need to change — `let` works like `const` but allows reassignment. Use it when the value will genuinely change — like a score, a counter,…
- ++ and -- shortcuts — Adding or subtracting 1 is so common JavaScript has special shortcuts:
- var — and why to avoid it — `var` is the original JavaScript variable declaration from 1995. It has two problems:
- Naming rules — Variable names have rules:
- Multiple assignments — You can declare multiple variables on separate lines or use destructuring to unpack from an array (more on that in Chapt…
- undefined and the temporal dead zone — An uninitialized `let` is `undefined`. Accessing a `let` before its declaration (the temporal dead zone) crashes.
- Build a profile — No starter code. Write everything from scratch.
JavaScript Variables concepts covered
- Give your data a name