Safely identify null, nil, undefined and empty in javascript / typescript
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) {
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