DEV Community

Cover image for A case of no value vs no object: Comparing 'null', 'undefined' and 'undeclared'.
Joshua Ng'ang'a Raphael
Joshua Ng'ang'a Raphael

Posted on

A case of no value vs no object: Comparing 'null', 'undefined' and 'undeclared'.

Weird JavaScript
Often times, programmers coming from other languages such as Java or Python which uses the 'none' keyword in place of 'null', are often left bewildered with just how to interact with 'null' in JavaScript, considering its confusing similarity but complete use case contrast with the 'undefined' keyword.
While in most languages, 'null' is often used to refer to the absence of an assigned value, JavaScript instead uses the keyword 'undefined' to do so with 'null' referring to the intentional absence of any object instance.
In this article, we discuss the two keywords as well as elaborate on the differences between them.


Null
Used to signify that a variable ** or **object doesn't currently point to any valid object instance, Brendan Eich in the development of object oriented JavaScript saw it valid to provide developers with a clear way to indicate the absence of a relevant object instance.

This allows 'null' to be applied in the following use cases;

Explicit initialization as well as object reference resetting - allowing for the initializing of variables to 'null', indicating no current object reference which may be assigned later as well as erasing the memory associated with it when no longer needed allowing for garbage-collection.

let user = null; // Initialize user to null
// Later in the code...
user = { name: "John", age: 30 }; // Assign an object reference
user = null; //Release the memory associated with user
Enter fullscreen mode Exit fullscreen mode

As a return value in functions- depending on the scenario, 'null' can be used in functions to indicate;

  • Error signaling: indicating an error or inability to produce a valid result.
function fetchData(url) {
    if (!isValidUrl(url)) {
        return null; // Return null to indicate invalid URL
    }
    // Otherwise, fetch data from the URL...
}

const data = fetchData("https://example.com/api");
if (data === null) {
    console.log("Error fetching data.");
}
Enter fullscreen mode Exit fullscreen mode
  • Default Value: functions may return 'null' as a default value when given no valid result or object available.
function findElement(arr, target) {
    for (let element of arr) {
        if (element === target) {
            return element; // Return element if found
        }
    }
    return null; // Return null if element is not found
}

const result = findElement([1, 2, 3, 4], 5);
if (result === null) {
    console.log("Element not found.");
}

Enter fullscreen mode Exit fullscreen mode

From the previous examples, 'null' can be seen to be of type object with its introduction to JavaScript providing a means to indicate that one is referring to a object instance that does not exist.

Checking for null
To check if an object or variable is pointing to an object instance that does not exist, we use strict equality to compare the variable to 'null' as shown;

if (variable === null) {
    // Variable is null
}
Enter fullscreen mode Exit fullscreen mode

Undefined
Being one of the object oriented programming languages allowing for the declaring of variables without immediately assigning them values, there was a need to represent the absence of a defined value or property in JavaScript.
As the keyword 'null' already served the purpose of indicating the absence of an object instance, there arose the need of a different keyword which would instead represent the presence of a variable that has not been assigned a value where one should be defined, in other words, the variable is 'undefined'

Checking for undefined
We check for 'undefined' as follows;
Checking if a variable is of type 'undefined' by using strict equality as shown;

if (variable === undefined) {
 // resolved if variable is undefined
}
Enter fullscreen mode Exit fullscreen mode
  • Using 'typeof' operator:
if (typeof variable === 'undefined') {
 // resolved if variable is undefined
}
Enter fullscreen mode Exit fullscreen mode

Undeclared
A variable is said to be undeclared when an attempt at trying to access it is made yet the variable has not been created.
We can check if a variable exists by;

  • Checking its type;
if (typeof foo !== 'undefined') {
    // foo could get resolved and it's defined
}
Enter fullscreen mode Exit fullscreen mode
  • Logging the suspect variable in the console;

Console results for undeclared variable

As observed, trying to access a variable that has not been initialized leads to the returning of a reference error.

Mistaken Identity
As both undefined and null are falsy values meaning they are both treated as 'false' in boolean context, there arises a need to distinguish the two as trying to access a variable that is not assigned a value and one that doesn't point to any valid object instance will return the same error; undefined.
Inorder to confirm the specific scenario at hand, the use of strict equality === is used and not == as the loose equality double equal operator carries out 'type coercion' which converts the type of the variables being compared into the same type.

Comparing 'undefined' and 'null' using '==';
Loose equality comparison
Comparing the two using '===';
Strict equality comparison


We discuss 'null' and 'undefined' and outline their key differences and similarities and why there was a need to have both. We also provide use cases for both values as well as techniques on distinguishing one from another.
Mechanisms for checking and dealing with 'null' and 'undefined' should be provided to avoid accessing invalid objects or variables working with invalid objects or variables.

Top comments (0)