How can I determine if a variable is 'undefined' or 'null'?

前端 未结 30 1869
耶瑟儿~
耶瑟儿~ 2020-11-22 03:30

How do I determine if variable is undefined or null?

My code is as follows:

var EmpN         


        
30条回答
  •  执笔经年
    2020-11-22 03:57

    I know I'm 10 years late. But I'll leave my answer here just in case anybody needs a short method.

    Installing Lodash in your project could be useful because of the helper functions that could come in handy in these situations.

    Using ES6 modules, import would look like this:

    import isNull from 'lodash/isNull';
    
    import isUndefined from 'lodash/isUndefined';
    
    import isNil from 'lodash/isNil';
    

    Would be better if only the used functions are imported.

    Lodash's isNull checks if value is null.

    const value = null;
     
     if(isNull(value)) {
        // do something if null
     }
    

    lodash's isUndefined checks if value is undefined.

    const value = undefined;
    
    if(isUndefined(value)) {
       // do something if undefined.
    }
    

    isNil Checks if value is null OR undefined. I prefer this method over other two, because it checks both undefined and null.

提交回复
热议问题