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

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

Related

Can I use double equal in JavaScript if one of the elements is a string? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I'm newbie in JS, I know that == double comparation for equality and === triple one for equality and type. My teacher says that I should use always triple. However, I don't see any down effect if I use double equal when one of the elements is a string.
'' == 0 // true
'10' == 10 // true
'dog' == 'cat' // false
So, I'm using always double equal when some of the element is a string (avoiding this 'false' == false) and triple when I'm detecting null or undefined.
Is there any down side for my approach?
I checked this previous answer: Which equals operator (== vs ===) should be used in JavaScript comparisons?
Using my personal working experience as a basis, I have never user the abstract equality operator(==) over the strict equality operator(===).
Since the == operator may have some unpredictable behavior, like
'0' == false // true
While
'0' === false // false
The second case is normally what you want your code to do.
Also, the == operator is more performance-costly than the === operator.
You can read more about this on the ecmaScript documentation:
The Equals(==) Operator: https://www.ecma-international.org/ecma-262/5.1/#sec-11.9.1
The Abstract Equality Comparison Algorithm: https://www.ecma-international.org/ecma-262/5.1/#sec-11.9.3
The Strict Equals(===) Operator: https://www.ecma-international.org/ecma-262/5.1/#sec-11.9.4
The Strict Equality Comparison Algorithm: https://www.ecma-international.org/ecma-262/5.1/#sec-11.9.6 (these two comparison algorithm probably will clarify to you why the strict equality is better on performance)
If you read the linked answer, you also read this chunk of code involving strings:
'' == '0' // false
0 == '' // true
0 == '0' // true
false == 'false' // false
false == '0' // true
Those are string, but still the behaviour is not exactly what you may expect. Indeed using === can make your life easier as your teacher said :)
If you use '10' == 10 , then the js interpreter must do a type conversion. This costs a little performance.
If you are using code quality tools like sonarqube, you will get some 'hints' to fix it.
It depends on the ocassion.
For example if you try to check if 9 == '9' it would return true, but they are in fact different, because one of then is a word(string) and the other is number(integer). In some of the cases that would make you suffer later.
The best scenario is to know what you are expecting it to be - is it a string, integer or something else and use the === or atleast check the type of the variable.

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

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.

Double-negation + logical and in Javascript [duplicate]

This question already has answers here:
Why don't logical operators (&& and ||) always return a boolean result?
(9 answers)
Closed 7 years ago.
I just ran across this code
var someBool = !!(o.a && o.a.t);
I was about to remove the double-negation, then realized it forces someBool to be a boolean value... Looking on the MDN, I find this example
a5 = "Cat" && "Dog"; // t && t returns "Dog"
This seems atypical based on my experience in other languages. I'd expect the logical and operation to always return a boolean value. Can anyone explain why this use case is supported in Javascript?
Also, is the code that sent me in this direction the best way to force a bool around logical and? I'm aware of new Boolean, but that doesn't return a primitive type like the double-negation, so perhaps that's the way to go?
The && and || operators have an effect similar to boolean AND and OR, but they don't affect the expression value. The expressions are evaluated and the values tested with the JavaScript "truthiness" rules, but the overall expression value is that of the actual operand expressions (well, one of them).
Yes, that's different from C and Java and etc. JavaScript is a different language with its own rules.
The Boolean constructor can be called without new to perform a "truthiness" test and return a boolean primitive. Using !! is fairly idiomatic however.

There's difference between "$var === true" and "true === $var"? [duplicate]

This question already has answers here:
What is a reason of placing boolean or null before comparison operator?
(3 answers)
Closed 8 years ago.
A few time ago, I saw in a JavaScript application (I don't remember which one is) the use of true === $var instead of $var === true. Example:
if (true === $var) {
// do something
}
I think these comparisons are differnet but I can see why — someone can explain it for me? And plus: when I should use and when I shouldn't.
Duplicated?
I searched on the web but no results.
There is no difference between them.
Yoda comparisons are done by some people to prevent a typo (missing =s) creating an assignment instead of a comparison (since true = $var will throw an error while $var = true will not).
I think this is just a best practice kind of thing, at least I'm used to seeing the suggestion when coding in languages such as C#, where it's easy to accidentally do
if(someVar = 1)
instead of:
if(someVar == 1)
Doing it in reverse prevents that possibility, as the compiler will pick up the fact that you can't assign the value of a variable to a literal (or constant, if you use constants).
No there is not any difference in both
But there is difference in $var == false and $var === false
$var = 0;
$var == false // TRUE
$var === false // FALSE
=== will also compare the variable type. It checks if it's a bool, string or integer for example.
$var = "1";
$var == 1 // TRUE
$var === 1 // FALSE

Triple (3) Equal Signs [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
JavaScript === vs == : Does it matter which “equal” operator I use?
I asked another question here and received a great answer as follows:
$(document).on("keydown", function (e) {
if (e.which === 8 && !$(e.target).is("input, textarea") || $(e.target).is('[readonly]')) {
e.preventDefault();
}
});
Notice the three equal signs === in the if-statement. I have always thought you only needed two equal signs == for a javascript/jQuery if-statement. Is there any reason for the three?
UPDATE
Sorry for the duplicate question - I searched but didn't find any good questions. I guess I was using the wrong search terms.
The triple equal sign in javascript means equality without type coercion.
For example:
1=="1" // true, automatic type coercion
1==="1" // false, not the same type.
Three equal signs indicates both the value and type are equal.

Categories

Resources