Does it make sense to use === for string comparison in JavaScript? - javascript

While it's clear how using the === operator for e.g. numbers is useful (0, null and undefined all being falsy values, which can lead to confusion), I'm not sure if there are benefits to using === for string comparisons.
Some of my team mates use this operator for all comparisons, but does it really make sense? Is there at least some minor performance impact?

If you know the types are the same, then there's no difference in the algorithm between == and ===.
That said, when I see ==, I assume that I'm using it for its type coercion, which makes me stop and analyze the code.
When I see === I know that there's no coercion intended, so I don't need to give it a second thought.
In other words, I only use == if I intend for there to be some sort of type coercion.

It is considered good practice to always use === for comparisons in JavaScript. Since JavaScript is a dynamic language, it is possible that what you think are two strings could be variables with different types.
Consider the following:
var a = "2", b = 2;
a == b // true
a === b // false
The only way to guarantee a false result in this case would be to use === when comparing the two values.

Related

In JavaScript, is there any difference between typeof x == 'y' and typeof x === 'y'?

I'm aware of the difference between strict and loose comparison operators. Clearly x == y is different from x === y. But whenever I see code that uses typeof, it always uses ===.
If the typeof operator always evaluates to a string (such as 'boolean', 'number', etc.), then wouldn't typeof x == 'y' and typeof x === 'y' always render the same result? And if so, why the use of ===?
I know it's faster doing strict comparisons, but except in extreme cases, the performance gain should be imperceptible. Another idea is that it's just clearer to always use === since it does cause issues with similar operations like x == undefined versus x === undefined. Is it worthwhile to reduce these cases to == to improve minification and transfer encoding, or is it better to keep === to maintain runtime performance and general clarity?
It makes absolutely no useful difference either way in this case.
The typeof operator returns a string indicating the type of the unevaluated operand.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof
We know it is always going to be a string, and it will only be that of a few predefined values, so there is no explicit reason to use the strict operator when comparing the results of typeof, however the strict comparison operator should be used for readability, and to avoid any possible exceptions to that statement.
But
Loose equality using ==
Loose equality compares two values for equality, after converting both values to a common type.
That being said it should be marginally faster to use the strict comparison as there is no conversion, but the difference is so small that it doesn't matter, and micro optimizing is a very bad thing
Edit
According to the documentation 11.9.3 and 11.9.6 if they are the same type there should be no difference.

What is the difference between a comparison operator and a logical operator?

