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

前端 未结 30 3629
眼角桃花
眼角桃花 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-21 23:59

    The probably shortest answer is

    val==null || val==''
    

    if you change rigth side to val==='' then empty array will give false. Proof

    function isEmpty(val){
        return val==null || val==''
    }
    
    // ------------
    // TEST
    // ------------
    
    var log = (name,val) => console.log(`${name} -> ${isEmpty(val)}`);
    
    log('null', null);
    log('undefined', undefined);
    log('NaN', NaN);
    log('""', "");
    log('{}', {});
    log('[]', []);
    log('[1]', [1]);
    log('[0]', [0]);
    log('[[]]', [[]]);
    log('true', true);
    log('false', false);
    log('"true"', "true");
    log('"false"', "false");
    log('Infinity', Infinity);
    log('-Infinity', -Infinity);
    log('1', 1);
    log('0', 0);
    log('-1', -1);
    log('"1"', "1");
    log('"0"', "0");
    log('"-1"', "-1");
    
    // "void 0" case
    console.log('---\n"true" is:', true);
    console.log('"void 0" is:', void 0);
    log(void 0,void 0); // "void 0" is "undefined" - so we should get here TRUE

    More details about == (source here)

    BONUS: Reason why === is more clear than ==

    To write clear and easy understandable code, use explicite list of accepted values

    val===undefined || val===null || val===''|| (Array.isArray(val) && val.length===0)
    

    function isEmpty(val){
        return val===undefined || val===null || val==='' || (Array.isArray(val) && val.length===0)
    }
    
    // ------------
    // TEST
    // ------------
    
    var log = (name,val) => console.log(`${name} -> ${isEmpty(val)}`);
    
    log('null', null);
    log('undefined', undefined);
    log('NaN', NaN);
    log('""', "");
    log('{}', {});
    log('[]', []);
    log('[1]', [1]);
    log('[0]', [0]);
    log('[[]]', [[]]);
    log('true', true);
    log('false', false);
    log('"true"', "true");
    log('"false"', "false");
    log('Infinity', Infinity);
    log('-Infinity', -Infinity);
    log('1', 1);
    log('0', 0);
    log('-1', -1);
    log('"1"', "1");
    log('"0"', "0");
    log('"-1"', "-1");
    
    // "void 0" case
    console.log('---\n"true" is:', true);
    console.log('"void 0" is:', void 0);
    log(void 0,void 0); // "void 0" is "undefined" - so we should get here TRUE

提交回复
热议问题