I know that below are the two ways in JavaScript to check whether a variable is not null
, but I’m confused which is the best practice to use.
Should I do:
if (myVar) {...}
or
if (myVar !== null) {...}
I know that below are the two ways in JavaScript to check whether a variable is not null
, but I’m confused which is the best practice to use.
Should I do:
if (myVar) {...}
or
if (myVar !== null) {...}
Have a read at this post: http://enterprisejquery.com/2010/10/how-good-c-habits-can-encourage-bad-javascript-habits-part-2/
It has some nice tips for JavaScript in general but one thing it does mention is that you should check for null like:
It also mentions what's considered 'falsey' that you might not realise.
The two conditional statements you list here are not better than one another. Your usage depends on the situation. You have a typo by the way in the 2nd example. There should be only one equals sign after the exclamation mark.
The 1st example determines if the value in myVar is true and executes the code inside of the {...}
The 2nd example evaluates if myVar does not equal null and if that case is true it will execute your code inside of the {...}
I suggest taking a look into conditional statements for more techniques. Once you are familiar with them, you can decide when you need them.