EDIT This question has been answered, but I've chosen to clarify it for future readers.
I've studied the explanations given about the logical operator !(parameter) and the inequality operator !==. They do not though clarify in what way they differ from each other. Let's look at an example.
!($.inArray(latlng, markers) == -1)
and
$.inArray(latlng, markers) !== -1
What is the difference between theese two expressions and are there any performance issues with either of the solutions making the other more preferable?
In your case there is no difference [due to aforementioned De Morgan's law], so stick to what is more readable to you.
Worth adding:
Comparison operators are binary operators -> have a arity value of 2, because they compare two things.
On the other hand, the negation operator (!) has arity one, because it negates its only argument to its boolean counterpart -> its image is thus [true, false].
This is why you may encounter !!foo in your programmer's life as a way to coerce foo to a boolean.
There really isn't a whole lot of difference, just the order that the logic operates. The first statement checks if they are equal and then gives you the opposite result. The second checks to see if they are different by comparing the values to see if they are the same and returning false if they are.
In effect, they are the same. There is actually something called DeMorgan's Law that governs the equality between comparison and logical operators (i.e. stating that they are equivalent and can be exchanged for others that have the same result in a different structure)
Comparison: take two values and compare them. We could ask various questions, for example:
are these two values "the same", we use == for that
is this value bigger than that value, >
is this value bigger than or equal to that, >=
The result of each of this is a boolean value. So we could write:
boolean areTheyEqual = ( x == y );
So aretheyEqual would be "true" if x was equal to y. Now suppose you wanted a variable "areTheyDifferent". We could get that in two ways, either using the "not" operator, which works on a boolean value:
boolean areTheyDifferent = ! areTheyEqual;
or we could use the "notEqual" comparison
boolean areTheyDifferent = ( x != y );
So the ! operator takes a boolean value and "inverts" it. You need to read the
!=
as a single comparison operator, just like >= is a single operator
Comparison operators are used in logical statements to determine equality or difference between variables or values. eg x!=y
Logical operators are used to determine the logic between variables or values.
eg !(x==y)

Use === to check whether String.replace() actually performed a substitution?

I'd like to know whether String.replace() actually found a match and performed a substitution. Since String.replace() returns the resulting string rather than the number of substitutions performed, it seems that I would have to compare the original with the result.
The question is, should I use === or == for that comparison?
As far as I can tell, neither the Mozilla documentation nor the ECMAScript 5.1 Standard specifies that the string that is returned must be the same object as the string that was passed in, if no match occurred.
On the other hand, it would seem stupid for any implementation of JavaScript to return a copy of an unchanged string.
In concrete terms, what happens with
var s = 'abc';
var t = s.replace(/d/, 'D');
console.log(s === t); // I expect true, but am not sure
Is it
Guaranteed to print true? If so, where is that behaviour documented?
Undefined and unreliable behaviour (i.e., I should test s == t instead, or do something clever with a replacement callback closure)?
Undefined behaviour that in practice returns true on every JavaScript implementation?
Edit
#cookiemonster asks:
So it seems that you're not really wondering if the result is guaranteed, but more whether an implementation is optimized to perform an identity comparison internally. Is that right?
Actually, I did screw up the question, and it ended up being an X-Y problem. What I really want to know is, how can I check whether any substitution occurred (the actual number of substitutions doesn't matter — one or more times are all the same)? And do so efficiently, without doing a separate .match() or a character-by-character comparison. And be certain that the result is guaranteed by the language specification.
=== won't work with a String object:
a = new String("foo")
a.replace(/XXX/, "") == a
> true
a.replace(/XXX/, "") === a
> false
or any object that has a custom toString method:
b = { toString: function() { return "foo" }}
"foo".replace(/XXX/, "") == b
> true
"foo".replace(/XXX/, "") === b
> false
Most of the time, this is a non-issue, but "praemonitus, praemunitus" as they say.
To answer your update: as seen here, at least V8 is optimized to return the subject itself if no replacements can be made:
int32_t* current_match = global_cache.FetchNext();
if (current_match == NULL) {
if (global_cache.HasException()) return isolate->heap()->exception();
return *subject; <-------
and, although the standard only requires two strings to look the same to be strict equal (===), I'm absolutely positive that every JS engine out there is smart enough to avoid strcmp on equal pointers.
It makes no difference.
Why? Because String.replace operates on strings, and returns a string. Also, strings are primitives, not objects.
You already know that you have two strings. == and === are therefore identical for this purpose. I'd even go so far as to say that === is superfluous.
The replace method on the String class always returns a string, so === is just as safe to use and reliable as == since no type coercion will happen. Secondly, if no substitution occurred, the === test will return true since they contain the same characters.
Given your example...
"Is it Guaranteed to print true? If so, where is that behaviour documented?"
Yes, it is. It's documented in the respective equality comparison algorithms used by == and ===.
Abstract Equality Comparison Algorithm
Strict Equality Comparison Algorithm
"Is it Undefined and unreliable behaviour (i.e., I should test s == t instead, or do something clever with a replacement callback closure)?"
No, it's well defined behavior. See above. The == and === operators will behave identically.
"Is it Undefined behaviour that in practice returns true on every JavaScript implementation?"
As long an implementation is following the specification, it will return true.

In Javascript, is it not recommended to use ==, and how to use ===? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Javascript === vs == : Does it matter which “equal” operator I use?
In Douglas Crockford's book Javascript: The Good Parts, it is recommended to not use == at all, due to hard to memorized rules. Do advanced or seasoned Javascript programmers really not use == or !=?
If so, then I guess we will be using === and !==, but then how do we use them effectively? Is the most common case comparing a string with number, so we can always do
if (Number(s) == 3) { ... } // s is a string
Can Number(s) work in most browsers? And what are the other common cases to use with ===?
The problem with == is that it uses type-coercion which can have unexpected results.
You nearly always want === or !==. You can explicitly change the types as appropriate. In your example it would be easier to write "3" as a string instead of converting the string to a number.
Never say never, but indeed, in most cases it is best to use the more strict === and !== operators, because they compare the value as well as the type.
Comparing '68' to 68 is not a problem, if it matches, it is probably what you meant. The big risk in not doing so lies especially in 'empty values'. Empty strings may be evaluated as false, as may 0 and 0.0. To prevent hard to find errors, it is best to do a strict type comparison as well.
If you want something to be true or false, it should be true or false and not any other value. Even in cases where these other types would be allowed, it may be better to explicitly convert it to the type you're comparing with, just for the sake of readability, maintanability and clarity. You are in that case making clear that you know the value can be of another type and that it is allowed so. With just using the less strict operator, no one can tell if you just forgot or made a deliberate choice.
So yes, I'd say it's a best practise to always use the strict operators, although there will always be exceptions.
=== is 'exactly equal to' where == is not exact.
For example,
'' == false // true
0 == false // true
false == false // true
'' === false // false
0 === false // false
false === false // true
== will return true for 'falsy' or 'truthy' values. Read this for more information.
A lot of developers will use ===. It does not hurt to use === solely. But in some cases === is not necessary. Crockford suggests a lot of things in his book. Some people follow his word to the T. Others, myself included, take it all with a grain of salt. He has some good points, but a lot of it is preference.
You should make sure you know exactly what == and === do. And with that information you can decide how to use them, and when.
== operator compares two operands values and returns a Boolean value.
=== This is the strict equal operator and only returns true if both the operands are equal and of the same type.
Example:
(2 == '2') //return true
(2 === '2') //return false

Javascript === (triple equals)

Give the following snippet
function countZeroes(array) {
function counter(total, element) {
return total + (element === 0 ? 1 : 0);
}
return reduce(counter, 0, array);
}
What does the === do?
Is reduce a built in function? What does it do?
Please explain the steps of this program.
It is the strict equality operator.
It compares two values and checks to see if they are identical according to the Strict Equality Comparison Algorithm.
This is opposed to ==, which will attempt to coerce one or both of the values being compared if they are of different types. That one uses the Absract Equality Comparison Algorithm.
The rules for the Abstract algorithm can be tricky. You're better off using === unless you have special need for ==.
From the MDC docs
The standard equality operators (== and !=) compare two operands without regard to their type. The strict equality operators (=== and !==) perform equality comparisons on operands of the same type. Use strict equality operators if the operands must be of a specific type as well as value or if the exact type of the operands is important. Otherwise, use the standard equality operators, which allow you to compare the identity of two operands even if they are not of the same type.
With regard to the code, this part:
(element === 0 ? 1 : 0)
...basically says if the value of element is exactly equal to 0, then use 1, otherwise use 0.
So to take that entire line:
return total + (element === 0 ? 1 : 0);
...the return value of the function will be total + 1 if element equals 0, otherwise the return value will be total + 0.
You could rewrite the code using an if-else statement:
if( element === 0 ) {
return total + 1;
} else {
return total + 0;
}
=== is the same as == except it doesn't cast variables
0 == '0' -> true
0 === '0' -> false
reduce isn't a built in function, but what it certainly does is run counter on each element of the array.
so for each element of the array the element is checked to be 0 and if it is the total is incremented.
=== is the identity operator, it's like ==, but does not perform type conversion.
this function appears to count the number of zeros in an array and return the count.
I assume that reduce() acts like Array.prototype.reduce
=== is strictly equal, both sides have to be of the same type and be equal. This is used to avoid the comparison of 2 unequal types (usually boolean false and a number 0)
The "===" is means "exactly equals", as in the value is the same, as is the type. So ...
var x = 5;
if (x === 5) {
alert("This will happen");
} else {
alert ("This won't");
}
It's rarely used.
The reduce function is likely the Array.prototype.reduce() method, which is used to apply a function to values in an array sequentially (sort-of). So, in this usage it is applying the 'counter' function to everything in the array, which will count the # of zeros in the array and return that.
Its a very good question and generally developer coming from other languages always have difficulty understanding the importance of using === as compare to ==
1. 5 == '5' //true why? Because it do
type conversion whereas in case with
=== 5 === '5'//false because '5' is a string as compare to number 5.
2. '\t\r\n' == 0 //true this lack of transitivity is alarming and cause
lot of errors.
3. Use JsLint ...it will help writing better JS code keep your code safe
from this kind of issues.
4. Moreover their is a performance penalty for using == when you are
comparing number with a string.
In my test it turns out that there is
little practical performance
difference between == and ===. While
the strict operator is marginally
faster (roughly 10%) in most browsers
when combined with explicit type
conversion, such as a === +b, the
only real performance gains will come
from avoiding type conversion
entirely. Converting a string to an
integer for comparison with another
integer is significantly slower (up
to 10x) than simple comparing two
integers. You should never allow
integers to be stored as strings
internally, as the type conversion
will incur a performance penalty.
While that was the basic takeaway from the numbers, I did find one interesting outlier when testing with Firefox. In Firefox, the comparison a === +b is about 20x slower than the equivalent a == b when a is an integer and b is a string integer. This result seems suspicious to me, and nothing similar occurred in any other browser. Oddly, when the Firebug script debugger is turned on, this result changes, and a === +b becomes about 10% faster than the other. I'm not sure what to make of this result, but it does serve as a reminder that integers should always be stored in numbers, not in strings.
see other answer about ===.
reduce it built in JS function which uses like "foreach", its moving on every elemnt in the array.
it start with the inital value, which in your case its zero, and then call to counter() and on the first element.
it check it, and return total(which is zero)+ 1 if the element is 0, after the returned value will be the "total" for the 2nd element in the array and so on....
in conclusion: the reduce call to counter on every element of the array,doing the test and adding its value to the (n-1)st element's returned value;
=== is a strict equality comparison. The == operator in JavaScript does type coercion, which often has surprising results, like how ' ' == false. So most JavaScript developers use === where possible.
Hard to tell about reduce(). That is not a built-in global function in JavaScript, but it likely refers to the reduce() method on JavaScript arrays. The reduce() method executes counter() once for every element in the array, and each time it calls counter(), it replaces total with the returned value from the counter() call. So the given function counts the number of elements that are strictly equal to zero in array.

Categories

Resources