current position:Home>Everything you need to know about VaR, let and const in JavaScript

Everything you need to know about VaR, let and const in JavaScript

2021-08-26 14:16:27 wscats

stay JavaScript Variables can be defined using keywords var,let or const.

We can understand var,let and const Before different , We need to know a JavaScript The concept of Scope .

Scope Essentially, it refers to where these variables are available .

Global scope

Globally declared variables have global scope outside any function .

Global variables can be from JavaScript Access anywhere in the program .

Local scope

Variables declared within a function have function scope .

Local variables can only be accessed from within the function that declares them .

Block scope

The code block is JavaScript The code between curly braces . In block {} Variables declared within have block scope .

Use it carefully var A variable declared by a keyword cannot have a block scope .


var Declarations can be global or local ( In the function ).

When var When a variable is declared outside a function , Scope is global . var When declared in a function, it is the function scope .


use var Keyword declared variables can be redeclared like this


Or their values can be updated like this



let Now it's the first choice for variable declarations . It's no surprise , Because it's right var Declared improvements . It also solves var Some remaining problems , Let's see how it works .

let Is block wide , So the variables declared in the block let Can only be used in this block .


use let The variable declared by keyword cannot be redeclared. It will throw such an error


let Variables can be updated within their scope like this



Use const Variables that hold constant value declarations .const Declaration and let The statement has some similarities . And let The statement is the same ,const Declarations can only be accessed within the block in which they are declared .


But with const Declared variables can neither be redeclared nor reassigned




I hope this article can help you understand varlet and const The difference between , Thank you for your patience , If articles and notes can give you a little help or inspiration , Please don't be stingy with your Star and Fork, Articles are updated continuously , Your affirmation is my biggest driving force

copyright notice
author[wscats],Please bring the original link to reprint, thank you.

Random recommended