Loading course content...
Loading course content...
Code Playground is only enabled on larger screen sizes.
A variable is a way for the program to "remember" a value so that it can be reused later.
There are three different ways to define a variable in JavaScript, using the keywords let, const, and var.
let defines a mutable variable, meaning you can change the value after it has been declared. For example:
let a = 123;
a = null;
console.log(a); // -> null
a = 0;
console.log(a); // -> 0
a = "John Doe";
console.log(a); // -> John DoeRemember that the equal sign (=) here doesn't really mean equal, it is the assignment operator that assigns a value to a variable.
Using let, you are allowed to declare a variable first, and assign a value later. Before the value is assigned, the variable will be automatically assigned undefined.
let a;
console.log(a); // -> undefined
a = 123;
console.log(a); // -> 123const, on the other hand, defines an immutable constant. If you try to change its value, an error will be returned.
const b = 123;
b = 100; // -> Error
console.log(b);/Users/. . ./index.js:3
b = 100;
^
TypeError: Assignment to constant b.
at Object.<anonymous> (/Users/. . ./index.js:3:10)
. . .
Node.js v21.6.0You cannot declare the variable first and then assign the value later using const.
const variable;
variable = 100;
console.log(variable);/Users/. . ./index.js:1
const variable;
^^^^^^^^
SyntaxError: Missing initializer in const declaration
at internalCompileFunction (node:internal/vm:77:18)
. . .
Node.js v21.6.0The var keyword is the legacy method of defining a variable. In terms of mutability, it behaves just like let. You can change its value after being declared.
var variable = 123;
variable = 100;
console.log(variable);100The feature that makes var unique has to do with its scope. var can only be either function-scoped or global-scoped, but not block-scoped.
To better understand this, we'll discuss what is a scope later.
let a = 123; a = null; console.log(a); // -> null a = 0; console.log(a); // -> 0 a = "John Doe"; console.log(a); // -> John Doe