A case of no value vs no object: Comparing 'null', 'undefined' and 'undeclared'.
Tags: javascript, webdev, python
Published: 2024-03-15 13:48:37


**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.

```JavaScript
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
```
**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.

```JavaScript
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.");
}
```
 

   - **Default Value:** functions may return **`'null'`** as a default value when given no valid result or object available.

```JavaScript
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.");
}

``` 
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;
```JavaScript
if (variable === null) {
    // Variable is null
}
```
**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;

```JavaScript
if (variable === undefined) {
 // resolved if variable is undefined
}
```
 - Using **'typeof'** operator:
```JavaScript
if (typeof variable === 'undefined') {
 // resolved if variable is undefined
}
``` 
**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**;

```JavaScript
if (typeof foo !== 'undefined') {
    // foo could get resolved and it's defined
}
```
- Logging the suspect variable in the console;
 
![Console results for undeclared variable](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/46mbbq2tnbf9uyr99zch.png)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yvculadj3k9p02v55ks0.png)
Comparing the two using **'==='**;
![Strict equality comparison](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/g08f3i659qyz69u1i6rs.png)

---
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.