1624

I want to know what the difference is between null and undefined in JavaScript.

  • 31
    I always thought: `null` is you set it to empty, `undefined` it's empty because it has not been set. Or `null` is empty on purpose, while `undefined` is still empty. Basically it shows intent. – Muhammad Umer Sep 12 '14 at 16:20
  • 1
    See also [Why is null an object and what's the difference between null and undefined?](http://stackoverflow.com/q/801032/1048572) – Bergi Sep 24 '14 at 14:29
  • 60
    NaN. See for yourself. console.log(null-undefined). The difference between null and undefined is NaN. (Note that this is an attempt at humour, before you flame me for misunderstanding the question.) – Ivan Apr 22 '16 at 10:44
  • Know about undefined and it's relationship with scope https://codepen.io/grumpy/post/undefined-scope-in-javascript – AL-zami Sep 19 '17 at 16:53
  • With `null` you use it generally to erase the contents of a variable, with `undefined` it generally comes with input when there hasn't been set a value yet. – Robert Nov 18 '17 at 17:42
  • See also [is-it-better-to-return undefined or null?](https://stackoverflow.com/questions/37980559/is-it-better-to-return-undefined-or-null-from-a-javascript-function?noredirect=1&lq=1) – Michael Freidgeim Jan 08 '22 at 12:42
  • `null` means the variable was declared, but have a null value. A null is a special value like any other possible value. `undefined` means that the variable you're trying to read/reference did not was not assigned with any value. – Jone Polvora Mar 22 '22 at 04:38
  • 1
    As a side note, it's worth noting that while the originator of `null` called it his "billion-dollar mistake" ([Tony Hoare](https://qconlondon.com/london-2009/qconlondon.com/london-2009/speaker/Tony+Hoare.html)), JavaScript happily decided to multiply that mistake by 2. Happy debugging! – Chris Collett Jul 18 '22 at 15:32
  • There is a lint rule explaining that undefined is preferred. See palantir.github.io/tslint/rules/no-null-keyword – Michael Freidgeim Jul 09 '23 at 08:36
  • The TypeScript Coding guidelines recommend using only undefined and discouraging the use of null values (see https://github.com/Microsoft/TypeScript/wiki/Coding-guidelines#null-and-undefined) – Michael Freidgeim Jul 09 '23 at 08:45

39 Answers39

1538

undefined means a variable has been declared but has not yet been assigned a value :

var testVar;
console.log(testVar); //shows undefined
console.log(typeof testVar); //shows undefined

null is an assignment value. It can be assigned to a variable as a representation of no value :

var testVar = null;
console.log(testVar); //shows null
console.log(typeof testVar); //shows object

From the preceding examples, it is clear that undefined and null are two distinct types: undefined is a type itself (undefined) while null is an object.

Proof :

console.log(null === undefined) // false (not the same type)
console.log(null == undefined) // true (but the "same value")
console.log(null === null) // true (both type and value are the same)

and

null = 'value' // Uncaught SyntaxError: invalid assignment left-hand side
undefined = 'value' // 'value'
Samathingamajig
  • 11,839
  • 3
  • 12
  • 34
sebastian
  • 16,470
  • 1
  • 22
  • 18
  • 442
    Quote from the book Professional JS For Web Developers (Wrox): "You may wonder why the typeof operator returns 'object' for a value that is null. This was actually an error in the original JavaScript implementation that was then copied in ECMAScript. Today, it is rationalized that null is considered a placeholder for an object, even though, technically, it is a primitive value." – Captain Sensible Nov 03 '11 at 14:54
  • 51
    the variable might as well not be defined at all. for example: console.log(typeof(abc)); undefined – Nir O. May 08 '12 at 21:12
  • 27
    The comment from Nir O. is very important. If I want to have a variable that has no value in the beginning, I write "... = null", eg "myvar = null". This way - when I mistype "if (myxar == null) {...}" - the if block is not executed. I don't have this advantage with undefined: myvar = undefined; myvar = 4; if (typeof myxar == "undefined") { ...} – Wolfgang Adamec Sep 26 '12 at 07:29
  • 18
    @Wolfgang Adamec, error-free programming is not about mistypes. – Jorge Fuentes González Mar 15 '13 at 17:12
  • 17
    so basically null value means a variable has been explicitly set as (no value = null) or has been initialized and defined to be nothing. While undefined means. it was probably never initialized or if it was it was never defined. – Muhammad Umer Aug 10 '13 at 11:06
  • 1
    Why does null==undefined return true? – khunshan Oct 29 '13 at 09:21
  • 1
    @khunshan pretty bizaare that one but if you use === (the proper equality operator) then they are not. This is because the types are different null is an object & undefined is undefined. See this [link](http://stackoverflow.com/questions/359494/does-it-matter-which-equals-operator-vs-i-use-in-javascript-comparisons) for more info – JonnyRaa Feb 12 '14 at 12:40
  • 8
    **undefined means a variable has been declared but has not yet been assigned** not really.. `var a = {};` then `a.abc === undefined is true`..but if you do `a.n=undefined;` now a is {a:undefined}... so regardless if var was declared or not it was undefined !!!! – Muhammad Umer Mar 05 '15 at 17:10
  • 5
    From the preceding examples, it is clear that there is no point of having undefined and null as separate concepts. – merrr May 07 '15 at 11:42
  • 1
    @merrr: There are cases when it makes perfect sense to test for undefined instead of null, for example: If you make use of associative arrays which serve as dynamic containers for some type of data...you may not know which index exists, so you have to find out first: if (typeof niceArray['index1']['option_xy'] !== 'undefined') { ... } typeof will return 'undefined' even if the identifier has never been declared...pretty cool...and you cannot test for null instead, because Javascript will throw a reference error. – sebastian Jun 09 '15 at 21:40
  • 1
    @JorgeFuentesGonzález I agree. Don't program according to how often you hit the wrong key on the keyboard. Well said. – dudewad Oct 08 '15 at 16:54
  • @all, I think a real life example is better, i have declared a variable node with var node. If this variable has no value node == null and node == undefined both are true. If i want to know if this variable is declared i use node === undefined and that result is false. These are the most common practices for conditions. Some will use node == undefined also for variables that need to be declared and i think thats bad practice. The null gives information about the variable and says i need to be declared. Thats usefull information for the developer. – Herman Van Der Blom Mar 23 '16 at 10:43
  • 1
    @HermanVanDerBlom That's incorrect though. checking for `node === undefined` while `node` hasn't been declared will throw a `ReferenceError` because `node` is indeed (pun intended) undefined. You probably mean to check whether `typeof node === "undefined"` – user777 Aug 02 '16 at 13:20
  • 4
    It's probably also worth mentioning that since this answer was written, ES6 has introduced default function parameters, which work differently for `null` and `undefined`. Wtih `function foo(bar = 'default') { return bar; }`, then `foo(null) === null` but `foo() === foo(undefined) === 'default'`. React props also work similarly, so there are more reasons now than before to intentionally pass `undefined` rather than `null`. – 0x24a537r9 Feb 15 '18 at 02:47
  • 1
    Also, null is not object, typeof operator return object which is a bug in JS but yet null is a primitive data type same as undefined or Boolean – Junaid Sarwar Jan 10 '19 at 15:51
  • 2
    FWIW, @user3597009 - `null` is a *value*, not a *type*. IMHO, its arbitrary what *type* JS says `null` is; its not particularly meaningful to talk about the "type of null" - in any language. As you know, its a pre-defined value that you assign to a variable so that later you can ask "does this variable have value null?" E.g. `x = null;` ... `if (x === null) ...`. It would not be meaningful to ask "does this variable have *type* null?" – ToolmakerSteve Oct 02 '19 at 14:05
  • `x = {}` and then `x["hede"] === undefined` is `true` so "undefined means a variable has been declared but has not yet been assigned a value" <- this is just confusing and probably wrong. – nurettin Mar 29 '21 at 15:06
  • If something is undefined, it means it has been unassigned. If something is null, it means it has been assigned a null value. – Yellowjacket11 Sep 10 '21 at 21:39
  • @nurettin In that example, basically every imaginable object property is "implicitly declared". This is consistent with other instances of handling "undeclared" properties, so from that perspective the statement remains correct. – Egor Hans Nov 15 '21 at 12:27
  • @user777 The way I read this, the problem is more saying "declared" where the intention appears to be "initialized". – Egor Hans Nov 15 '21 at 12:28
  • Why is this answer marked as correct? You can assign undefined to a variable “let foo = undefined;” – neiker Nov 11 '22 at 19:11
  • I vote for the elimination or either one. In both case there is no value and it just gives headaches in test cases. There is data or there is not. Intent to leave a variable empty should not be at the cost of overall confusion and complexity among us developers. I cannot see a single case where null would be useful. – scavenger Nov 12 '22 at 17:42
677

The difference can be explained with toilet tissue holder:

  • A non-zero value is like a holder with roll of toilet tissue and there's tissue still on the tube.

  • A zero value is like a holder with an empty toilet tissue tube.

  • A null value is like a holder that doesn't even have a tissue tube.

  • An undefined value is similar to the holder itself being missing.

BSMP
  • 4,596
  • 8
  • 33
  • 44
Sebastian Norr
  • 7,686
  • 2
  • 12
  • 17
  • 17
    Could you include the attribution for the image source, please? – Vega Feb 17 '20 at 14:46
  • 11
    @Vega Unfortunately no, I don't remember where I got it from other than somewhere on imgur.com and that's probably from a repost, not the ORIGINAL source. Not even the embedded link here gives any clue of who posted this version, so I can't really search for it either. – Sebastian Norr Feb 18 '20 at 01:38
  • 50
    @SebastianNorr "I don't remember where I got it from other than somewhere on imgur.com" -> so is it `undefined` or `null` in that case? – Erowlin Oct 27 '20 at 17:09
  • 100
    `let toiletPaperIn2020 = undefined;` – Rain Feb 25 '21 at 21:04
  • @Erowlin It is closer to being `null` because I remember that the image comes from imgur, so it isn't totally unknown. The `undefined` would be more like "I have no idea where it came from". – Sebastian Norr Sep 29 '21 at 11:22
  • @hakre is this what you mean? https://i.stack.imgur.com/T9M2J.png As I have already said before, I don't have the information anymore where it came from, not even editing the post shows it to me, other than that the image comes from imgur.com This link is what I get when I right click & choose "Copy link address", I still don't know who originally uploaded this image or the full url to it. – Sebastian Norr Oct 29 '21 at 21:28
  • This is probably a problem with the Stackoverflow UI when uploading images and not having the user to certify whether a) it is the users original work that is contributed under license or b) to annotate the upload with the appropriate license information. Could be Meta material. – hakre Oct 29 '21 at 22:31
  • I disagree with the toilet picture, it actually gives a bad representation of the problem. – Stefaan Vandevelde Dec 16 '21 at 17:27
  • 10
    `undefined` cannot be an empty wall if the holder represents the variable. In this representation, `undefined` is an empty holder while null is an empty holder with post-it note `empty`. (so the unfortunate user knows it's useless to ask the cleaning lady for toilet paper). That also show why many developers are confused : should I put an `empty` post-it note on an uninitialized variable or will everyone understand that `empty` means *empty* ? e.g. is the lack op toilet paper intentional or not ? – Stefaan Vandevelde Dec 16 '21 at 17:37
  • 1
    And the RAM is the bathroom – mercury May 01 '22 at 18:23
  • 1
    @mercury - "And the RAM is the bathroom" - wouldn't that be the hard disk? RAM should be the cleaning lady's hands. – Claim May 18 '22 at 11:45
89

I picked this from here

The undefined value is a primitive value used when a variable has not been assigned a value.

The null value is a primitive value that represents the null, empty, or non-existent reference.

When you declare a variable through var and do not give it a value, it will have the value undefined. By itself, if you try to WScript.Echo() or alert() this value, you won't see anything. However, if you append a blank string to it then suddenly it'll appear:

var s;
WScript.Echo(s);
WScript.Echo("" + s);

You can declare a variable, set it to null, and the behavior is identical except that you'll see "null" printed out versus "undefined". This is a small difference indeed.

You can even compare a variable that is undefined to null or vice versa, and the condition will be true:

undefined == null
null == undefined

They are, however, considered to be two different types. While undefined is a type all to itself, null is considered to be a special object value. You can see this by using typeof() which returns a string representing the general type of a variable:

var a;
WScript.Echo(typeof(a));
var b = null;
WScript.Echo(typeof(b));

Running the above script will result in the following output:

undefined
object

Regardless of their being different types, they will still act the same if you try to access a member of either one, e.g. that is to say they will throw an exception. With WSH you will see the dreaded "'varname' is null or not an object" and that's if you're lucky (but that's a topic for another article).

You can explicitely set a variable to be undefined, but I highly advise against it. I recommend only setting variables to null and leave undefined the value for things you forgot to set. At the same time, I really encourage you to always set every variable. JavaScript has a scope chain different than that of C-style languages, easily confusing even veteran programmers, and setting variables to null is the best way to prevent bugs based on it.

Another instance where you will see undefined pop up is when using the delete operator. Those of us from a C-world might incorrectly interpret this as destroying an object, but it is not so. What this operation does is remove a subscript from an Array or a member from an Object. For Arrays it does not effect the length, but rather that subscript is now considered undefined.

var a = [ 'a', 'b', 'c' ];
delete a[1];
for (var i = 0; i < a.length; i++)
WScript.Echo((i+".) "+a[i]);

The result of the above script is:

0.) a
1.) undefined
2.) c

You will also get undefined returned when reading a subscript or member that never existed.

The difference between null and undefined is: JavaScript will never set anything to null, that's usually what we do. While we can set variables to undefined, we prefer null because it's not something that is ever done for us. When you're debugging this means that anything set to null is of your own doing and not JavaScript. Beyond that, these two special values are nearly equivalent.

Victor2748
  • 4,149
  • 13
  • 52
  • 89
ayush
  • 14,350
  • 11
  • 53
  • 100
  • 9
    Really a good answer. But just to point out, when u checked "undefined == null" the type checking was not strict. Hence it returned "true". If you check "undefined === null", it would return false. – wOlVeRiNe Feb 17 '14 at 09:06
  • 4
    It's worth noting that while this comment was true in '11, with the advent of optional function params, emergence of type-checking systems like Flow, and pervasiveness of React (all of which treat undefined and null very differently), the old wisdom of generally using null rather than undefined no longer holds so strictly. undefined is actually preferable to null in many cases where you want to explicitly use the default value (e.g. for an optional param or optional React prop). – 0x24a537r9 Feb 15 '18 at 02:36
  • From https://blog.devgenius.io/typescript-when-to-use-null-undefined-or-empty-array-d45244ffc565 “in my point of view, better not to use null at all and prefer undefined.” – Michael Freidgeim Jan 08 '22 at 12:56
64

Please read the following carefully. It should remove all your doubts regarding the difference between null and undefined in JavaScript. Also, you can use the utility function at the end of this answer to get more specific types of variables.

In JavaScript we can have the following types of variables:

  1. Undeclared Variables
  2. Declared but Unassigned Variables
  3. Variables assigned with literal undefined
  4. Variables assigned with literal null
  5. Variables assigned with anything other than undefined or null

The following explains each of these cases one by one:

  1. Undeclared Variables

    • Can only be checked with the typeof operator which returns string 'undefined'
    • Cannot be checked with the loose equality operator ( == undefined ), let alone the strict equality operator ( === undefined ),
      as well as if-statements and ternary operators ( ? : ) — these throw Reference Errors
  2. Declared but Unassigned Variables

    • typeof returns string 'undefined'
    • == check with null returns true
    • == check with undefined returns true
    • === check with null returns false
    • === check with undefined returns true
    • Is falsy to if-statements and ternary operators ( ? : )
  3. Variables assigned with literal undefined
    These variables are treated exactly the same as Declared But Unassigned Variables.

  4. Variables assigned with literal null

    • typeof returns string 'object'
    • == check with null returns true
    • == check with undefined returns true
    • === check with null returns true
    • === check with undefined returns false
    • Is falsy to if-statements and ternary operators ( ? : )
  5. Variables assigned with anything other than undefined or null

    • typeof returns one of the following strings: 'bigint', 'boolean', 'function', 'number', 'object', 'string', 'symbol'

Following provides the algorithm for correct type checking of a variable:

  1. Get the typeof our variable and return it if it isn't 'object'
  2. Check for null, as typeof null returns 'object' as well
  3. Evaluate Object.prototype.toString.call(o) with a switch statement to return a more precise value. Object's toString method returns strings that look like '[object ConstructorName]' for native/host objects. For all other objects (user-defined objects), it always returns '[object Object]'
  4. If that last part is the case (the stringified version of the variable being '[object Object]') and the parameter returnConstructorBoolean is true, it will try to get the name of the constructor by toString-ing it and extracting the name from there. If the constructor can't be reached, 'object' is returned as usual. If the string doesn't contain its name, 'anonymous' is returned

(supports all types up to ECMAScript 2020)

function TypeOf(o, returnConstructorBoolean) {
  const type = typeof o

  if (type !== 'object') return type
  if (o === null)        return 'null'

  const toString = Object.prototype.toString.call(o)

  switch (toString) {
    // Value types: 6
    case '[object BigInt]':            return 'bigint'
    case '[object Boolean]':           return 'boolean'
    case '[object Date]':              return 'date'
    case '[object Number]':            return 'number'
    case '[object String]':            return 'string'
    case '[object Symbol]':            return 'symbol'

    // Error types: 7
    case '[object Error]':             return 'error'
    case '[object EvalError]':         return 'evalerror'
    case '[object RangeError]':        return 'rangeerror'
    case '[object ReferenceError]':    return 'referenceerror'
    case '[object SyntaxError]':       return 'syntaxerror'
    case '[object TypeError]':         return 'typeerror'
    case '[object URIError]':          return 'urierror'

    // Indexed Collection and Helper types: 13
    case '[object Array]':             return 'array'
    case '[object Int8Array]':         return 'int8array'
    case '[object Uint8Array]':        return 'uint8array'
    case '[object Uint8ClampedArray]': return 'uint8clampedarray'
    case '[object Int16Array]':        return 'int16array'
    case '[object Uint16Array]':       return 'uint16array'
    case '[object Int32Array]':        return 'int32array'
    case '[object Uint32Array]':       return 'uint32array'
    case '[object Float32Array]':      return 'float32array'
    case '[object Float64Array]':      return 'float64array'
    case '[object ArrayBuffer]':       return 'arraybuffer'
    case '[object SharedArrayBuffer]': return 'sharedarraybuffer'
    case '[object DataView]':          return 'dataview'

    // Keyed Collection types: 2
    case '[object Map]':               return 'map'
    case '[object WeakMap]':           return 'weakmap'

    // Set types: 2
    case '[object Set]':               return 'set'
    case '[object WeakSet]':           return 'weakset'

    // Operation types: 3
    case '[object RegExp]':            return 'regexp'
    case '[object Proxy]':             return 'proxy'
    case '[object Promise]':           return 'promise'

    // Plain objects
    case '[object Object]':
      if (!returnConstructorBoolean)
        return type

      const _prototype = Object.getPrototypeOf(o)
      if (!_prototype)              
        return type

      const _constructor = _prototype.constructor
      if (!_constructor)            
        return type

      const matches = Function.prototype.toString.call(_constructor).match(/^function\s*([^\s(]+)/)
        return matches ? matches[1] : 'anonymous'

    default: return toString.split(' ')[1].slice(0, -1)
  }
}
Gust van de Wal
  • 5,211
  • 1
  • 24
  • 48
Arup Hore
  • 1,509
  • 15
  • 9
43

null is a special keyword that indicates an absence of value.

think about it as a value, like:

  • "foo" is string,
  • true is boolean ,
  • 1234 is number,
  • null is undefined.

undefined property indicates that a variable has not been assigned a value including null too . Like

var foo;

defined empty variable is null of datatype undefined


Both of them are representing a value of a variable with no value

AND null doesn't represent a string that has no value - empty string-


Like

var a = ''; 
console.log(typeof a); // string 
console.log(a == null); //false 
console.log(a == undefined); // false 

Now if

var a;
console.log(a == null); //true
console.log(a == undefined); //true 

BUT

var a; 
console.log(a === null); //false 
console.log(a === undefined); // true

SO each one has it own way to use

undefined use it to compare the variable data type

null use it to empty a value of a variable

var a = 'javascript';
a = null ; // will change the type of variable "a" from string to object 
Dovlet Mamenov
  • 581
  • 1
  • 7
  • 20
Mina Gabriel
  • 23,150
  • 26
  • 96
  • 124
  • 2
    null is also a data type. Both undefined and null are data types and values – danwellman Jun 21 '14 at 14:38
  • 15
    `null` Absolutely IS a data type: msdn.microsoft.com/en-us/library/ie/7wkd9z69(v=vs.94).aspx . The fact that `typeof null` returns `object` is a well known and documented bug in early versions of ECMAScript that has remained for backwards-compatibility. The link that *you* actually posted in your comment says halfway down the page "typeof null // object (bug in ECMAScript, should be null)" ! So please, show some search effort before commenting on down-votes – danwellman Jun 25 '14 at 18:33
  • 2
    Definitions contradict: "absence of value" vs "has not been assigned a value". Isn't it the same? – Zon Jan 26 '16 at 10:35
  • 4
    I disagree with this answer. Null and undefined are both distinct datatypes. null is of type null and undefined is of type undefined. Only when using a truthy operator (==) may we see that javascript says its true but a strict comparison (===) is produces a false. – alaboudi Jan 03 '17 at 18:51
  • 1
    To this day _“null is undefined”_ remains wrong. – Sebastian Simon Aug 09 '21 at 11:33
27

null: absence of value for a variable; undefined: absence of variable itself;

..where variable is a symbolic name associated with a value.

JS could be kind enough to implicitly init newly declared variables with null, but it does not.

rjh
  • 49,276
  • 4
  • 56
  • 63
Dmitry Sychov
  • 237
  • 7
  • 16
  • 34
    `var a = {}; a.n = undefined;' then ..`a.hasOwnProperty('n') == true` ...so saying **absence of variable itself** isn't correct anymore – Muhammad Umer Mar 05 '15 at 17:19
  • That's a really pithy definition, but it's not really accurate - for the reason you give. A defined variable starts with the value `undefined`. – Steve Bennett Jun 23 '21 at 03:14
  • Even after these many years of this answer being posted, I think I agree with this answer. The intent of `undefined` is that the variable doesn't exist and the intent of `null` is that variable exists but has no value. Peeps are going into the implementation-specific details by checking `typeof` variables but missed to understand one of the most powerful term of CS called "abstraction". – Aman Godara Nov 29 '21 at 07:40
17

You might consider undefined to represent a system-level, unexpected, or error-like absence of value and null to represent program-level, normal, or expected absence of value.

via JavaScript:The Definitive Guide

Kevin
  • 795
  • 2
  • 9
  • 21
17

The best way to understand the difference is to first clear your mind of the inner workings of JavaScript and just understand the differences in meaning between:

let supervisor = "None"
    // I have a supervisor named "None"

let supervisor = null
    // I do NOT have a supervisor. It is a FACT that I do not.

let supervisor = undefined
    // I may or may not have a supervisor. I either don't know
    // if I do or not, or I am choosing not to tell you. It is
    // irrelevant or none of your business.

There is a difference in meaning between these three cases, and JavaScript distinguishes the latter two cases with two different values, null and undefined. You are free to use those values explicitly to convey those meanings.

So what are some of the JavaScript-specific issues that arise due to this philosophical basis?

  1. A declared variable without an initializer gets the value undefined because you never said anything about the what the intended value was.

    let supervisor;
    assert(supervisor === undefined);
    
  2. A property of an object that has never been set evaluates to undefined because no one ever said anything about that property.

    const dog = { name: 'Sparky', age: 2 };
    assert(dog.breed === undefined);
    
  3. null and undefined are "similar" to each other because Brendan Eich said so. But they are emphatically not equal to each other.

    assert(null == undefined);
    assert(null !== undefined);
    
  4. null and undefined thankfully have different types. null belongs to the type Null and undefined to the type Undefined. This is in the spec, but you would never know this because of the typeof weirdness which I will not repeat here.

  5. A function reaching the end of its body without an explicit return statement returns undefined since you don't know anything about what it returned.

By the way, there are other forms of "nothingness" in JavaScript (it's good to have studied Philosophy....)

  • NaN
  • Using a variable that has never been declared and receiving a ReferenceError
  • Using a let or const defined local variable in its temporal dead zone and receiving a ReferenceError
  • Empty cells in sparse arrays. Yes these are not even undefined although they compare === to undefined.

    $ node
    > const a = [1, undefined, 2]
    > const b = [1, , 2]
    > a
    [ 1, undefined, 2 ]
    > b
    [ 1, <1 empty item>, 2 ]
    
Ray Toal
  • 86,166
  • 18
  • 182
  • 232
  • Best answer! Most of the answers ignore the fact that you can **define the value of a variable as `undefined`**, like in the `let supervisor = undefined` case. – J. Bruni Mar 07 '20 at 14:47
  • Thank you, and yes, that misconception that something is `undefined` only if it has not been declared or has not yet been given a value is so rampant and it is really hard to get across to people (though I keep trying). So many people trash JavaScript for having both `null` and `undefined` but these values _do_ have completely distinct meanings and for the most part they work well with their intended meanings (IMHO of course). – Ray Toal Mar 08 '20 at 03:29
17

A lot of "technical" answers have been given, all of them mostly correct from the limited point of view of JS as a mere programming language.

However, I would like to add the following thoughts, especially when you're writing TypeScript code as part of a bigger project / (enterprise) application:

  • When talking with a Backend of some kind you'll most probably receive JSON
  • While some backends correctly avoid the use of "null" in their JSON (removing those properties), others do not
  • Now, while "null" may mean that the value is missing deliberately, more often it does not convey this meaning. Most databases use "null" just because they don't have an "undefined" type. But the meaning really just is "undefined".
  • Because of that, you can never know if a "null" value really means deliberate absence. Therefore "null" cannot really mean the deliberate choice of "missing value". It is undecidable in general.
  • As a consequence, semantically, "null" and "undefined" are exactly the same thing in practice.

Therefore, in an effort to harmonize things I'm strictly against using "null" and want to encourage you to stop using "null" in your code. It's far easier than you might think. Don't get me wrong. I'm not talking about not handling "null" values, only to avoid explicitly using them in your code. Put differently: your code should still be able to work with accidentally passed "null" values coming from outside your application, e.g. via a 3rd party lib like Angular, or a 3rd party backend.

Here are the guidelines that make it possible:

  • avoid direct undefined type guards (e.g. if (value === undefined) { ... }.
  • Instead, use indirect type guards (aka truthiness checks) e.g. if (value) { ... }
    • Whenever 0 or empty strings are meaningful, use either
      • an explicit helper method like Lodash's isNil
      • or include the meaningful value in the comparison (e.g. if (!value && value !== 0) { ... })
  • Consider using a lint rule that disallows the usage of null
NicBright
  • 7,289
  • 5
  • 18
  • 19
  • This is an interesting perspective, and I think it could be expanded; and that's why I'm just posting this comment. Now that C# has implemented non-nullable types, there's a kind of "progress", if you want to call it that, towards understanding something that I'd phrase like: if you request a database for a key that it doesn't have, then you return undefined, because the key is undefined; but if you request a key that it does have, you return null for any value that's not null — you don't return undefined there. So just wondering if fails are picking up on some trend or whatever you call it? – Steven Coco May 21 '22 at 15:28
  • 2
    I agree with this completely. It's more important to look at this in the context of the ecosystem, you generally cannot garuntee your datasource is differentiating between Unknown and Null in the same way that Javascript the programming language does. In fact this is rarely true. Therefore you cannot assume null is intentional for this reason you must treat them same. This is especially true when we are discussing a program that gets data from multiple sources or you don't have control of the structure of the datasource. Javascripts actual implementation is unimportant in this context. – jdmneon Jul 15 '22 at 01:20
  • 1
    Agree that `if (value)` is better than `if (value == null)`. But what would a function return instead of an object, when it encounters an error? I would think that `return null` is the obvious choice, but it's not clear what you're suggesting with *'stop using "null" in your code*' in this case. – Nagev Nov 10 '22 at 12:34
  • @Nagev: you need to decide whether you want to handle the error directly in the function or if you would like to have the caller handle it. The latter can be done easily by making your function actually throw an Error. The former can be done by either still returning an object of some kind (with maybe only defaults or empty or undefined properties). Alternatively you can just return `undefined` and make this a valid return value besides objects (e.g. think about TS signature `(): YourType | undefined`). The caller can then easily skip `undefined` via simple truthiness check `if (...) {}` – NicBright Dec 01 '22 at 10:20
  • They're all good options, thanks for clarifying. I guess it's a matter of preference (unless of course dictated by the code base or team conventions). Personally, I like throwing exceptions sparingly, as I find it annoying having to wrap everything in `try ... catch`. Returning a custom object can be overly complex in many cases. And the `if (...)` test works as well for `undefined` as it does for `null`, and since the latter is actually an object, `null` makes sense when an object is the return type. The function is saying: sorry, can't give you the object you want, here is `null` instead. – Nagev Dec 02 '22 at 09:53
  • And by the way, using a `null` object will often lead to an exception anyway, so if the intention is to handle it higher up, that also covers it. Although it has the disadvantage of not being a custom/specific exception. If that's desirable, for example handling each case differently, it's one case where I'd prefer to throw exceptions. – Nagev Dec 02 '22 at 10:01
  • I completely agree with the main sentiment of this post. The difference between `null` and `undefined` is just the opinion of the person who used it in the first place. Looking through some of the other answers here, it is clear that many people have different ideas about what each means. The only way of silencing those ambiguous opinions is to accept that, at a conceptual level, they are the same thing. As such, the safe way to check for both `null` and `undefined` is `if(value == null){...`. Airbnb ESLINT rules specifically make an exception to the "always use `===`" to allow for `== null`. – spender Dec 20 '22 at 11:07
15

null is a special value meaning "no value". null is a special object because typeof null returns 'object'.

On the other hand, undefined means that the variable has not been declared, or has not been given a value.

Richard H
  • 38,037
  • 37
  • 111
  • 138
  • 3
    It is important to note, that while `undefined` may mean that a variable has not been declared, but does not guarantee that. A variable can be declared as `var thing;` and it will be equal to `undefined`. – Yura Oct 17 '15 at 17:48
13

null and undefined are two distinct object types which have the following in common:

  • both can only hold a single value, null and undefined respectively;
  • both have no properties or methods and an attempt to read any properties of either will result in a run-time error (for all other objects, you get value undefined if you try to read a non-existent property);
  • values null and undefined are considered equal to each other and to nothing else by == and != operators.

The similarities however end here. For once, there is a fundamental difference in the way how keywords null and undefined are implemented. This is not obvious, but consider the following example:

var undefined = "foo";
WScript.Echo(undefined); // This will print: foo

undefined, NaN and Infinity are just names of preinitialized "superglobal" variables - they are initialized at run-time and can be overridden by normal global or local variable with the same names.

Now, let's try the same thing with null:

var null = "foo"; // This will cause a compile-time error
WScript.Echo(null);

Oops! null, true and false are reserved keywords - compiler won't let you use them as variable or property names

Another difference is that undefined is a primitive type, while null is an object type (indicating the absense of an object reference). Consider the following:

WScript.Echo(typeof false); // Will print: boolean
WScript.Echo(typeof 0); // Will print: number
WScript.Echo(typeof ""); // Will print: string
WScript.Echo(typeof {}); // Will print: object
WScript.Echo(typeof undefined); // Will print: undefined
WScript.Echo(typeof null); // (!!!) Will print: object

Also, there is an important difference in the way null and undefined are treated in numeric context:

var a; // declared but uninitialized variables hold the value undefined
WScript.Echo(a === undefined); // Prints: -1

var b = null; // the value null must be explicitly assigned 
WScript.Echo(b === null); // Prints: -1

WScript.Echo(a == b); // Prints: -1 (as expected)
WScript.Echo(a >= b); // Prints: 0 (WTF!?)

WScript.Echo(a >= a); // Prints: 0 (!!!???)
WScript.Echo(isNaN(a)); // Prints: -1 (a evaluates to NaN!)
WScript.Echo(1*a); // Prints: -1.#IND (in Echo output this means NaN)

WScript.Echo(b >= b); // Prints: -1 (as expected)
WScript.Echo(isNaN(b)); // Prints: 0 (b evaluates to a valid number)
WScript.Echo(1*b); // Prints: 0 (b evaluates to 0)

WScript.Echo(a >= 0 && a <= 0); // Prints: 0 (as expected)
WScript.Echo(a == 0); // Prints: 0 (as expected)
WScript.Echo(b >= 0 && b <= 0); // Prints: -1 (as expected)
WScript.Echo(b == 0); // Prints: 0 (!!!)

null becomes 0 when used in arithmetic expressions or numeric comparisons - similarly to false, it is basically just a special kind of "zero". undefined, on the other hand, is a true "nothing" and becomes NaN ("not a number") when you try to use it in numeric context.

Note that null and undefined receive a special treatment from == and != operators, but you can test true numeric equality of a and b with the expression (a >= b && a <= b).

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
R.G.
  • 131
  • 1
  • 4
12

I'll explain undefined, null and Uncaught ReferenceError:

1 - Uncaught ReferenceError : variable has not been declared in your script, there is no reference to this varaible
2 - undefined: Variable declared but does not initialised
3 - null : Variable declared and is an empty value

c0m3tx
  • 98
  • 1
  • 7
BERGUIGA Mohamed Amine
  • 6,094
  • 3
  • 40
  • 38
10

Undefined means a variable has been declared but has no value:

var var1;
alert(var1); //undefined
alert(typeof var1); //undefined

Null is an assignment:

var var2= null;
alert(var2); //null
alert(typeof var2); //object
Chris
  • 7,864
  • 1
  • 27
  • 38
9

tl;dr

Use null for set a variable you know it is an Object.

Use undefined for set a variable whose type is mixed.


This is my usage of both 5 primitives and Object type, and that explain the difference between « use case » of undefined or null.

String

If you know a variable is only a string while all lifecycle, by convention, you could initialize it, to "":

("") ? true : false; // false
typeof ""; // "string";
("Hello World") ? true : false; // true
typeof "Hello World"; // "string"

Number

If you know a variable is only a number while all lifecycle, by convention, you could initialize it, to 0 (or NaN if 0 is an important value in your usage):

(0) ? true : false; // false
typeof 0; // "number";
(16) ? true : false; // true
typeof 16; // "number"

or

(NaN) ? true : false; // false
typeof NaN; // "number";
(16) ? true : false; // true
typeof 16; // "number"

Boolean

If you know a variable is only a boolean while all lifecycle, by convention, you could initialize it, to false:

(false) ? true : false; // false
typeof false; // "boolean";
(true) ? true : false; // true
typeof true; // "boolean"

Object

If you know a variable is only an Object while all lifecycle, by convention, you could initialize it, to null:

(null) ? true : false; // false
typeof null; // "object";
({}) ? true : false; // true
typeof {}; // "object"

Note: the smart usage off null is to be the falsy version of an Object because an Object is always true, and because typeof null return object. That means typeof myVarObject return consistent value for both Object and null type.

All

If you know a variable has a mixed type (any type while all lifecycle), by convention, you could initialize it, to undefined.

Bruno J. S. Lesieur
  • 3,612
  • 2
  • 21
  • 25
8

In JavasScript there are 5 primitive data types: String, Number, Boolean, null and undefined. I will try to explain with some simple examples.

Let's say we have a simple function

 function test(a) {
     if(a == null) {
        alert("a is null");
     } else {
        alert("The value of a is " + a);
     }
  }

Also, in above function if(a == null) is the same as if(!a).

Now when we call this function without passing the parameter a

test(); // will alert "a is null";
test(4); // will alert "The value of a is " + 4;

also

var a;
alert(typeof a);

This will give undefined; we have declared a variable but we have not asigned any value to this variable;

but if we write

var a = null;
alert(typeof a); // will give alert as object

so null is an object. In a way we have assigned a value null to 'a'

Manaus
  • 131
  • 1
  • 7
dinesh_malhotra
  • 1,829
  • 17
  • 10
  • Symbol is a new primitive type :) – Alexander Mills Oct 26 '17 at 01:46
  • In your `a == null` example above, it's only true because `null` and `undefined` are both truthily equal (`null === undefined` is false.) If you call `test()` without an argument, it will be `undefined`. – jimmyfever Oct 07 '21 at 21:20
  • Update for 2020: There are now _seven_ primitives types. Symbol and BigInt were added since this answer was written. – Ray Toal Oct 12 '21 at 21:50
8

In addition to a different meaning there are other differences:

  1. Object destructuring works differently for these two values:
    const { a = "default" } = { a: undefined }; // a is "default"
    const { b = "default" } = { b: null };      // b is null
    
  2. JSON.stringify() keeps null but omits undefined
    const json = JSON.stringify({ undefinedValue: undefined, nullValue: null });
    console.log(json); // prints {"nullValue":null}
    
  3. typeof operator
    console.log(typeof undefined); // "undefined"
    console.log(typeof null);      // "object" instead of "null"
    
Valeriy Katkov
  • 33,616
  • 20
  • 100
  • 123
6

OK, we may get confused when we hear about null and undefined, but let's start it simple, they both are falsy and similar in many ways, but weird part of JavaScript, make them a couple of significant differences, for example, typeof null is 'object' while typeof undefined is 'undefined'.

typeof null; //"object"
typeof undefined; //"undefined";

But if you check them with == as below, you see they are both falsy:

null==undefined; //true

Also you can assign null to an object property or to a primitive, while undefined can simply be achieved by not assigning to anything.

I create a quick image to show the differences for you at a glance.

Null and Undefined

Alireza
  • 100,211
  • 27
  • 269
  • 172
6

When you declare a variable in javascript, it is assigned the value undefined. This means the variable is untouched and can be assigned any value in future. It also implies that you don't know the value that this variable is going to hold at the time of declaration.

Now you can explicitly assign a variable null. It means that the variable does not have any value. For example - Some people don't have a middle name. So in such a case its better to assign the value null to the middlename variable of a person object.

Now suppose that someone is accessing the middlename variable of your person object and it has the value undefined. He wouldn't know if the developer forgot to initialize this variable or if it didn't have any value. If it has the value null, then the user can easily infer that middlename doesn't have any value and it is not an untouched variable.

glennsl
  • 28,186
  • 12
  • 57
  • 75
psyborg.eth
  • 310
  • 5
  • 18
5

For the undefined type, there is one and only one value: undefined.

For the null type, there is one and only one value: null.

So for both of them, the label is both its type and its value.

The difference between them. For example:

  • null is an empty value
  • undefined is a missing value

Or:

  • undefined hasn't had a value yet
  • null had a value and doesn't anymore

Actually, null is a special keyword, not an identifier, and thus you cannot treat it as a variable to assign to.

However, undefined is an identifier. In both non-strict mode and strict mode, however, you can create a local variable of the name undefined. But this is one terrible idea!

function foo() {
    undefined = 2; // bad idea!
}

foo();

function foo() {
    "use strict";
    undefined = 2; // TypeError!
}

foo();
zangw
  • 43,869
  • 19
  • 177
  • 214
5

I want to add a knowledge point which pertains to a subtle difference between null and undefined. This is good to know when you are trying to learn Vanilla JavaScript(JS) from ground up:

null is a reserved keyword in JS while undefined is a property on the global object of the run-time environment you're in.

While writing code, this difference is not identifiable as both null and undefined are always used in right hand side (RHS) of a JavaScript statement. But when you use them in left hand side (LHS) of an expression then you can observe this difference easily. So JS interpreter interprets the below code as error:

var null = 'foo'

It gives below error:

Uncaught SyntaxError: Unexpected token null

At the same time, below code runs successfully although I won't recommend doing so in real life:

var undefined = 'bar'

This works because undefined is a property on the global object (window object in case of JavaScript running in a browser)

RBT
  • 24,161
  • 21
  • 159
  • 240
  • 1
    `undefined='bar'` does not really assign any value to `undefined` (which is immutable), it just doesn't throw an error confusingly. – Dmitri Zaitsev Aug 29 '19 at 06:46
4

null and undefined are both are used to represent the absence of some value.

var a = null;

a is initialized and defined.

typeof(a)
//object

null is an object in JavaScript

Object.prototype.toString.call(a) // [object Object]

var b;

b is undefined and uninitialized

undefined object properties are also undefined. For example "x" is not defined on object c and if you try to access c.x, it will return undefined.

Generally we assign null to variables not undefined.

Brad Koch
  • 19,267
  • 19
  • 110
  • 137
Praveen
  • 1,772
  • 3
  • 24
  • 42
4

Per Ryan Morr's thorough article on this subject...

"Generally, if you need to assign a non-value to a variable or property, pass it to a function, or return it from a function, null is almost always the best option. To put it simply, JavaScript uses undefined and programmers should use null."

See Exploring the Eternal Abyss of Null and Undefined

bholben
  • 1,077
  • 1
  • 15
  • 24
4

In javascript all variables are stored as key value pairs. Each variable is stored as variable_name : variable_value/reference.

undefined means a variable has been given a space in memory, but no value is assigned to it. As a best practice, you should not use this type as an assignment.

In that case how to denote when you want a variable to be without value at a later point in the code? You can use the type null ,which is also a type that is used to define the same thing, absence of a value, but it is not the same as undefined, as in this case you actually have the value in memory. That value is null

Both are similar but usage and meaning are different.

poushy
  • 1,114
  • 11
  • 17
4

The difference in meaning between undefined and null is an accident of JavaScript’s design, and it doesn’t matter most of the time. In cases where you actually have to concern yourself with these values, I recommend treating them as mostly interchangeable.

From the Eloquent Javascript book

Alex Misiulia
  • 1,542
  • 17
  • 16
3

As typeof returns undefined, undefined is a type where as null is an initializer indicates the variable points to no object(virtually everything in Javascript is an object).

3

null - It is an assignment value, which is used with variable to represent no value (it's an object).

undefined - It is a variable which does not have any value assigned to it, so JavaScript will assign an undefined to it (it's a data type).

undeclared - If a variable is not created at all, it is known as undeclared.

Pang
  • 9,564
  • 146
  • 81
  • 122
Sandip Nirmal
  • 2,283
  • 21
  • 24
3

Check this out. The output is worth thousand words.

var b1 = document.getElementById("b1");

checkif("1, no argument"                        );
checkif("2, undefined explicitly",     undefined);
checkif("3, null explicitly",               null);
checkif("4, the 0",                            0);
checkif("5, empty string",                    '');
checkif("6, string",                    "string");
checkif("7, number",                      123456);

function checkif (a1, a2) {
 print("\ncheckif(), " + a1 + ":");
 if (a2 == undefined) {
  print("==undefined:    YES");
 } else {
  print("==undefined:    NO");
 }
 if (a2 === undefined) {
  print("===undefined:   YES");
 } else {
  print("===undefined:   NO");
 }
 if (a2 == null) {
  print("==null:         YES");
 } else {
  print("==null:         NO");
 }
 if (a2 === null) {
  print("===null:        YES");
 } else {
  print("===null:        NO");
 }
 if (a2 == '') {
  print("=='':           YES");
 } else {
  print("=='':           NO");
 }
 if (a2 === '') {
  print("==='':          YES");
 } else {
  print("==='':          NO");
 }
 if (isNaN(a2)) {
  print("isNaN():        YES");
 } else {
  print("isNaN():        NO");
 }
 if (a2) {
  print("if-?:           YES");
 } else {
  print("if-?:           NO");
 }
  print("typeof():       " + typeof(a2));
}

function print(v) {
 b1.innerHTML += v + "\n";
}
<!DOCTYPE html>
<html>
<body>
<pre id="b1"></pre>
</body>
</html>

See also:

Cheers!

latitov
  • 432
  • 3
  • 8
2

The difference between undefined and null is minimal, but there is a difference. A variable whose value is undefined has never been initialized. A variable whose value is null was explicitly given a value of null, which means that the variable was explicitly set to have no value. If you compare undefined and null by using the null==undefined expression, they will be equal.

Stacked
  • 6,892
  • 7
  • 57
  • 73
  • This answer is misleading... see the discussion in the accepted answer. Bottom line - `null==undefined` is `true` only because of implicit casting (or the equivalent term in JS). Evidently, `null===undefined` is `false` because using when you use `===` it compares the **type** as well. – Guy Nov 11 '15 at 05:47
2

Basically, Undefined is a global variable that javascript create at the run time whether null means that no value has assigned to the variable (actually null is itself an object).

Let's take an example:

        var x;  //we declared a variable x, but no value has been assigned to it.
        document.write(x) //let's print the variable x

Undefined that's what you will get as output.

Now,

        x=5;
        y=null;
        z=x+y;

and you will get 5 as output. That's the main difference between the Undefined and null

Zaid Khan
  • 357
  • 4
  • 14
2

Both special values imply an empty state.

The main difference is that undefined represents the value of a variable that wasn’t yet initialized, while null represents an intentional absence of an object.

The variable number is defined, however, is not assigned with an initial value:

let number;
number; // => undefined

number variable is undefined, which clearly indicates an uninitialized variable

The same uninitialized concept happens when a non-existing object property is accessed:

const obj = { firstName: 'Dmitri' };
obj.lastName; // => undefined

Because lastName property does not exist in obj, JavaScript correctly evaluates obj.lastName to undefined.

In other cases, you know that a variable expects to hold an object or a function to return an object. But for some reason, you can’t instantiate the object. In such a case null is a meaningful indicator of a missing object.

For example, clone() is a function that clones a plain JavaScript object. The function is expected to return an object:

function clone(obj) {
  if (typeof obj === 'object' && obj !== null) {
    return Object.assign({}, obj);
  }
  return null;
}
clone({name: 'John'}); // => {name: 'John'}
clone(15);             // => null
clone(null);           // => null

However, clone() might be invoked with a non-object argument: 15 or null (or generally a primitive value, null or undefined). In such case, the function cannot create a clone, so it returns null - the indicator of a missing object.

typeof operator makes the distinction between the two values:

typeof undefined; // => 'undefined'
typeof null;      // => 'object'

The strict quality operator === correctly differentiates undefined from null:

let nothing = undefined;
let missingObject = null;
nothing === missingObject; // => false
Jayakumar Thangavel
  • 1,884
  • 1
  • 22
  • 29
2

Quote from "Eloquent Javascript" 3rd edition by Marijn Haverbeke:

The difference in meaning between undefined and null is an accident of Javascript's design, and it doesn't matter most of the time. In cases where you actually have to concern yourself with these values, I recommend treating them as mostly interchangeable

Honestly, at first, I am a bit skeptical about this advice. However, in my own interpretation, it is a lazy (vs eager) way to deal with their differences. Maybe, we don't have to deal with the differences at all. If we have to, we can delay our concern (util we have to) and not hyperactively/defensively worry about it every step of the way as those values (null and undefined) flow through our code.

PS: This is not a direct answer to your question. This is just a related opinion.

Lu Tran
  • 401
  • 4
  • 9
2

Generally – don't use null to avoid confusion.

  1. Standard library methods return undefined, not null
let a = [10];
console.log(a[1]) //=> undefined
console.log(a.find(value => value === 5)) //=> undefined
  1. I see often in people's code that some variable was undefined at first, then assigned to some value, then cleared by setting to null. That's not consistent, better to set back to undefined.

Still, null makes sense if framework uses it, or for json serialization.

Lev Lukomsky
  • 6,346
  • 4
  • 34
  • 24
2

also note the difference in comparison:

10 > undefined
false

10 < undefined
false

10 < null
false

10 > null
true
Giulio
  • 469
  • 5
  • 15
0

The type of null is Object, while the type of undefined is undefined. Null means ‘no value’, while undefined means ‘not existing’.

typeof undefined; //undefined
typeof null; // Object
undefined !== null; //true
undefined == null; //true
undefined === null; //false
var var1;
var1; //undefined 
var var2 = null;
var2; //null
UserName Name
  • 267
  • 2
  • 3
0
const data  = { banners: null }
const { banners = [] } = data;
console.log(data)      // null


const data  = { banners: undefined }
const { banners = [] } = data;
console.log(data)      // []
mohit arora
  • 592
  • 6
  • 10
-1

In Javascript null is an empty or non-existent value and it must be assigned. But Undefined means a variable has been declared, but not value has not been defined.

let a = null;  
console.log(a);    // null
let b;         
console.log(b);    // undefined

In JS both null and undefined are primitive values. Also you can look the following lines of code

console.log(typeof null); //Object
console.log(typeof undefined); //undefined
console.log(10+null); // 10
console.log(10+undefined); //NaN
vrogros
  • 25
  • 1
  • 8
  • 1
    Undeclared variables have also undefined type. And typeof undefined is "undefined", not "object". – Linostar Feb 16 '21 at 11:39
-2

If a variable is not initialized then it is undefined. undefined is not a object. Example: var MyName; console.log(typeof MyName);

Check the console log in development tool, it will be printed as undefined.

null is a a object.If you want some variable to be null then null is used.null variable exists but value is not known.It should be assigned to a variable pro grammatically. null is not automatically initialized.

Example : var MyName = null; console.log(typeof MyName); Check the csole log in development tool, it will be an object.

NavyaKumar
  • 587
  • 5
  • 3
-4

Just to add my views -

A variable that is declared only, and never used anywhere, is removed off by an optimizing compiler in case of compiled languages like C++[or a warning is flagged in the IDE]. It ultimately means that the variable is non-existent because it's memory is never allocated.

In case of javascript interpreter, [I guess] a variable is treated as existing only from the point onwards where it is given a value. Before that point, it's type is "undefined", and no memory is allocated for it. And, so its type is undefined.

A null in javascript is a value that represents an address, but that address points to nothing yet[non-existent reference]. Nevertheless, its a value.

Hoven
  • 393
  • 4
  • 8
  • Nope, there needs to be some memory allocated to differentiate a declared (yet `undefined`) variable from a non-declared one. `undefined` is just a value as well, and it's the default value for uninitialized variables. – Bergi Aug 18 '14 at 07:23
  • I don't have the knowledge about how the js interpreter might be working, but the guess was based on the fact that the typeof operator applied to a non-existant variable and a declared-only variable yields the same "undefined" string. I have doubts about the fact that an undeclared variable gets a default primitive value undefined[perhaps, somebody who has internal knowldege of the interpreter could clarify this], even though the comparison would return true. There was no undefined value prior to ECMA-262? – Hoven Aug 18 '14 at 11:11
  • That `typeof` has the same output for these two cases doesn't mean anything (though it might hint at the original implementation in netscape). Admittedly, it's possible that an optimizing compiler doesn't allocate stack variables until they're assigned to, but I don't think the non-optimising ones of the various implementations (note: there isn't a single interpreter for the language) do this - after all, ES spec says variable environments are initialized on call. – Bergi Aug 18 '14 at 11:40
  • 1
    After a research I find my views were not correct. Please refer section 12.2 ECMA Standard - http://www.ecma-international.org/ecma-262/5.1/#sec-12.2 Quote: A variable statement declares variables that are created as defined in 10.5. Variables are initialised to undefined when created. And, on the following link, the point no. 2 clarifies that undeclared variables are in fact created only at the time of initialization, otherwise not - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var – Hoven Aug 28 '14 at 12:48
-4

Null is ALWAYS an unknown object that exists in memory, whereas undefined is not.

AbbyPaden
  • 592
  • 5
  • 5