Checking if a variable exists in javascript

后端 未结 7 1156
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:56

    It is important to note that 'undefined' is a perfectly valid value for a variable to hold. If you want to check if the variable exists at all,

    if (window.variableName)
    

    is a more complete check, since it is verifying that the variable has actually been defined. However, this is only useful if the variable is guaranteed to be an object! In addition, as others have pointed out, this could also return false if the value of variableName is false, 0, '', or null.

    That said, that is usually not enough for our everyday purposes, since we often don't want to have an undefined value. As such, you should first check to see that the variable is defined, and then assert that it is not undefined using the typeof operator which, as Adam has pointed out, will not return undefined unless the variable truly is undefined.

    if ( variableName  && typeof variableName !== 'undefined' )
    

提交回复
热议问题