Is there a standard function to check for null, undefined, or blank variables in JavaScript?

前端 未结 30 3624
眼角桃花
眼角桃花 2020-11-21 23:37

Is there a universal JavaScript function that checks that a variable has a value and ensures that it\'s not undefined or null? I\'ve got this code,

30条回答
  •  一整个雨季
    2020-11-22 00:16

    If you want to avoid getting true if the value is any of the following, according to jAndy's answer:

    • null
    • undefined
    • NaN
    • empty string ("")
    • 0
    • false

    One possible solution that might avoid getting truthy values is the following:

    function isUsable(valueToCheck) {
        if (valueToCheck === 0     || // Avoid returning false if the value is 0.
            valueToCheck === ''    || // Avoid returning false if the value is an empty string.
            valueToCheck === false || // Avoid returning false if the value is false.
            valueToCheck)             // Returns true if it isn't null, undefined, or NaN.
        {
            return true;
        } else {
            return false;
        }
    }
    

    It would be used as follows:

    if (isUsable(x)) {
        // It is usable!
    }
    // Make sure to avoid placing the logical NOT operator before the parameter (isUsable(!x)) and instead, use it before the function, to check the returned value.
    if (!isUsable(x)) {
        // It is NOT usable!
    }
    

    In addition to those scenarios, you may want to return false if the object or array is empty:

    • Object: {} (Using ECMA 7+)
    • Array: [] (Using ECMA 5+)

    You would go about it this way:

    function isEmptyObject(valueToCheck) {
        if(typeof valueToCheck === 'object' && !Object.keys(valueToCheck).length){
            // Object is empty!
            return true;
        } else {
            // Object is not empty!
            return false;
        }
    }
    
    function isEmptyArray(valueToCheck) {
        if(Array.isArray(valueToCheck) && !valueToCheck.length) {
            // Array is empty!
            return true;
        } else {
            // Array is not empty!
            return false;
        }
    }
    

    If you wish to check for all whitespace strings (" "), you may do the following:

    function isAllWhitespace(){
        if (valueToCheck.match(/^ *$/) !== null) {
            // Is all whitespaces!
            return true;
        } else {
            // Is not all whitespaces!
            return false;
        }
    }
    

    Note: hasOwnProperty returns true for empty strings, 0, false, NaN, null, and undefined, if the variable was declared as any of them, so it might not be the best to use. The function may be modified to use it to show that it was declared, but is not usable.

提交回复
热议问题