Undefined vs Null in JavaScript ๐Ÿค”

Undefined vs Null in JavaScript ๐Ÿค”

ยท

2 min read

Undefined vs Null in JavaScript

In last article I explained how to use variables in JavaScript but I also mentioned undefined, here I will try my best to explain to you what is undefined, what is the difference with null, why both are existing and I will give you some examples.

Undefined

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

// console.warn(notDeclared); // Impossible not defined
console.warn(typeof notDeclared); // logs : undefined

let test;
console.warn(test); // logs : undefined
console.warn(typeof test); // logs : undefined

const testConst = undefined;
console.warn(testConst); // logs : undefined
console.warn(typeof testConst); // logs : undefined

// Impossible, missing initializer in const declaration
/* const testConst2; 
console.warn(testConst2); // Broken code
console.warn(typeof testConst2); // Broken code */

Null

Unlike undefined, null is an assignment value, null can be assigned to a variable as a representation of no value :

const test = null;
console.warn(test); // logs : null
console.warn(typeof test); // logs : object

As you can see undefined and null are very different undefined is a type itself, and null seems like an object but no it is in reality a primitive value

To understand why null is not an object I will quote a sentence from the book Professional JavaScript for Web Developers : "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."

More examples

Sometimes JavaScript is fun, or horrible depending on how you feel ๐Ÿค’

console.warn(null === undefined); // logs : false
console.warn(null == undefined); // logs : true
console.warn(null === null); // logs : true

// null = 'value'; // Impossible ReferenceError
// let undefined = 'value'; Impossible trick :
// Identifier 'undefined' has already been declared

// /!\ DON'T DO THIS /!\
(function () {
  var undefined = 'wtf';
  console.warn(undefined, typeof undefined); // logs : wtf string
})();

// /!\ DON'T DO THIS /!\
(function (undefined) {
  console.warn(undefined, typeof undefined); // logs: wtf2 string
})('wtf2');

That's it for undefined and null !

๐Ÿš€ In my next article you can learn how to use conditions in JavaScript ๐Ÿš€