Javascript Tutorial
Javascript Tutorial Introduction to Javascript JavaScript Code Editors & IDE JavaScript Hello World Example Javascript Syntax and Rules syntax_rules javascript_identifiers JavaScript Keywords & Reserved Words javascript_variables JavaScript Const JavaScript let vs var vs const Data Types in JavaScript JavaScript String Template Literals & String interpolation in JavaScript Tagged Templates in JavaScript String to Number in JavaScript Number Data Type in JavaScript NaN in JavaScript JavaScript Number Min & Max & Safe Values JavaScript EPSILON & Floating point precision Infinity in JavaScript JavaScript Bigint BigInt Vs Number in JavaScript Boolean Data Type in JavaScript Undefined in JavaScript Null in JavaScript Null vs Undefined in JavaScript JavaScript Operators Arithmetic Operators in JavaScript Unary plus & minus operators in JavaScript Increment & Decrement Operators in JavaScript Comparison or Relational operators in JavaScript Strict Equality (==) Loose Equality (===) in JavaScript Ternary Conditional Operator in JavaScript Logical Operators in JavaScript Bitwise Operators in JavaScript Assignment Operators in JavaScript Nullish Coalescing Operator in JavaScript Comma Operator in JavaScript Typeof JavaScript Operator Precedence in JavaScript JavaScript if, else & nested if statement Switch Statement in JavaScript While & Do While Loops in JavaScript For Loop in JavaScript Break statement in JavaScript Continue Statement in JavaScript Arrays in JavaScript Array Constructor in Javascript Sparse Array Vs Dense Array in JavaScript How to merge Arrays in JavaScript Array Methods in JavaScript Functions in JavaScript Function Parameters & Arguments in JavaScript JavaScript Default Parameters Pass by Value and Pass by Reference in Javascript Function Expression in Javascript Nested Functions in JavaScript Immediately-invoked Function Expressions (IIFE) JavaScript Callback Functions Arrow Functions in JavaScript Arguments Object In JavaScript Rest Parameters in JavaScript Objects in Javascript Create Objects in JavaScript JavaScript Object Properties Computed Property Names in JavaScript Object Literal in JavaScript Constructor Function & New Operator in JavaScript Delete Operator in JavaScript hasOwnProperty in JavaScript Using Getters and Setters in Javascript DefineProperty in JavaScript JavaScript Property Descriptors Enumerable, Writable & Configurable Object Destructuring in JavaScript Variable Scope in JavaScript Hoisting in JavaScript Lexical Scope & Closures in JavaScript This in JavaScript Global Object, Window & Globalthis in JavaScript Call function in Javascript Prototype In Javascript Prototype Inheritance in JavaScript Instanceof Operator in JavaScript Spread Operator in JavaScript

Undefined in JavaScript

Undefined is a primitive data type in JavaScript. It is also a special value in JavaScript. JavaScript also has a global variable with the name undefined which has the value Undefined. It is one of JavaScript’s primitive values and is treated as falsy for boolean operations.

Undefined in JavaScript

When we refer to undefined in JavaScript, it could be one of the following

Undefined as a value

undefined is a primitive valuethat indicates that the value is not assigned. i.e. whenever we do not explicitly assign a value to a variable, JavaScript assigns the undefined value to it. It is an unintentional absence of any value. Undefined also means non-existing property of an object or non-existing array element etc.

Undefined is different from the value null. The null value means we know that it does not have any value. The value undefined means we do not know its value.

The ECMA specifications define undefined as “the primitive value used when a variable has not been assigned a value”.

JavaScript explicitly sets the value undefined when we do not provide any value. The following are some of the instances where a variable gets the value undefined

Uninitialized variable

Every JavaScript variable that we create without assigning any value gets the value of undefined.

The following example declares the variable num. We have not given it any initial value. By default, it gets the value undefined.

                            
let num;
console.log(num);         //undefined
 
 
                            
                        
                            
                        

Function argument that has not been supplied

In JavaScript number of arguments that we supply does not have to match the Parameters of the functions. The unpassed arguments are set to undefined.

In the following example, we do not pass any argument to the parameter c. Here JavaScript assigns undefined to c argument.

                             
someFunc(1,2)
 
function someFunc(a, b ,c) {
    console.log(a)
    console.log(b)
    console.log(c)  //undefined 
}
  
 
                            
                        
                            
                        

The return value of functions that don’t return a value

When a function has no return value, it returns undefined.

In the following example, the functionsomeFunc does not have a return value. But when we assign its return value to a variable, JavaScript assigns undefined to it.

                            
var a = someFunc()
 
console.log(a)      //undefined
 
function someFunc() {
}        
  
 
                            
                        
                            
                        

Non-existing object Property

