Skip to content
Lesson 2 of 15

Step 1 of 7 · Reading · ~3 min

Learn

Getting Started

Variables: let and const

A variable is a name attached to a value. By the end of this lesson you can choose between const and let, change a variable's value over time, and turn lines of input into numbers.

const and let

javascript

= is assignment, not a question about equality. The right side is evaluated first, then the name on the left is pointed at the result. That is why lives = lives - 1 is not a contradiction: the old lives (3) is used to compute the new one (2).

The rule to follow: declare with const; switch to let only when the value must change. A reader who sees const knows the name never moves.

javascript

The program starts fine and throws when that line runs. If your own program dies with this message, the fix is almost always to change that one declaration to let.

const locks the name, not the contents

An array is a list of values in square brackets; the arrays lesson covers them properly. Here one is just something that can be changed after it is created:

javascript

For now: const stops reassignment, nothing more.

Block scope

A block is the code between { and }. Variables made with let and const exist only inside the block that declares them:

A bare block can stand on its own:

javascript

The same rule holds for the blocks that conditionals, loops and functions use in later lessons: a let or const inside the braces stays inside the braces.

var, the older keyword, ignores blocks and leaks out of them, which causes bugs that are hard to see. Old tutorials still use it; you should not.

Values have types

Every value has a type, and typeof tells you which:

javascript

This matters because everything read from stdin is a string. "7" + "5" is "75", not 12. Wrap each line in Number(...) to convert:

javascript

Reading several lines

Input arrives as one string with \n between lines. split('\n') turns it into a list you index from 0:

javascript

Naming

Names use letters, digits, _ and $, cannot start with a digit, and are case-sensitive (Total and total differ). Use camelCase for variables, and UPPER_SNAKE_CASE for fixed settings such as MAX_RETRIES.

Common mistakes

  • Declaring with const a value you later update. The program crashes with Assignment to constant variable.
  • Forgetting Number(...) and getting "75" where you wanted 12: with strings, + joins instead of adding.
  • Re-using the first value instead of the updated one. After x = x + 5, the next step must build on the new x.
  • Declaring a variable inside a block and reading it outside.

Your exercise

You track a running balance. The starter reads four numbers and declares let balance. Update the same variable step by step and print it after each step.

Up nextNumbers and MathGetting Started

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…