How to check for an undefined or null variable in JavaScript?

前端 未结 24 2290
悲&欢浪女
悲&欢浪女 2020-11-22 15:55

We are frequently using the following code pattern in our JavaScript code

if (typeof(some_variable) != \'undefined\' && some_variable != null)
{
             


        
24条回答
  •  星月不相逢
    2020-11-22 16:33

    Firstly you have to be very clear about what you test. JavaScript has all sorts of implicit conversions to trip you up, and two different types of equality comparator: == and ===.

    A function, test(val) that tests for null or undefined should have the following characteristics:

     test(null)         => true
     test(undefined)    => true
     test(0)            => false
     test(1)            => false
     test(true)         => false
     test(false)        => false
     test('s')          => false
     test([])           => false
    

    Let's see which of the ideas here actually pass our test.

    These work:

    val == null
    val === null || val === undefined
    typeof(val) == 'undefined' || val == null
    typeof(val) === 'undefined' || val === null
    

    These do not work:

    typeof(val) === 'undefined'
    !!val
    

    I created a jsperf entry to compare the correctness and performance of these approaches. Results are inconclusive for the time being as there haven't been enough runs across different browsers/platforms. Please take a minute to run the test on your computer!

    At present, it seems that the simple val == null test gives the best performance. It's also pretty much the shortest. The test may be negated to val != null if you want the complement.

提交回复
热议问题