Once you start learning JavaScript, you quickly meet the word “variable.” No need to tense up. A variable is a box you’ve given a name.
Let’s write one
let name = "Shima";| Part | Meaning |
|---|---|
let | The signal “I’m setting up a box” |
name | The name you gave the box |
"Shima" | The contents you put in the box |
From now on, writing name calls up the “Shima” inside. For example, in a spot where you use the same name over and over, instead of writing it out each time you just call name—that’s the joy of tucking it away in a box.
You can put numbers in too
It’s not only text that fits in a box. Numbers go right in as well.
let age = 3;
let city = "Hokkaido";Wrap text in " ", and write numbers as they are. Remembering just this difference is enough. If you keep a number in there, you can later use it for calculations like “add 1.”
The contents can be swapped later
The word “variable” comes from “able to vary.” True to the name, the contents can be swapped later.
let count = 0;
count = 1;A box that first held 0 now has 1 put back in. It’s exactly because this “swap” is possible that you can build movement like “the number goes up each time you press.”
There are a few rules for naming
I said “you can name it however you like,” but there are just a few promises.
- You can use plain letters and numbers (and
_). You can’t start with a number, like1st - You can’t put a space in the middle (
my nameis an error) - Uppercase and lowercase are treated separately (
nameandNameare different boxes)
Since you can’t use spaces, when you want to join two or more words, you capitalize the first letter of each word from the second onward and connect them. It looks like thanksMessage (thanks + message). Because the uppercase parts look like a camel’s humps, this is called camelCase, a classic way of writing in programming.
The box you don’t swap: const
A close cousin of let is const. It’s written the same way, but a box made with const can’t have its contents swapped later.
const city = "Hokkaido";“Use const for a value you don’t plan to swap, and let for a value you do plan to change”—that’s the guideline for choosing. In real code, situations where you use const come up more often than let. When in doubt, try const first.
Summary of this lesson
- Variable = a box you’ve given a name
- Set up a box with
let name = contents; - The contents can be swapped later (that’s exactly why it’s called a “variable”)
- For a box you don’t swap, use
const. When in doubt, start with const