Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it necessary to use double exclamation points (!!) in order to make sure that an object is not null? [duplicate]

Tags:

javascript

I've recently started using double exclamation points !! before an object to make sure that it's not null and that it's not undefined and not an empty string, to make sure that I encompass all the different ways that a variable can be empty.

Is this necessary? It's hard to read, for instance: if(!!name) vs if(name)

Any opinions on this? I want my code to be safe and not get into conditions where a null pointer exception and other things can occur, but I also want my code to be readable.

like image 946
reectrix Avatar asked Dec 02 '22 14:12

reectrix


1 Answers

What you're doing is already done by JavaScript natively.

if( value ) { }

will evaluate to true as long as value is not:

  • null
  • undefined
  • NaN
  • empty string ("")
  • 0
  • false

Check out the toboolean conversions in the specification.

like image 124
Bricky Avatar answered Jan 19 '23 00:01

Bricky