Trying to access a non-existing property of an object returns undefined.

In the example below, the person object does not have age property. Trying to access it does not throw any errors but returns undefined instead.

                            
let person = { 
    firstName: "Allie", 
    lastName: "Grater", 
};
 
console.log(person.age)     //undefined    
  
 
                            
                        
                            
                        

Non-existing array elements

Similarly, Non-existing array elements also return undefined.

In the following example, the cars array does not have an element at 5. But JavaScript returns undefined.

                            
const cars = ["Saab", "Volvo", "BMW"];
 
console.log(cars[5])  //undefined
                            
                        
                            
                        

Note that referring non-existent variable returns reference error. But the referring non-existent property of an object (or non-existent array element) returns undefined.

void operator

The void operator always returns undefined irrespective of the expression provided to it.

For Example, all of the following returns are undefined.

                            
void (100)                 //undefined
void (true)                //undefined 
void {firstName: 'Bill'}   //undefined
void ("Hello")             //undefined
 
                        
                            
                        

Explicitly set to undefined

We can explicitly set a variable to undefined.

                            
let myVar= undefined;
 
                        
                            
                        

Assigning undefined is not recommended unless you have a good reason to do so. undefined means that the value is not assigned. If you know the variable does not have any value then use null.

Undefined Type

The undefined is also a type in JavaScript. The data type of variable with the value of undefined is undefined. The variable of undefined type can store only one value i.e. undefined.

In the following example, we use the typeof operator to find out the data type of num variable.

                            
let num;
console.log(num);         //undefined
typeof (num)              //undefined
 
 
                            
                        
                            
                        

Global Undefined variable

The JavaScript has a global variable with the name undefined. The initial value of the global undefined is the value undefined.

It is the property of the global object. Hence you can access it using the window object (only in the browser) or using theglobalThis property.

                            
console.log(undefined)          //undefined
console.log(typeof(undefined))  //undefined
 
console.log(window.undefined)          //undefined
console.log(typeof(window.undefined))  //undefined
 
console.log(globalThis.undefined)          //undefined
console.log(typeof(globalThis.undefined))  //undefined
 
 
                            
                        
                            
                        

We can explicitly assign undefined to a variable. The undefined right-hand side of the assignment operator refers to the global variable.

                            
let myVar= undefined;   
                        
                            
                        

Since the ES5 version, the undefined is a non-configurable, non-writable & non-enumerableproperty. But that does not stop someone from overriding it inside a function

                            
abc()
 
function abc() {
    var undefined=10
    console.log(undefined)      //10
    console.log(typeof(undefined))  //number
}
 
 
                            
                        
                            
                        

Hence take care not to override it

Checking for undefined

There are two ways you can check if the value is undefined.

One method is to compare the value against the value of the global undefined property

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

Another way is to use the typeof operator, which returns the data type as a string.

                            
let a
console.log(typeof(a)==="undefined") //true
                        
                            
                        

Note that undefined is true does not mean that the property or variable exists. To check whether the property exists use the hasOwnProperty or use the 'prop' in obj syntax.

The typeof is the preferred way of checking for undefined because the global undefined property can be overwritten

                            
var undefined=10      //overwrting global undefined property
 
var a;
console.log(a===undefined)              // false.  becuase undefined is 10 
console.log(typeof(a)==="undefined") //true
                        
                            
                        

Null & undefined

Comparing undefined to null using loose equality checker (==) return true. This is because JavaScript loose the equality checker (==) coerces the value of undefined to no value. Hence the result is true

                             
 
let a
console.log(a==null)     //true because both null & undefined is treated as no value
 
  
 
                            
                        
                            
                        

But using the strict equality checker (===) returns false because the data type of null is different from the data type of undefined.

                             
let a
console.log(a===null)   //false. Becuase types are different
 
                            
                        
                            
                        

The boolean value of undefined

The boolean value of undefined is considered as falsy. i.e. JavaScript implicitly converts the value undefined to false before using it in an expression involving booleans.

                             
let a
 
if (a) {
    console.log("true")     //this code does not execute
}
 
if (!a) {
    console.log("false")    //false
}
 
 
*****
false
 
                            
                        
                            
                        

But this does not mean that undefined is false. Undefined means we do not know its value. Hence comparing undefined either with false or true always results in false.

                            
let a
 
 //loose equality check
  
 console.log(a==false)       //false
 console.log(a==true)        //false
  
  
 //Strict equality check
  
 console.log(a===false)      //false
 console.log(a===true)       //false     
  
 
                            
                        
                            
                        

Arithmetic Expression & undefined

In arithmetic expressions, the undefined is coerced to NaN.

                            
let a=10
let b
 
console.log(a+b)        //NaN
console.log(Number(b))  //NaN