Open original
Info
Demo 3.2

Defining variables with let and const

Files in this demo

├─ index.html
└─ script.js

A variable is a name for a value, so you can use it later without retyping it.

let score = 0;
const name = "Gabriel";

The = means “put this in here”. It is not a statement that the two sides are equal ~ that catches people who remember it from maths.

let vs const

  • const ~ you won’t reassign this name.
  • let ~ you will.

Use const by default. Switch to let only when you genuinely need to change the value. It means anyone reading your code (including you, in a month) can see at a glance which values move and which don’t.

You may also see var in older code. It’s the original, it has some strange scoping behaviour, and there’s no reason to write new code with it.

The const gotcha

const list = ["a", "b"];
list.push("c");   // this works!
list = ["x"];     // this does not

const stops you pointing the name at something new. It doesn’t freeze what’s inside. Everyone trips on this once.

The types you’ll use

  • Number ~ 42, 3.14. No quotes.
  • String ~ "text". Quotes, single or double, just be consistent.
  • Boolean ~ true or false.
  • Array ~ ["a", "b"]. An ordered list. Count from zero: list[0] is the first item.
  • Object ~ { name: "Moonbug" }. Named values. Reach in with object.name.
  • null and undefined ~ “deliberately nothing” and “never set”.

Naming

Lowercase first letter, capitals for each word after: myScore, catName. Names can’t start with a number or contain spaces. Make them describe what’s in them ~ x tells you nothing.

Next demoOperations (+, -, <, >, and more)
Keyboard Shortcuts
⌘ Z / ⌘ ⇧ ZCtrl Z / Ctrl ⇧ Z Undo / redo
Tab / ⇧ TabTab / ⇧ Tab Indent / unindent selection
⌘ ] / ⌘ [Ctrl ] / Ctrl [ Indent / unindent lines
⌘ ACtrl A Select all
⌘ DCtrl D Select next occurrence of selection
⌘ /Ctrl / Comment / uncomment lines
Ctrl SpaceCtrl Space Autocomplete
Ctrl EnterCtrl Enter Reset layout
⌘ ⌥ [ / ⌘ ⌥ ]Ctrl ⇧ [ / Ctrl ⇧ ] Fold / unfold block
Code
The editor didn't load — try refreshing the page. Navigation, shortcuts and the info panel still work in the meantime.
Preview
Dimensions0 × 0
Delay
Console