Is using == instead of === ok for null/undefined? [duplicate] - javascript

This question already has answers here:
How can I determine if a variable is 'undefined' or 'null'?
(34 answers)
Which equals operator (== vs ===) should be used in JavaScript comparisons?
(48 answers)
Closed 3 years ago.
I currently have a variable that can be null as well as undefined. In both cases I want to leave the function:
if (myvar==null) return;
this works fine but I retrieve warnings from my IDE (VS) because == does not care about the type while === does. I am aware that == is generally be seen as bad style because of this.
Is this the exception from the rule? Should I simply ignore this warning and stick to the better readability or would the following be the recommend action?
if (myvar===null || myvar===undefined) return;

The problem is the lack of clarification.
If you're writing the code for yourself, it's fine as you know exactly what you're doing. But if a contributor find this code, they could either:
Not knowing how == works in case of null / undefined
Knowing how it works but not knowing if the use was intentional (if you actually want to check both null or undefined, or you wanted just check for null but used ==)
The code should be clear, so often you find programmers adding comments before this check to specify that yes, they know what they're doing, and yes, it was intentional.
Eventually you get tired of that and start to use myvar === null || myvar === undefined.
It's more verbose, but it's clearer, and doesn't give room to misunderstanding.
Another thing I notice is creating custom fuction for such things, e.g. isNil(myvar) but despite the verbosity I prefer checking both values.

== has very specific rules, and it normally recommended against because those rules are not intuitive. I would only condone using it if you have memorized the rules related to its behavior, as have all other devs who could possibly have to deal with your code (which most have not).
In this case, a == null returns true if a is one of null, undefined, or document.all, but not the other 4 falsely JS values (MDN, including why document.all is falsely). So unless you want it to match document.all, I would use ===.
Additionally, using === in all places adds consistency to your code.

Related

Using !! in if statements [duplicate]

This question already has answers here:
What is the !! (not not) operator in JavaScript?
(42 answers)
Closed 2 years ago.
I have come across code in a web app where it uses !!, I was told that this enforces a check for true or false instead of truthy or falsy. Is this correct?
if (!!this._currentItemIndex) {
this._findItemByCurrentIndex();
}
I have been having trouble finding any resources online to explain this.
Normally you'll see code like:
let x = !!y;
Where this is casting whatever value y has into a simple true or false outcome, a boolean. This is often employed to avoid retaining references to things you don't need, like y could be a complex structure but you don't care about the details, you just want to track if it was assigned.
It's unusual to see this employed in an if since it really doesn't do anything useful. It converts to a boolean, but if will anyway. This is just junk code.
It might as well be if (!!!!!!!!!!!!!!!!!!!!x) for all the good it does.
A better version would look like:
if (this._currentItemIndex) {
// Some non-zero value was assigned
}
Or if it is populated:
if (this._currentItemIndex > 0) {
// Communicates intent better
}

Why "if(!!variable)" instead of "if(variable)"? [duplicate]

This question already has answers here:
What is the difference between if(!!condition) and if(condition)
(3 answers)
When to use the double not (!!) operator in JavaScript
(2 answers)
Why use if (!!err)?
(3 answers)
Closed 6 years ago.
In someone else's code I found this way to test the existence of a variable :
if(!!variable) {
//Do something
} else {
//Something else
}
Is there a reason to test with if(!!variable) instead of if(variable) ? Is it a good practice?
Is there a reason to test with if(!!variable) instead of if(variable)?
No.
Using if() will coerce the condition to a boolean anyway, there's no need to manually do it. Using this sort of syntax makes sense when you want to guarantee you've got a boolean elsewhere, for example if you wanted to log the truthiness of the expression:
console.log(!!variable)
This will ensure that you get either true or false logged, rather than the original value of the variable. But inside an if? It makes no difference.
No, in the case of a if, their is usually no reason to write that in JS.
I would not call it bad practice, since it can often come from programmer coming from strongly typed language, and is a common quick way to do the conversion to bool in thoses language.
It can also be used to emphasise the importance of the truthiness of the value in a long if, and show the programmer didn t forget to put the condition.
TL:DR: As for a lot of things: it may not be good practice, but it only become bad practice if your team is not used to that practice, either train them, document, or leave it.
Double negation is a bit of a hacky way (IMHO) to convert a variable to bool. using ! on variable coerces it to a bool and negates it, and using it again convert it back to the 'correct' value. So !!0 === false
As mentioned by James there is no reason to do this inside an if statement. The only reason really to do this would be to coerce to a bool for logging purposes or similar so the value logged is true or false rather than 0, an empty string etc
Double ! (!!) is not an operator. It's just ! twice - double negation.

