In Javascript, I can do
> var foo;
< undefined
> foo;
< undefined
This suggests that in Javascript, declared uninitialized variables are always undefined. But are they? Or could they, like in C, take on a random garbage value?
MDN's var docs weren't of help.
In Javascript, I can do
> var foo;
< undefined
> foo;
< undefined
This suggests that in Javascript, declared uninitialized variables are always undefined. But are they? Or could they, like in C, take on a random garbage value?
MDN's var docs weren't of help.
Share Improve this question edited Dec 3, 2021 at 5:01 CertainPerformance 371k55 gold badges350 silver badges356 bronze badges asked Jun 1, 2018 at 9:51 Robert HönigRobert Hönig 6831 gold badge9 silver badges19 bronze badges 2- This looks like a duplicate question from stackoverflow./questions/5113374/… – Klaus Heinrich Commented Aug 1, 2019 at 16:54
- Semi-related, since you look to be typing into the console: stackoverflow./questions/54979906/… – CertainPerformance Commented Dec 3, 2021 at 5:00
2 Answers
Reset to default 5They won't take a random garbage value, if no value is assigned, it will stay "undefined".
That gives the possibility to check if an object as yet been assigned : From MDN :
function test(t) {
if (t === undefined) {
return 'Undefined value!';
}
return t;
}
var x;
console.log(test(x));
// expected output: "Undefined value!
A variable that has not been assigned a value is of type undefined. A method or statement also returns undefined if the variable that is being evaluated does not have an assigned value. A function returns undefined if a value was not returned.
In javascript any property that has not been assigned a value it is assigned as undefined
. There are two things you need to seperate to understand it, there are two Undefined "things" from ECMA-262 Standard:
- 4.3.9 undefined value
- 4.3.10 Undefined type
Undefined type
=> type whose sole value is the undefined value
undefined value
=> primitive value used when a variable has not been assigned a value
So in your case the variable is initialized and it has been assigned the undefined
value.
Also a premitive value in javascript is defined as:
4.3.2 primitive value
member of one of the types Undefined, Null, Boolean, Number, or String as defined in Clause 8
NOTE: A primitive value is a datum that is represented directly at the lowest level of the language implementation.