Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reassign javascript with let

Are there any differences between the two ways described below? Which one should I use any why?

while (true) {
    let test = getValue();
    ....
}

And

let test;
while (true) {
    test = getValue();
    ....
}
like image 816
sleepless_in_seattle Avatar asked Dec 11 '17 10:12

sleepless_in_seattle


People also ask

Should I use Let instead of VAR in JavaScript?

As a general rule, you should always declare variables with const, if you realize that the value of the variable needs to change, go back and change it to let. Use let when you know that the value of a variable will change. Use const for every other variable. Do not use var.

Can I change value of LET?

let declares a variable in its current block scope. After that, we can change the value as often as we need.

Can I Redeclare let and const variables?

Constants are block-scoped, much like variables declared using the let keyword. The value of a constant can't be changed through reassignment (i.e. by using the assignment operator), and it can't be redeclared (i.e. through a variable declaration).


2 Answers

let is block-scoped that means it will only exist within a {...} block.

You should use this form (note that here let is not necessary if you don't modify the value within the same block) if you only use test within that while block (and not outside).

while (true) {
    const test = getValue();
    ....
}

You should use this form if you need to access test from outside the while loop.

let test;
while (true) {
    test = getValue();
    ....
}
like image 195
klugjo Avatar answered Nov 02 '22 10:11

klugjo


If you use test variable outside your while loop, go with the second:

let test;
while (true) {
    test = getValue();
    ....
}
if (test) { ... }   // <--- Use test outside the while loop

Otherwise, the first one is better

like image 26
Faly Avatar answered Nov 02 '22 12:11

Faly