Skip to main content

Command Palette

Search for a command to run...

Null in Javascript

Published
2 min read
Null in Javascript

Null is an interesting term in JavaScript and has many use cases. let's take a deep dive into them,

Define a null variable: null in JavaScript represents an intentional absence of any object value and can be used as a value and also inferred as a type.

Nullable Types: A variable can have a specific type and a null value, we can use both using union types which allows us to use multiple types for a single variable.

Non-Nullable Assertion Operator ( ! ): It helps you deal with situations where a variable might not have a value (null), making sure you don't run into problems when you try to use it.

Strict null checking: strictNullChecks is a TypeScript compiler option that enhances code safety by enforcing stricter rules around handling null and undefined.

Object Prototype: In JavaScript, null is a primitive value, not an object, despite the confusing result of typeof null being 'object'.Null itself does not have a prototype chain when you use Object.getPrototypeOf(null), it attempts to treat null as an object and that is where it will return you an error.

Null vs Undefined

When should a function return null or undefined?

The simple answer is that when there is no error-like situation and there is no value to refer to, return null. Undefined signifies an unintended absence of a value and we usually return undefined when the return value isn't explicitly set. Also, it varies from project to project, what standards they are following.

More from this blog

ankita yadav's blog

8 posts