Javascript: What is additional Zero in the if syntax? [duplicate]

This question already has answers here:
What does `void 0` mean? [duplicate]
(3 answers)
Closed 8 years ago.
I have been reading the javascript source of my company project and came across this
if (options.parse === void 0) options.parse = true;
Not sure what 0 does here?
The void operator is very interesting: It accepts an operand, evaluates it, and then the result of the expression is undefined. So the 0 isn't extraneous, because the void operator requires an operand.
People use void 0 sometimes to avoid the fact that the undefined symbol can be overridden (if you're not using strict mode). E.g.:
undefined = 42;
Separately, the undefined in one window is not === the undefined in another window.
So if you're writing a library and want to be a bit paranoid, either about people redefining undefined or that your code may be used in a multi-window situation (frames and such), you might not use the symbol undefined to check if something is undefined. The usual answer there is to use typeof whatever === "undefined", but === void 0 works (well, it may not work in the multi-window situation, depending on what you're comparing it to) and is shorter. :-)

difference between if (!!variable), and, if (variable)? [duplicate]

This question already has answers here:
Can someone explain this 'double negative' trick? [duplicate]
(9 answers)
Closed 9 years ago.
Is there any difference (in JS) between using the double negative !! and not using it at all?
For example
if (!!variable){... vs. if (variable){...
I know there are times where I've gotten a warning using the 2nd method..
When should each be used? and when will each throw a warning in the console? (for variables, objects, arrays etc.)
Thanks!!
There is a difference for assigning it, but not for using it in a conditional statement. The reason the !! is used is because the first ! will convert your variable to its truthy evaluation and then not it. So "hello" becomes true, is then negated, becomes false, and the second ! will negate the false, resulting in true. This can be desirable when trying to obtain the thruthy value from a variable. However, there is not much gained by doing it in an if statement.
In this particular case, there is no difference. In fact, !!variable is wasteful.
However in more general cases, it casts the variable to a boolean. Personally I've only found this useful when debugging, and to learn what values are truthy and falsy.

Which JavaScript equality operator (== or ===) is faster? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
JavaScript === vs == : Does it matter which “equal” operator I use?
I always assumed that == is faster than === operator. But after some reading I am confused.
Is there any benefit at performance level if I use === over == operator?
The === operator will be faster than the == operator. This is because === doesn't need to check multiple comparisons, while == does (i.e., == performs conversions).
return "true" == true; //true
The above will first test to see if "true" === true which is false, then check "true" === "true" (i.e., it converts the bool to a string, then checks again).
Read the comments below. You can also look at these two benchmarks as sort of guides:
http://jsperf.com/2-vs-3-eq
http://jsperf.com/2-vs-3-eq-2
For future reference, though, they really aren't the same thing and you shouldn't use them interchangeably. In fact, there aren't many any cases you'd really want to use == over ===. It'll usually lead to unexpected or seemingly random results while the main point of programming is to create an interface your user can travel on. With conditions that don't always evaluate to what you originally test for, programs can turn out to be buggy, messy, or unreliable.
While the === operator might perform faster than ==, it's really hard to distinguish the speed difference in most cases so you can freely use whichever of those two options makes your code clearer.
You can try with === operator is faster

Categories

Resources