Reassign javascript with let

Are there differences between the two methods described below? Which one should be used, why?

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

and

let test;
while (true) {
    test = getValue();
    ....
}
+6
source share
7 answers

let with a block region , which means that it will exist only in a block {...}.

You should use this form (note that it is letnot required here if you do not change the value within the same block), if you use only testinside this block, and not (and not outside).

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

You should use this form if you need to access testdue to the loop while.

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

while, :

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

+4

, :

  • test ; test, . , (, , , , ).
  • () test ; , test .

, ?

. test , , ; , .

+3

, , while. .

+2

while, while.

+2

, .

  • , ​​ .

  • , .

+1

let - - , . , , let , undefined.

while (true) {
    let test = getValue();
    console.log(test); // => some value...
    ....
}
console.log(test); // => undefined

test while ( ), while:

let test;
while (true) {
    test = getValue();
    console.log(test); // => some value...
    ....
}
console.log(test); // => still some value...

, let while , :

let test = 5;
while (true) {
    let test = 4;
    console.log(test); // => 4
    ....
}
console.log(test); // => 4, not 5

, .

, 😂

0

All Articles