Is there a difference between "declaring an empty variable" and "not assigning a value" to a variable?

InJavaScript. is there a difference between declaring an empty variable and not assigning a value to a variable?

For example, Is there a difference between this…

let variable; // this variable was only declared but not assigned any value.

AND this

let variable = ""; // this variable was declared and assigned an empty value.

If you console.log both of these the answer will become clear :slight_smile: They’re both useful for different situations.


Okay! I did that.

When I declare a variable and assign it to an empty variable or empty string (""), then log it to the console, nothing is printed out. e.g

let bob = "";

console.log(bob);  // this prints nothing

But when I only declare a variable without assigning it, then log it, it prints “undefined” .e.g.

let baab;

console.log(baab);  // this prints undefined

What different situations are each of them meant for?

undefined is just the default value JS gives to everything that has not been explicitly given a value (like an unassigned variable). Generally, one would never want undefined to be stored in a variable, but it could come up useful if you were checking if a form had been answered, or something like that.

An empty variable might be used to build strings up (like concatenating every letter of a word to a once empty string). Empty variables can also be empty arrays ([]), and so forth.

I hope this helps!

1 Like