Search code examples
javascriptarraysobjectis-emptyisnullorempty

check for empty values in JavaScript for datatypes like Array, Object, String and Number


I need to check whether enter parameter is empty or not like php empty function works.

For example, if I have function with name isEmpty and I passed string as parameter to it then function will return true if string is empty else false and similar for other datatypes like Object, Array and Number.


Solution

  • let isEmpty = param => {
    	let isAnObject = (obj) => {
    		if (obj == null) return false;
    		return obj.constructor.name.toLowerCase() === "object"
    	}
    	if (Array.isArray(param)) {
    		return !param.length;
    	}
    	if (isAnObject(param)) {
    		return !Object.keys(param).length;
    	}
    	return !param;
    }
    console.log('Is empty Array: ',isEmpty([]));
    console.log('Is empty Array: ',isEmpty([1,2,3]));
    console.log('Is empty Object: ',isEmpty({}));
    console.log('Is empty Object: ',isEmpty({a: 'I am not empty'}));
    console.log('Is empty String: ',isEmpty(''));
    console.log('Is empty String: ',isEmpty('I am string'));
    console.log('Is empty Number: ',isEmpty(NaN));
    console.log('Is empty Number: ',isEmpty(100));
    console.log('Is empty String parse as number: ',isEmpty(parseInt('')));

    I have created a function and named it as isEmpty. This function will return true if passed parameter is empty else false.