JavaScript undefined and null: Let's talk about it one last time!
Tags: javascript, codenewbie, beginners
Published: 2020-11-10 04:59:20

In JavaScript, `undefined` and `null` are very different from each other. However, there are only a few similarities that may confuse a beginner to the language. This article aims to explain the similarities, differences, and usages with examples. Hope you find it useful.

# What is undefined?
`undefined` typically means a variable has been declared but has not yet been assigned a value. 

```js
let author;
console.log(author); // prints, undefined
```
In the above example, we have declared a variable `author` but haven't assigned a value to it. Hence the variable `author` is `undefined`. 

There is also a way to confirm it,

```js
typeof(author); // prints "undefined"
```
When you access non-existent object properties, you get an `undefined`.

```js
let article = {'title': 'How to do something..'};

console.log(article.title); // prints, "How to do something.."
console.log(article.author); // prints, undefined
```
## Watch out for: ReferenceError
In the case of `undefined`, the variable must be declared. On the contrary, accessing a variable that's not been declared will cause a `ReferenceError`. 

```js
console.log(rating);
```
If you haven't declared the rating variable and trying to access it like shown above, you will get an error,

![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1604652349517/yg_PSWQXN.png)

⚠️ **Confusion Alert**: Please do not be confused with the phrase, `is not defined` in the above error message. As explained, it doesn't mean `undefined`.

# What is null?
`null` is an assignment value. You as a programmer may want to assign the value `null` to a variable. It simply means the value is blank or non-existent.

```js
let author = null;
console.log(null); // prints, null
```
Interestingly, when we use `typeof` to check the type of null, it returns "object". 

```js
typeof(null); // prints, "object"
```
⚠️ **Confusion Alert**: This can be confusing as `null` is a primitive value. This is probably one issue JavaScript is living with for a long now and we expect better reasoning for it.

# Similarities
There are a couple of similarities between `undefined` and `null`.
- They both are primitive values. JavaScript has 7 primitive values, 
 1. Number
 1. String
 1. Symbol
 1. Boolean
 1. BigInt
 1. undefined
 1. null. 

 All other values in JavaScript are objects(yes, including functions and arrays).

- They both are `falsey` values.

 > A falsy (sometimes written falsey) value is a value that is considered false when encountered in a Boolean context.

 In JavaScript, there are 6 falsy values including undefined and null,
 1. false
 1. 0
 1. ""(empty string)
 1. NaN
 1. undefined
 1. null

# Differences
Apart from the similarities mentioned above, `undefined` and `null` are way apart from each other. They are strictly not equal,

```js
(undefined === null) // returns, false
(undefined !== null) // returns true
```
⚠️ **Confusion Alert**: However, they are loosely equal. Loose equality is performed using the `==` operator which compares two values after converting them to a common type. You should try avoiding it.

```js
(undefined == null) // returns, true
```
Just remember, `undefined` means no value assigned for a declared variable. Whereas, `null` itself is a value that can be assigned to a variable, and `null` signifies an empty/blank value.

# How to check for undefined and null?
Use the strict equality operator(`===`) to check if a variable is `undefined` or has a `null` value

```js
let author ;

if (author === undefined) {
 console.log(`author is undefined`);
} else {
 // Do something
}
```
Similarly, for `null`,

```js
let author = null ;

if (author === null) {
 console.log(`The value of author is null`);
} else {
 // Do something
}
```
As both `undefined` and `null` are falsy values, you can do this as well. It will match both undefined and null.

```js
if (!author) {
 // Do something
}
```

# Usage Cheatsheet: undefined and null
With the understanding, we have so far, here is the cheat-sheet for using `undefined` and `null`,

```js
// Declared age but not assigned any value to it
let age;

// Right way to check
age === null;  // returns, false
age === undefined;  // returns, true

// Don't use this 
age == null;  // returns, true            
age == undefined;  // returns, true



// Declared name and assigned a null value
let name = null;

// Right way to check
name === null;  // returns, true      
name === undefined;  // returns, false   

// Don't use this 
name == null;  // returns, true
name == undefined;  // returns, true       

// type checking
typeof  age;  // 'undefined'
typeof name;  // 'object'

// Create an object with one property where key is x and value is null
let obj = {x: null};

obj.x === null;   // true
obj.x === undefined;   // false
obj.y === null;  // false
obj.y === undefined;  // true


// Not possible
null = 'abcd';
// Possible, but don't do it
undefined = 'abcd';

```
# In Summary
To summarize,
- `undefined` and `null` are primitive values and they represent falsy values. All the similarities between undefined and null end here.
- `undefined` value is typically set by the JavaScript engine when a variable is declared but not assigned with any values.
- `null` value is typically set by programmers when they want to assign an empty/blank value.
- undefined and null are strictly not equal(!==).
- If you try to access the value of a variable that is not even declared, it will result in a `ReferenceError`.

# Before we end...
Thank you for reading this far! You can @ me on [Twitter (@tapasadhikary)](https://twitter.com/tapasadhikary) with comments, or feel free to follow.

If it was useful to you, please Like/Share so that, it reaches others as well. You may also like,
- [JavaScript: Equality comparison with ==, === and Object.is](https://blog.greenroots.info/javascript-equality-comparison-with-and-objectis-ckdpt2ryk01vel9s186ft8cwl)
- [Understanding JavaScript Execution Context like never before](https://blog.greenroots.info/understanding-javascript-execution-context-like-never-before-ckb8x246k00f56hs1nefzpysq)
- [JavaScript Scope Fundamentals with Tom and Jerry](https://blog.greenroots.info/javascript-scope-fundamentals-with-tom-and-jerry-ckcq723h4007vkxs18dxa97ae)

That's all for now. See you again with my next article soon. Until then, please take good care of yourself.