edubun 한국어

Variables: let and const

A variable is a name for a value. After let score = 10, the word score stands for 10 until you give it something else.

Naming a value so you can use it again

So far every value has been typed straight into console.log and then forgotten. Real programs need to remember things: the player's score, the items in a basket, the name someone typed in. A variable is a named box that holds a value. You create it once, then use its name wherever you need the value.

let score = 10;
console.log(score);        // 10
console.log(score + 5);    // 15

The line let score = 10; does two things. The keyword let declares a new variable called score, and = 10 puts the value 10 into it. The equals sign here does not mean "is equal to" as in maths. It means "store the value on the right in the name on the left." Programmers call this assignment. When score appears later without quotes, JavaScript looks up the box and uses the value inside.

Changing a value with let

A variable declared with let can be given a new value later. You write the name, an equals sign and the new value, without let this time, because the variable already exists:

let score = 10;
score = 25;
console.log(score);        // 25
score = score + 5;
console.log(score);        // 30

The line score = score + 5; looks impossible as maths, but read it as an instruction and it makes sense. JavaScript first evaluates the right side, the current score plus 5, which is 30. Then it stores 30 back into score. The old value is gone. This pattern, reading a variable and storing an updated value into it, is how programs count, add up totals and keep track of anything that changes.

const for values that stay put

The keyword const also declares a variable, but it must be given a value straight away and can never be assigned a new one. Trying to do so stops the program with TypeError: Assignment to constant variable. That error is useful. If a value is not supposed to change, such as the number of days in a week or a tax rate, declaring it with const means a mistake elsewhere in the program cannot quietly overwrite it.

const daysInWeek = 7;
console.log(daysInWeek * 4);   // 28
// daysInWeek = 8;  would stop with a TypeError

A good habit, recommended by many style guides, is to use const by default and switch to let only when you know the value will change. You may also see the older keyword var in code on the web. It still works, but it follows looser rules that cause surprising bugs, so this course uses let and const only.

Rules for names

A variable name may contain letters, digits, the underscore _ and the dollar sign $, but it cannot start with a digit and cannot contain spaces. So total2 is fine and 2total is not. Names are case sensitive: score and Score are two different variables. A few words such as let, const, if and for are reserved by the language and cannot be used as names. When a name is made of several words, JavaScript programmers usually write it in camelCase: the first word in lower case and each later word starting with a capital, as in totalPrice or daysInWeek. Pick names that say what the value means; price tells a reader far more than x.

Declared but empty, and used too early

If you write let answer; with no value, the variable exists but holds undefined until you assign something. Using a let or const variable on a line above its declaration is an error: ReferenceError: Cannot access 'answer' before initialization. Using a name that was never declared at all gives ReferenceError: answer is not defined. Both messages mean the same practical thing: check the spelling and check that the declaration comes first.

let name = value; can change later. const name = value; never changes.

variableA name that holds a value
declareCreate a variable with let or const
assignmentStoring a value with =
letDeclares a variable whose value can change
constDeclares a variable that cannot be reassigned
camelCasetotalPrice: later words start with a capital
undefinedWhat a declared variable holds before it gets a value
reserved wordA word like let or if that cannot be a name
  1. What does this print?
    let x = 4;
    x = x + 3;
    console.log(x);
  2. What does this print?
    let n = 2;
    n = 10;
    n = n * 3;
    console.log(n);
  3. What does this print?
    let city = "Busan";
    console.log("city");
    • Busan
    • city
    • undefined
  4. What happens when this runs?
    const max = 5;
    max = 6;
    • max becomes 6
    • TypeError: Assignment to constant variable
    • Nothing, max stays 5 silently
  5. Which is a valid variable name?
    • 2ndPlace
    • second place
    • secondPlace
  6. What does this print?
    let total;
    console.log(typeof total);
  7. What does this print?
    let a = 5;
    let b = a;
    a = 9;
    console.log(b);
  8. Are score and Score the same variable?
    • Yes
    • No
  9. Which keyword should you use for the number of minutes in an hour?
    • const
    • let
    • var
  10. What does this print?
    let word = "hi";
    word = word + word;
    console.log(word);
Key points
  • let name = value; declares a variable that can change.
  • const name = value; declares one that cannot be reassigned.
  • = means store, not equals.
  • x = x + 1 reads x, adds 1, and stores the result back.
  • Names: letters, digits, _ and $, no leading digit, case sensitive, camelCase.