SoFunction
Updated on 2025-03-01

Detailed explanation of the scope differences between var let declarations in JS

var declaration promotion

(name)  //Potatovar name = 'Potato';

usevarThe declared variable will automatically be promoted to the top of the function scope

function foo(){
    (name);
    var name = "Potato";
}
foo()  //undefined
//Equivalent tofunction foo(){
    var name;
    (name);
    name = "Potato";
}
foo(); //undefined
(name)  //ReferenceError name is not definedlet name ="Potato";

and useletDefinednameWill not be promoted, reportReferenceErrorerror;

var can repeatedly declare the same variable

var name = "tomato";
var name = "watermelon";
var name = "Potato";
(name);//Potato

Using let repeatedly declare the same variable will report an error.

var name = "Potato";
let name = "Potato";
(name);//'name' has already been declared
let name = "Potato";
var name = "Potato";
(name);//Cannot redeclare block-scoped variable 'name'.

var global statement

var name = "Potato";
();//Potatolet age = "24";
();  //undefined

usevarThe defined variable will be mounted on the window and become a property of the window object, but using let will not.

Scope

if(true){
    var name = "Potato";
    (name);
}
(name);
//Potato//Potatoif(true){
    let age = 24;
    (age);
}
(age);
//24
//undefined

usevarThe scope declared is the function scope, usingletThe scope of the declaration is the block scope.

The above is a detailed explanation of the scope of var let declarations in JS. For more information about the scope of var let declarations in JS, please pay attention to my other related articles!