JavaScript Helper to determine the type of your variable
Continuously you will need to know what type are the variables in order to create conditionals that are prepared to manipulate and maintain your code stable. For that reason I give you a cheat sheet to establish what is exactly your variable.
These are functions to which you pass your variable to indicate whether it is of a certain type or not.
Object
const myObject = {};const isObject = variable => variable.constructor === Objectconsole.log("myObject is an Object: ", isObject(myObject))
Array
const myArray = [];const isArray = variable => Array.isArray(variable)console.log("myArray is an Array: ", isArray(myArray))
Number, String, Boolean and Function
For these 4, it’s more simple. We just need a typeof following === and their type as string to make the condition.
const myNumber = 12;
const myString = "js";
const myBoolean = true;
const myFunction = () => "hello";const isNumber = variable => typeof variable === 'number'
const isString = variable => typeof variable === 'string'
const isBoolean = variable => typeof variable === 'boolean'
const isFunction = variable => typeof variable === 'function'console.log("myNumber is an Number: ", isNumber(myNumber))
console.log("myString is an String: ", isString(myString))
console.log("myBoolean is an Boolean: ", isBoolean(myBoolean))
console.log("myFunction is an Function: ", isFunction(myFunction))
Null and Undefined
Because null == undefined
is true, the bellow code will catch both null
and undefined
.
const myNull = null;const isNullOrUndefined = variable == null;console.log("MyNull null or undefined:" ,isNullOrUndefined(myNull))
which is 100% equivalent to the more explicit but less concise:
if (variable === undefined || variable === null)
Note: We are not using typeof on purpose because this solution above will cause a ReferenceError if the variable doesn't exist. This is a good thing. This ReferenceError is desirable in order to help and find any mistakes and fix them before shipping your code.
Summary
Object variable.constructor === ObjectArray Array.isArray(variable)Number typeof variable === 'number'String typeof variable === 'string'Boolean typeof variable === 'boolean'Function typeof variable === 'function'Null Or Undefined variable == null;Strictly Undefined Or Null
variable === undefined || variable === null