SoFunction
Updated on 2025-05-13

JavaScript variable declaration keywords var, let, const

Variables in JavaScript are loosely typed and can hold any type of data, and a variable is nothing more than a name. In JavaScript, the keywords that can declare variables include var, let, and const.

1. var

Use var to define variables and you can save any type of value. If the variable is not initialized, the variable will be saved undefined.

1.1 Function-level scope

A variable defined with var becomes a local variable of the function containing it.

function func() {
    var a = 'hi'; // Local variables}
func();
(a); // ReferenceError: a is not defined

Variable a is defined in the function using var, calling the function func will create this variable and assign it a value. After the function is executed, the variable will be destroyed, so the last line of the above code will report an error, showing that the variable a is undefined.

If the variable a is directly assigned to the function without using the var operator, then a becomes a global variable and can be accessed outside the function. In the browser environment, a becomes the property of the window object.

function func() {
    a = 'hi'; // Global}
func();
(a); // hi
(); // hi
( === a); // true

1.2 Variable improvement

Declaring variables with var will automatically be promoted to the top of the function scope, as shown below:

function func() {
    (a);
    var a = 1;
}
func(); // undefined

The code reported no error, and the output was undefined. This is because the declaration of the variable was promoted to the top of the function scope, which is equivalent to the following code:

function func() {
    var a;
    (a);
    a = 1;
}
func(); // undefined

1.3 Repeat statement

In addition, it is also possible to repeatedly declare the same variable using var:

function func() {
    var a = 1;
    var a = 2;
    var a = 3;
    (a);
}
func(); // 3

1.4 Global variables are mounted to window

In the browser environment, under the global scope, variables declared using var will be mounted on the window object.

var a = 1;
( === a); // true

An interview question:

("1":a,b);
var a = 12,b="34";
function foo(){
    ("2":a,b);
    var a=b=12;
    ("3":a,b);
}
foo()
("4":a,b);

Answer:
1: undefined,undefined //The variable has been declared but not assigned. Why is it said here that the variable has been declared? It is because when js compiles, all variables will be declared to the front, followed by the declaration of the function.
2: undefined, ‘34’ //Because the following var a= declares a again, a is undefined again, note that b is not declared here. If var a=b=12 is changed to var a=12, b=12, then the answer is undefined, undefined
3: 12, 12 //a, b have all been declared and assigned
4: 12,12 //a,b have all been declared and assigned, but here we need to distinguish it from the previous one, b=12 is because the value is reassigned in the function. As the second article says, if var a=b=12 is changed to var a=12, b=12, then the answer is 12, "34" and this 12 is assigned by the second line.

2. Let

Let can also declare variables, but there is a big difference between it and the var operator.

2.1 Block-level scope

The following code will report an error because the scope declared by let has a block-level scope, that is, the part wrapped by {}.

if (true) {
    let a = 10;
}
(a); // a is not defined

2.2 No repetitive declaration

The following code will report an error when executing let a = 2, because variable a has been declared in the current block-level scope and cannot be declared repeatedly.

if (true) {
    let a = 1;
    let a = 2; // SyntaxError: Identifier 'a' has already been declared
    let a = 3;
}

In addition, if you use var and let to declare variables, it is not allowed, and the following code will report an error:

let a;
var a; // Report an error
var a;
let a; // Report an error

2.3 There is no variable promotion (temporary lock zone)

A variable declared using let cannot be accessed before it is declared.

if (true) {
    (a); // ReferenceError: Cannot access 'a' before initialization
    let a = 1;
}

In fact, JavaScript will also pay attention to let declarations that appear after the block, except that undeclared variables cannot be referenced in any way before this. The moment of execution before the let declaration is called a temporary dead zone.

2.4 Global variables will not be mounted to window

Unlike var, variables declared using let will not be mounted to window objects even under global scope.

var a = 1;
let b = 2;
( === a); // true
( === b); // false

2.5 No dependency condition declaration

if (typeof name === 'undefined') {
    let name;
}
// name is limited to the scope of the if {} blockname = 'Matt'; // Global assignment
try {
    (age); // If age has not been declared, an error will be reported} catch (error) {
    let age;
}
// age is limited to the scope of the catch {} blockage = 26; // Global assignment

3. Const

The characteristics of const are basically the same as let, but const has some of its own characteristics.

3.1 The variable must be initialized at the same time

The following statement reports an error because the variable is not initialized at the same time.

const a; // Missing initializer in const declaration

3.2 Cannot modify the declared variables

After defining a variable with const, its value cannot be changed:

const a = 1;
a = 2; // TypeError: Assignment to constant variable

There is a misunderstanding here. In fact, the memory address cannot be modified using variables declared by const! !

The specific rules are as follows:

  • When the constant defined by const is a basic data type, it cannot be modified.
  • When the constant defined by const is a reference data type, data modification can be performed through its properties.

The value of the basic data type is stored in the memory address, so the basic data type defined by const cannot be changed. The memory address pointed to by the reference data type is just a pointer, pointing to the actual data through a pointer, that is, the pointer that cannot be changed is the pointer, not the data, so the constants of the reference data type defined by const can modify their data through attributes.

For example, using const to define an array. Although the data type cannot be changed, the data in this array can be modified by push and other methods.

const arr = [];
(1, 2, 3);
(arr); // [ 1, 2, 3 ]

4. Summary and best practices

var let const
Function-level scope Block-level scope Block-level scope
Repeat statement No repetitive statement No repetitive statement
Variable enhancement No variable promotion No variable promotion
Values ​​can be changed Values ​​can be changed Value cannot be changed
Global variables mounted to window Global variables will not be mounted to window Global variables will not be mounted to window

Generally, when writing JavaScript code, follow the following principles:

  • Don't use var
  • Const is preferred, let is second

An interview question:

for (var i = 1; i <= 5; i++) {
    setTimeout(function () {
        (i);
    }, 0);
}

Answer: 6 6 6 6 6

This is the article about JavaScript variable declaration keywords var, let, const. For more related JS variable declaration keywords var, let, and const, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!