Checking if a variable exists in javascript

后端 未结 7 1148
Happy的楠姐
Happy的楠姐 2021-01-31 06:58

I know there are two methods to determine if a variable exists and not null(false, empty) in javascript:

1) if ( typeof variableName !== \'undefined\' && v

7条回答
  •  清歌不尽
    2021-01-31 07:37

    If you want to check if a variable (say v) has been defined and is not null:

    if (typeof v !== 'undefined' && v !== null) {
        // Do some operation  
    }
    

    If you want to check for all falsy values such as: undefined, null, '', 0, false:

    if (v) {
       // Do some operation
    }
    

提交回复
热议问题