Variables
In JavaScript, you must declare a variable before you can use it. Here is an example:
let firstName; // declare
firstName = "Ali"; // initialize
console.log(firstName); // use
let lastName = "Madooei"; // declare and initialize
console.log(lastName); // use
In languages like Java and C++, you declare a variable by writing its type. In JavaScript, you use a variable declaration keyword instead:
letconstvar
JavaScript also performs implicit type coercion, which means values are sometimes converted automatically when operators are applied.
"5" + 2; // "52" (number coerced to string)
"5" - 2; // 3 (string coerced to number)
true + 1; // 2 (boolean coerced to number)
If you declare a variable but do not give it a value, its type and value are undefined.
let num;
console.log(num); // prints undefined
console.log(typeof num); // prints undefined
Block-scoped Local Variables with 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:
console.log(num); // ReferenceError: Cannot access 'num' before initialization let num = 2; -
It throws an error if you redeclare it:
let num = 2; let num = "two"; // SyntaxError: Identifier 'num' has already been declared console.log(num); -
It has a block scope:
for (let num = 1; num < 10; num++) { // do something with num } console.log(num); // ReferenceError: num is not defined
Constants with const
Variables declared using the const keyword are constants. They cannot be redeclared or reassigned.
let firstName = "Ali";
firstName = "John"; // OK
const lastName = "Madooei";
lastName = "Doe"; // TypeError: Assignment to constant variable.
Constants are block-scoped, like variables declared using the let keyword.
You must give a constant a value when you declare it.
const lastName; // SyntaxError: Missing initializer in const declaration
lastName = "Madooei";
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).
const numbers = [1, 2, 7, 9];
numbers[2] = 4; // OK: numbers now are [1, 2, 4, 9]
Function-scoped Variables with var
The variable declaration keywords let and const are later additions to JavaScript. The old way of declaring a variable was using var:
var firstName = "Ali";
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.
Undeclared Variables
Technically, you can create a variable in JavaScript by assigning a value to a name that has not been declared. Variables created this way become global variables. This behavior is a leftover from the early days of JavaScript. Avoid it.
firstName = "Ali";
console.log(window.firstName);
Assigning to an undeclared variable throws a ReferenceError under JavaScript’s “strict mode”, introduced in ECMAScript 5.