JavaScript Tutorial
JavaScript Variables
A variable is a named box. Modern JavaScript uses let and const. var is the old keyword.
A named box
A variable holds a value under a name. You declare the name, put a value in, then read it later. The name stays. The value can change if you used let.
Example
let score = 10;
console.log(score);
score = 15;
console.log(score);score is the name. 10 is the first value. The second assignment replaces it with15.
Run this in /javascript/try with Try it in JavaScript. Watch the console pane.
let, const, and var
Three keywords declare a name. Use let when the value will change. Use const when you will not rebind the name. Do not use var in new code.
| Keyword | Rebind the name? | Scope |
|---|---|---|
let | Yes | The block it is in |
const | No | The block it is in |
var | Yes | The function it is in — old rules |
The next two chapters cover let and const in full. This page is the map.
Declare, then assign
You can declare and assign in one line. You can also declare first and assign later with let. Until you assign, the value is undefined.
Example
let title;
console.log(title);
title = "StudyGrid";
console.log(title);const cannot wait. It needs a value on the same line as the declaration. That is one reason beginners start with let and then switch names to const when the value is known and fixed.
Assignment replaces the value
= stores a value in a name that already exists. It is not the same as ===, which compares. Read = as “put this in that box.”
Example
let count = 0;
count = count + 1;
count = count + 1;
console.log(count);Each assignment uses the current value, adds one, and stores the result. After two updates, countis 2.
Why not var
var is function-scoped and can be redeclared in the same scope. Those rules surprise people.let and const are block-scoped and refuse a second declaration in the same block.
Example
var n = 1;
var n = 2;
console.log(n);That second var n is allowed. The same pair with let is a syntax error. Prefer the stricter keywords. You will still see var in old pages and old answers.
This tutorial uses let and const only. If a snippet on the web starts withvar, rewrite it.
Names
JavaScript is case-sensitive: Score is not score. Start with a letter, underscore, or $. Do not use a reserved word such as let or return.
| Good | Poor |
|---|---|
itemCount, taxRate, n | x1x2, data, temp2 with no context |
Common style in JavaScript is camelCase: itemCount, not item_count. Both are legal. Pick one style and keep it.
A type can change
JavaScript does not lock a name to one type. A let that held a number can later hold a string. That is legal. It is also a source of bugs. Keep one kind of value in one name.
Next: let — reassignment and block scope.