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

前端 未结 30 3577
眼角桃花
眼角桃花 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:01

    This is the safest check and I haven't seen it posted here exactly like that:

    if (typeof value !== 'undefined' && value) {
        //deal with value'
    };
    

    It will cover cases where value was never defined, and also any of these:

    • null
    • undefined (value of undefined is not the same as a parameter that was never defined)
    • 0
    • "" (empty string)
    • false
    • NaN

    Edited: Changed to strict equality (!==) because it's the norm by now ;)

提交回复
热议问题