Safely identify null, nil, undefined and empty in javascript / typescript

Monir Khan
2 min readSep 4, 2021

--

One of the main differences between javascript family with languages like java, c++, python is the management of null and undefined values.

Javascript is loosely types programming lanuage and the grandparent of all web scripting languages. But maintaing null, unidentified etc. is often frustrating to many.

Here i have example of some utility methods to easily maintain and strictly check when a value is missing.

export function isNil(value: any): value is null | undefined {
return value === null || value === undefined;
}
export function isNull(value: any): value is null {
return value === null;
}
export function isUndefined(value: any): value is undefined {
return value === undefined;
}
export function isObjectEmpty(value: any): boolean {
return (value && Object.keys(value).length === 0 &&
value.constructor === Object);
}
export function isString(value: unknown): value is string {
return typeof value === ‘string’ || value instanceof String;
}
// eslint-disable-next-line @typescript-eslint/ban-typesexport function isFunction(value: unknown): value is Function {
return typeof value === ‘function’ || value instanceof Function;
}
export function isEmpty(obj: unknown): boolean {
return isNil(obj) || Object.keys(obj).length === 0;
}
export function isPromise(value: any): value is PromiseLike<any> {
return isFunction(value?.then);
}
export function isNilPrimitiveObject(obj: Number | Boolean | String): boolean {
return isNil(obj) || isNil(obj.valueOf());
}
export function isNotEmpty(value: string | number | boolean | unknown): boolean {
switch (typeof value) {
case 'number':
case 'boolean':
case 'undefined':
return !isNil(value);
case 'object':
if (value instanceof Number || value instanceof Boolean ||
value instanceof String) {
return !isNilPrimitiveObject(value);
}
return !isEmpty(value);
case 'string':
return value?.length > 0;
default:
console.error('Felaktig varde');
return false;
}}
Note: If you are using old javascript remove the type declarations from methods, t.ex. export function isNil(value: any): value is null | undefined { can be only export function isNil(value) {
https://dev.to/pandurijal/difference-between-null-and-undefined-in-javascript-with-notes-3o34

If you want to learn more about null vs undefined, visit this article

https://dev.to/pandurijal/difference-between-null-and-undefined-in-javascript-with-notes-3o34

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Monir Khan
Monir Khan

Written by Monir Khan

System developer, Swedish board of agriculture

No responses yet

Write a response