actually, the best approach would be to check if a value is falsy
, and based on MDN this is the list of falsy values:
- false The keyword false
- 0 The number zero
- 0n BigInt, when used as a boolean, follows the same rule as a Number. 0n is falsy.
"", '', ``
This is an empty string (the length of the string is zero). Strings in JavaScript can be defined with double quotes "", single quotes '', or Template literals ``.
null null - the absence of any value
- undefined undefined - the primitive value
- NaN NaN - not a number
so based on your code what you can do is simply:
if (!x) { // check for all the falsy values.
// do stuff with x
}
in the other hand, you ask for the difference of !=
and !==
, well basically taking some examples you can see the difference:
0 == false // true, because false is equivalent of 0
0 === false // false, because both operands are of different type
2 == "2" // true, auto type coercion, string converted into number
2 === "2" // false, since both operands are not of same type
as mentioned by @VLAZ comment, these cases will only work if the variable x
is defined, otherwise you will have the following error:
"Uncaught ReferenceError: x is not defined"
so on your case you could only use !=
because you will compare string
vs string
and you will avoid having to check if the variable was or not created.
if (typeof x != "undefined") {
// do stuff with x
}