Storing a Value with const
Introduction
Welcome back to Writing and Running Your First JavaScript Programs! This is the last lesson of the course, and it is a big one.
Up to now, every value in our programs has been typed straight into a console.log. That works for a greeting, but imagine a receipt that mentions the customer's name four times. Typing "Alex" four times is tedious, and if the customer turns out to be Sam, we have four places to fix.
In this lesson, we will learn how to:
- Store a value under a name of our choosing, using
const. - Read that value back by name wherever we need it.
- Choose names that make our programs easy to read.
By the end, we will have a small program that remembers a customer and a price and uses them in several lines of output.
Why Store a Value?
Programs become useful the moment they can remember things. A name typed once and used many times, a price that appears on every line of a receipt, a count that we check later on - all of these need somewhere to live while the program runs.
That "somewhere" is a variable: a named place that holds a value. We pick the name; JavaScript keeps the value under it. Whenever we write the name later, JavaScript quietly swaps in the value it is holding.
Declaring a Variable with const
To create a variable, we write the word const, then the name we want, then an equals sign, then the value:
Let's take this apart:
consttells JavaScript that we are creating a new variable. The word is short for constant, and it means the value will stay the same for the rest of the program.customerNameis the name we chose.- The
=is not a mathematical "equals". It means store the value on the right under the name on the left. Read it as "becomes" or "is set to". "Alex"is the value being stored - a piece of text, so it has quotation marks.
Nothing appears on the screen when this line runs. Storing a value is a quiet action; only console.log makes anything visible.
We can store a number the same way, without quotation marks:
Now JavaScript is holding two values for us, each under its own name.
Reading a Value Back by Name
