1. Let, var, const are the same
let, var, const can all declare variables
let age = 18;
var age = 19;
const age = 20;
2. The difference between let, var, and const
1. The variable declared by let is only valid in the code block where the let command is located.
function fn(){
console.log(name)
let name = 'hhh'
}
fn();
// 输出 ReferenceError
//let声明的变量不会被初始化,在初始化之前是不可被访问的。这被称为“时间死区”。因此如果在声明变量之前访问,js会抛出 ReferenceError。
2. const declares a read-only constant. Once declared, the value of the constant cannot be changed.
const a; //Error: Missing initializer in const declaration
const a = 1 ; // 1
a = 12 ; //Error: Assignment to constant variable.
const a = 5; // 相同变量名不可重复定义,会报错
console.log(a) //Error: Identifier 'a' has already been declared
3. There are two types of var : global scope and function scope. There is no talk of block scope, and there is variable hoisting.
function fn(){
console.log(name)
var name = '小熊'
}
fn();
// 输出 undefined
The above code is equivalent to
function fn(){
var name
console.log(name)
name = '小熊'
}
fn();
One statement, many variables
You can declare many variables in one statement. The statement starts with var and separates variables with commas:
var lastname="Doe", age=30, job="carpenter";
Declarations can also span multiple lines:
var lastname="Doe",
age=30,
job="carpenter";
Multiple variables declared in one statement cannot be assigned the same value at the same time:
var x,y,z=1;
//x,y 为 undefined, z 为 1。
Through the above explanation, I believe that everyone has a certain understanding of the difference between let, var, and const. Let's look at an example!
Answer: D
In the function, we first
var
declarename
the variable using the keyword. This means that the variable will be promoted during the creation phase (JavaScript
memory space will be allocated for it during the creation phase of the variable creation), the default value isundefined
until we actually execute the line that uses the variable. We haven'tname
assigned a value to the variable yet, so it still holdsundefined
the value.Variables declared with
let
the keywords ( andconst
) also have variable hoisting, but unlike withvar
, the initialization is not hoisted. They are not accessible until we declare (initialize) them. This is called a "temporary dead zone".JavaScript
A is thrown when we try to access a variable before declaring itReferenceError
.