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();
....
}
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.
let declares a variable in its current block scope. After that, we can change the value as often as we need.
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).
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();
....
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With