Checking if a variable exists in javascript

后端 未结 7 1146
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:39

    if (variable) can be used if variable is guaranteed to be an object, or if false, 0, etc. are considered "default" values (hence equivalent to undefined or null).

    typeof variable == 'undefined' can be used in cases where a specified null has a distinct meaning to an uninitialised variable or property. This check will not throw and error is variable is not declared.

提交回复
热议问题