Not declaring a value


#1

Why would you, when using let or var, declare a variable and not assign it a value?

https://www.codecademy.com/courses/learn-javascript-introduction/lessons/variables/exercises/let?action=resume_content_item&course_redirect=introduction-to-javascript


#2

Mainly it’s so the variable gets hoisted, whether it is defined or not. We may be defining and redefining the variable in a loop where var is not an option.

var b;
do {
  b = Math.random();
} while (b !== 0);

Above, b will take on anywhere from one to many new values. var would have no place inside that loop. We only declare a variable once, whereas we may define it many times.

As for let, that is a block scope declaration. I’m of the opinion that it does not belong in global scope, only in block scope, mainly for loops, or other instances where we don’t want the variables to leak out of their block scope.

var i = 42;
for (let i = 0; i < 10; i++) {
    console.log(i);    // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
}
// inside the block, `i` finishes up with value, `10`
console.log(i);    // 42

for (var j = 0; j < 10; j++) {

}
console.log(j);    // 10

The variable j is allowed to leak out of the block.

Bottom line, use var in global or function scope, and let in block scope.