function isEmpty(value) { if (value === undefined) { return true; } if (value === null) { return true; } if (typeof value === 'string' && /^[\s\u00A0]*$/.test(value)) { return true; } if (Array.isArray(value) && value.length === 0) { return true; } if (typeof value === 'object' && Object.keys(value).length === 0) { return true; } if (typeof value === 'number' && isNaN(value)) { return true; } if (value instanceof Date && isNaN(value.getTime())) { return true; } if (typeof value === 'boolean' && !value) { return true; } if (typeof value === 'function') { return true; } // Treat any other object as non-empty if (typeof value === 'object') { return false; } return false; } // Usage var moment = require('moment'); var variable1; console.log(isEmpty(variable1)); // true var variable2 = null; console.log(isEmpty(variable2)); // true var variable3 = 'Hello'; console.log(isEmpty(variable3)); // false var variable4 = 0; console.log(isEmpty(variable4)); // true var variable5 = '0'; console.log(isEmpty(variable5)); // true var variable6 = ' '; console.log(isEmpty(variable6)); // true var variable7 = '\t\t'; console.log(isEmpty(variable7)); // true var variable8 = '\n'; console.log(isEmpty(variable8)); // true var variable9 = []; console.log(isEmpty(variable9)); // true var variable10 = {}; console.log(isEmpty(variable10)); // true var variable11 = new Date('Invalid Date'); console.log(isEmpty(variable11)); // true var variable12 = function() { // Function body }; console.log(isEmpty(variable12)); // true var variable13 = moment('2023-07-10', 'YYYY-MM-DD'); console.log(isEmpty(variable13)); // false var variable14 = false; console.log(isEmpty(variable14)); // true var variable15 = { foo: 'bar' }; console.log(isEmpty(variable15)); // false
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter