Explain the variables in JavaScript – Cloud CVIT.

The finalization of ES6 in 2015 introduced new ways to define JavaScript variants. Of let While the keyword creates a blocked scooped variable const Specifies a non-variable value. This is how these modern variable types differ from the classic. var.


Before ES6, var Your only option was to specify a variable. You can freely change the values ​​of the variables created. var. You can re-declare the variable yourself.

var demo = "first value";
var demo = "second value";
demo = "third value";
example = "this throws an error - variable not declared";

Using var Creates a variable for the current function. If you use it outside of a function, the resulting variable will spread globally.

The “scope” of the variable specifies where it can be used. The function scoped variable can be obtained by the code in the function that defines it. A global variable is accessible in your code.

var myGlobal = "global";
function testA() {
    var myFunctionScope = "testA";
function testB() {
    myGlobal = "overwritten!";
   // console.log(myFunctionScope);          // ERROR

In this example, the difference between globally scoped and function scoped variables is shown. myGlobal Can be read (and written) by both. testA And testB. myFunctionScope Only stated in testA, You testB Throws an error when trying to access it. Here is what the result will be:




Value of myFunctionScope Each function is stored separately. Value of myGlobal When both functions are updated testB Overwrite it.

let’s go.

new. let Is a modern alternative to keywords. var. You can often adopt. let All the places where you used to write. var. There are important differences to note though.

The most prominent. let The feature is its scope. Variables are added to individual code blocks instead of whole functions. In JavaScript, a block is a piece of code wrapped in a curved bracket. each one. let The variable is only accessible to the code within its block.

function letTest(x) {
    let demo = "hello world";
    if (x > 10) {
        let y = 9000;
        demo = "foobar";
    console.log(demo);  // "foobar"
    console.log(y);     // ERROR

In this example, if The statement creates a new code block. Blocks inherit the scope of their parent block so demo Variable is available. Of y The variable is scoped. if The statement is trying to access. y outside of if Block results in an indefinite variable error.

Such as var, Variables created with let Their values ​​may change at any time. Although they cannot be re-announced using. let Twice with the same name in the same block will cause error.

let demo = "test";
demo = "example";
let demo = "test";      // ERROR

An exception occurs when a variable in a household circle is re-declared. Block level scoping rules mean it’s allowed – you end up with two. Separate Variables that have the same identifier.

let foo = "bar";
if (true) {
    let foo = "foobar";

The above example will come up. foobar bar. Of foo The variable has been re-declared if Block, without affecting. foo External scope variable. You lose the ability to refer to external variables from within the internal block.


Of const The keyword was another ES6 addition. It’s like a block scope. let. const Short for “permanent” and used for unchanging values ​​that will never change. Trying to update the value of a. const The variable will always result in an error.

const foo = "bar";
const foo = "foobar";   // ERROR

As a result, you always have to get started. const It is not permissible to define variables a with value. const And set the price later.

let demoLet;                    // OK
var demoVar;                    // OK
const demoConst;                // ERROR
const demoConst = "value";      // OK

Technically, const Does not specify constant value. It actually creates one. Permanent reference To a value. The effect is that you can still update the properties of the items assigned to a. const. Mistakes happen when you use const To the left of an assignment itself.

Which variable type should I use?

Should adopt let For the most general purposes in your JavaScript code. Block level scoping and prohibited recalculation help catch errors and avoid unintentional overrights.

Using let Variable prevents “leakage” where variables can be accessed in circles that are not intended. A classic example is the repetition in loops:

for (var i = 0; i <= 10; i++) {
    // do something

That will be the result. 10 Exiting the console using. let Will expel instead undefined, As i The variable will be inaccessible from the outside. if. Scope This is usually the desired result in this type of scenario.

Also show the dangers of loops. var Reassignment:

for (var i = 0; i <= 10; i++) {
    setTimeout(() => console.log(i), 1000);

At first glance, this code looks like this. Should Exclude numbers 1 to 10, instead, 10 You will be logged in ten times setTimeout() Unstable and i Callback is lexically bound. As var i Being used in a loop, i The variable gets a new value for each iteration. When the timer callback runs, all ten repetitions are already completed and. i Will always settle the final price – 10, in this case.

Using let i Will declare a instead. New Is called a variable i For each repetition of the loop. Each variable will retain its value after its iteration is completed, resulting in the expected logout.

When not in use.

There are scenarios where you should not use. let. You should use const When you create a variable that you know will never change. Bundlers and static analysis tools will be able to alert you if you inadvertently try to reassign it.

It is usually a good idea to keep the variables unchanged wherever possible. It helps eliminate bugs caused by unintentional overrights. Using const Indicating your intent in the code base also makes it clear that the value will not change.

ES6 features such as. let And const There is now global support for modern browsers. Some older browsers offer them without full ES6 support, especially Internet Explorer 11. You don’t have to worry about whether they will be available unless you are targeting too many historical platforms. Use let And const Keep your code clean and minimize the risk of hidden bugs.

Leave a Reply

Your email address will not be published.