JavaScript Tutorial
JavaScript Const
const is a name you do not rebind. The value can still change if it is an object or an array.
A name you do not rebind
const declares a name and assigns it once. You cannot write = to that name again. The binding is fixed. That is the rule.
Example
const days = 7;
console.log(days);
// days = 8; // TypeError: Assignment to constant variableUse const for values that are facts in this program: a tax rate, a maximum, a heading string you will not replace.
Run the examples in /javascript/try. Try it in JavaScript opens that editor.
You must assign on the same line
let can wait. const cannot. A declaration without a value is a syntax error.
Example
const title = "StudyGrid";
console.log(title);
// const empty; // SyntaxError: Missing initializerIf you do not know the value yet, use let. Switch to const when the value is known and will not be replaced.
Objects can still change
const locks the binding, not the insides of an object. You cannot point the name at a different object. You can change a property on the object that is already there.
Example
const person = { name: "Ada" };
person.name = "Grace";
console.log(person.name);
// person = { name: "Alan" }; // TypeError: Assignment to constant variableperson.name = "Grace" edits the object. person = ... tries to rebind the name. The first is allowed. The second is not.
Arrays can still change
The same split applies to arrays. You can push, pop, and assign an index. You cannot replace the whole array with a new one through that name.
Example
const colors = ["red", "green"];
colors.push("blue");
console.log(colors);
// colors = []; // TypeError: Assignment to constant variableconst is still the right default for arrays and objects you build once and then fill. You are promising not to swap the box, not that the contents are frozen.
const vs let
| const | let | |
|---|---|---|
| Must initialize | Yes | No |
Rebind with = | No | Yes |
| Change object properties | Yes | Yes |
| Scope | Block | Block |
Both are block-scoped. Both refuse a second declaration in the same block. The difference is rebinding.
Start with const
A useful habit: declare with const. If the next line needs to assign again, change that one name to let. Most names in a small script never need to be rebound.
const is not “the value can never change.” It is “this name will always point at this same value.” For numbers and strings, those two sentences mean the same thing. For objects and arrays, they do not.
What comes next
You can now name a value and decide whether that name may move. Next: operators — the symbols that compute and compare.