Skip to main content

Check If Object Is Not Null In Javascript Guide

Check If Object Is Not Null In Javascript Guide

In JavaScript, typeof null famously returns "object" , which is a historical bug. To verify that a variable is a non-null object (and not an array or other primitive), use a combined check: javascript

if (myObject != null) { // Runs if myObject is neither null nor undefined } Use code with caution. Copied to clipboard 3. Validating it is Truly an Object Check If Object Is Not Null In Javascript

const isRealObject = (val) => typeof val === 'object' && val !== null && !Array.isArray(val); if (isRealObject(myObject)) { // Safely work with object properties } Use code with caution. Copied to clipboard 4. Simple Truthiness Check How to check if a Variable Is Not Null in JavaScript In JavaScript, typeof null famously returns "object" ,

However, because of how JavaScript handles different "empty" types, the best approach depends on whether you also want to exclude undefined or ensure the variable is actually a valid object. 1. Strict Not-Null Check Validating it is Truly an Object const isRealObject