What is the difference between null and undefined in JavaScript?

What is the difference between null and undefined in JavaScript?

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

Solutions/Answers:

Solution 1:

In JavaScript, undefined means a variable has been declared but has not yet been assigned a value, such as:

var TestVar;
alert(TestVar); //shows undefined
alert(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;
alert(TestVar); //shows null
alert(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.

null === undefined // false
null == undefined // true
null === null // true

and

null = 'value' // ReferenceError
undefined = 'value' // 'value'

Solution 2:

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.

Solution 3:

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 

Solution 4:

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.

Solution 5:

Please read the following carefully. It shall remove all your doubts regarding
the the difference between null and undefined in JavaScript. Also you can use the utility function given below to exactly determine types.

In JavaScript we can have 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

Following explains each of these cases one by one

  1. Undeclared Variables: Following holds true for undeclared variables

    • Can only be checked by typeof() which returns string ‘undefined’
    • Cannot be checked with == or === or by if or conditional operator ? (throws Reference Error)
  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
    • if or conditional operator ? returns false
  3. Variables assigned with literal undefined: These variables are treated similarly as the 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
    • if or conditional operator ? returns false
  5. Variables assigned with anything other than undefined or null

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

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

  1. Check for undeclared/unassigned/assigned with undefined using typeof. return if string ‘undefined’ is returned.
  2. Check for null using ===. return ‘null’ if true.
  3. Check for actual type using typeof. return type if not equal to ‘object’
  4. Call Object.prototype.toString.call(o) to determine actual object type. It shall return a string of type ‘[object ObjectType]’ for all the built in Javascript or DOM defined Objects. For user defined objects it returns ‘[object Object]’

You can also use the following utility function for determining types. It currently supports all ECMA 262 2017 types.

function TypeOf(o,bReturnConstructor)
 {
   if(typeof o==='undefined') return 'undefined'
   if(o===null) return 'null'   
   if(typeof o!=='object') return typeof o

   var type=Object.prototype.toString.call(o)
  switch(type)
  {
     //Value types:4
     case '[object Number]': type='number';break;
     case '[object String]': type='string';break;
     case '[object Boolean]': type='boolean';break;
     case '[object Date]': type='date';break;


   //Error Types:7
     case '[object Error]': type='error';break;
     case '[object EvalError]': type='evalerror';break;
     case '[object RangeError]': type='rangeerror';break;
     case '[object ReferenceError]': type='referenceerror';break;
     case '[object SyntaxError]': type='syntaxerror';break;
     case '[object TypeError]': type='typeerror';break;
     case '[object URIError]': type='urierror';break;


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

    //Keyed Collection Types:2
     case '[object Map]': type='map';break;
     case '[object WeakMap]': type='weakmap';break;

    //Set Types:2
     case '[object Set]': type='set';break;
     case '[object WeakSet]': type='weakset';break;

    //Operation Types
    case '[object RegExp]': type='regexp';break;
    case '[object Proxy]': type='proxy';break;
    case '[object Promise]': type='promise';break;

    case '[object Object]': type='object';
             if(bReturnConstructor && o.constructor) type=o.constructor.toString().match(/^function\s*([^\s(]+)/)[1];
         break;
    default:
        type=type.split(' ')[1]
        type=type.substr(0,type.length-1)   

   }
    return type 
}

Solution 6:

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