简体   繁体   中英

Is there any difference in using !! vs using checks for null | undefined? in javascript/typescript

I was wondering if there is any difference when using ! vs checks like isNullOrUndefined or even custom checks like

customIsNullOrUndefined(obj: any) { return obj === null || obj === undefined;}

vs

!obj

vs

util.isNullOrUndefined(obj)

I know that util.isNullOrUndefined is deprecated

I mean semantically !obj should return the same as the checks for null | undefined

!obj will evaluate to true for any falsy value . That means null or undefined , but also things like 0 or "" . You can use this if you're sure you're only checking objects and not primitive values.

The not operator of ! determines whether a value is falsy, which includes the following:

  • false
  • 0
  • undefined
  • null
  • ''

If a function checks for null or undefined , then it will not check for other falsy values, such as false , for example.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM