As others have said, if (value) will already check for empties and nulls and stuff.
However, people (aka me) tend to forget or get confused about how truthy and falsy work in Javascript, or sometimes I need to check that a variable is not null or undefined, but 0 is an acceptable value. Therefore, I like to create helper functions that make the exact check I want explicit.
Here's an example of what I mean.
constexists=value=>value!=null// checks for null and undefined.constisEmpty=value=>value.length>0if(exists(tokenInfo)&&!isEmpty(tokenInfo)){...}
Now it's obvious that I'm checking whether tokenInfo is defined (and that means at this point it could be not), and whether it is empty.
Then I can use the classic if (tokenInfo) for actual boolean checks only and avoid having to remember whether it is a boolean check or a truthy/falsy check.
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
As others have said,
if (value)
will already check for empties and nulls and stuff.However, people (aka me) tend to forget or get confused about how truthy and falsy work in Javascript, or sometimes I need to check that a variable is not
null
orundefined
, but0
is an acceptable value. Therefore, I like to create helper functions that make the exact check I want explicit.Here's an example of what I mean.
Now it's obvious that I'm checking whether
tokenInfo
is defined (and that means at this point it could be not), and whether it is empty.Then I can use the classic
if (tokenInfo)
for actual boolean checks only and avoid having to remember whether it is a boolean check or a truthy/falsy check.