JavaScript Variables: let, const and var Explained
A variable is a named slot for a value. Modern JavaScript has two keywords for creating one: const for names that will not be reassigned, and let for names that will. A third, var, is older and best avoided in new code.
const by default, let when needed
const site = "TetSharing"; binds the name site permanently in its scope. Trying to assign to it again throws a TypeError, which the example catches so you can see the error name. let visits = 1; can be reassigned as often as you like: visits = visits + 1 or the shorthand visits += 10.
A good habit is to start with const and switch to let only when you really reassign. Readers then know that a const name means the same thing everywhere it appears.
const is not "frozen"
const protects the binding, not the value. A const array can still have items pushed into it, and a const object can have properties changed, because you are modifying the same object rather than pointing the name somewhere else. To prevent changes to the object itself, use Object.freeze().
Expected output
TetSharing 12 ["JS", "SQL"] TypeError block scoped undefined
Block scope
let and const are block scoped: a name declared inside { ... }, including the body of an if or a loop, exists only inside those braces. After the block, inner is unknown, so typeof inner reports "undefined". (typeof is one of the few operations that does not throw for an undeclared name.) Using a let name before its declaration line throws a ReferenceError; the region before the declaration is called the temporal dead zone.
Why not var?
var is function-scoped instead of block-scoped, and its declarations are hoisted to the top of the function with the value undefined. A var inside a loop leaks out of it, which causes subtle bugs. You will still see var in older tutorials and code bases, so recognize it, but write let and const.
Names may contain letters, digits, _ and $, cannot start with a digit, and are case-sensitive. The convention is camelCase: maxSpeed, userName.
Common mistakes
- Reassigning a
const, which throwsTypeError: Assignment to constant variable. - Declaring the same
letname twice in one scope, which is aSyntaxError. - Assigning without any keyword. In sloppy mode this silently creates a global variable; in strict mode it throws.
Summary
- Use
constby default andletfor values you reassign. conststops reassignment, not changes to an object's contents.letandconstare block scoped;varis function scoped and legacy.
Quiz: let, const and var