6

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.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
Robert Hönig
  • 645
  • 1
  • 8
  • 19
  • This looks like a duplicate question from https://stackoverflow.com/questions/5113374/javascript-check-if-variable-exists-is-defined-initialized/6509422?r=SearchResults&s=2|163.7775#6509422 – Klaus Heinrich Aug 01 '19 at 16:54
  • Semi-related, since you look to be typing into the console: https://stackoverflow.com/questions/54979906/is-there-any-difference-between-declared-and-defined-variable – CertainPerformance Dec 03 '21 at 05:00

2 Answers2

5

They 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.

Alexandre Beaudet
  • 2,774
  • 2
  • 20
  • 29
2

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.

KALALEX
  • 430
  • 1
  • 5
  • 19