Yes. You can declare a variable without initializing it:
var x; // or ... let y;
Or you can initialize it at the same time:
var x = 1; // or ... let y = 2;
If you don’t initialize it, then it will be
undefined until changed. Changing it later is not initialization. Note that
const variables must always be initialized because they cannot be changed/reassigned later.
So if I am following you well, me declaring a variable on a line and assigning it to a value on a different line, the initial value of the variable will be automatically set to (undefined) on the same line I declared it and the line of assigning is just changing the initial value ?
let x; // <-- undefined after this line x = 1; // <-- was undefined, not it is defined
Yes. Every variable has to have a value. JS has the
undefined value for things that are not initialized. True, you can also change it to
let x = 1; // <-- initialized x = undefined; // <-- changed to undefined
You can do that - in JS,
undefined is a value like any other. But many of us would avoid that, reserving
undefined for things that were not initialized and using
null when we want a variable to not have a set value. Most languages (afaik) don’t even have
This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.