In JavaScript, variables must be declared to be used. Here is an example:
Unlike in languages like Java and C++, where you declare a variable by indicating its type, in JavaScript, you must use a variable declaration keyword:
let
const
var
JavaScript is a dynamically-typed language, which means a variable is assigned a type at runtime based on the variable’s value at the time.
Dynamic typing means you can also change a variable’s type at any time:
If you declare a variable but do not give it a value, its type and value are undefined
.
You can use the typeof
operator to check the type of a value.
let
A variable declared with let
behaves for the most part the way you expect; for example:
It throws an error if you use it before it is declared:
It throws an error if you redefine it:
It has a block scope:
You can learn more in the let
section of the MDN WebDocs reference.
const
Declares a read-only named constant.
Constants are block-scoped, like variables defined using the let
keyword. The value of a constant can’t be changed through reassignment, and it can’t be redeclared.
An initializer for a constant is required.
The const declaration creates a read-only reference to a value. It does not mean the value it holds is immutable (just that the variable identifier cannot be reassigned).
Prefer const
over let
: it provides an extra layer of protection against accidentally reassigning your variables.
For more information, refer to the const
section on MDN WebDocs.
var
The variable declaration keywords let
and const
are relatively new additions to JavaScript. The old way of declaring a variable in JavaScript is using var
:
Variables declared with var
are not block scoped (although they are function scoped). Also, no error is thrown if you declare the same variable twice using var
.
Don’t use var
!
Learn more in the var
section of MDN WebDocs.
Technically, you can declare a variable in JavaScript without using a variable declaration keyword. Variables defined as such become global variables. This is another cruft from the early days of JavaScript, and it must be avoided.
Using an undeclared variable throws ReferenceError
under JavaScript’s “strict mode”, introduced in ECMAScript 5.