Javascript idiom: What does if (x === +x) do? [duplicate] - javascript

This question already has answers here:
+ operator before expression in javascript: what does it do?
(4 answers)
Closed 10 years ago.
Reading through the source code of underscore.js I stumbled upon the following line:
... if (obj.length === +obj.length) { ...
That's a bit confusing for me. What is actually being compared here? I believe it has something to do about detecting native arrays, but cannot figure out what's actually going on. What does the + do? Why use === instead of ==? And what are the performance benefits of this style?

The + coerces the value to an Number (much like !! coerces it to a boolean).
if (x === +x)
...can be used to confirm that x itself contains an integer value. In this case it may be to make sure that the length property of obj is an integer and has not been overwritten by a string value, as that can screw up iteration if obj is treated as an array.

It is a silly (IMO) way of checking if obj.length is a Number. This is better:
typeof obj.length == "number"

The + coheres what is on the right side to be a number.
In this case if length was not a property on the object undefined would be returned. + undefined will yield Nan and this evalutation be false.
If the string can be coheres-ed into a number then it will be.. e.g + '1' will yield 1 as a Number this is especially important when dealing with hex values in string form e.g. +'0x7070' yields 28784

Related

How can I pass label value as variable for if else case? [duplicate]

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 9 years ago.
Improve this question
I was trying to compare a variable to a value and accidently ended up using '=' in place of '==' hence the code looked like:
var test = 1;
if(test = 2) {
console.log(test);
}
instead of:
var test = 1;
if(test == 2) {
console.log(test);
}
I assume the value was successfully assigned to the variable , hence the condition returned truthy and console.log() was executed. Is my assumption correct? What is a good coding practice to avoid such mistakes besides Yoda Condition reference
Lint it. There are tools that can automatically analyze your Javascript and catch common errors like this.
The assignment operator (=) in JavaScript evaluates to the right-side value of the expression, which means that test = 2 evaluates to 2 and since all values that aren't falsey (0, false, null, undefined, '', NaN) are thruthy by definition, the if condition was entered.
A good practice would be to always use the === sign when checking for equality and !== for inequality and there are tools that will help you enforcing those rules, like JSHint
Use if (a === b) { do stuff ; } that's three equals, ===
In Javascript you often need three equals, ===, as this requires primitives to have both the same type and value, and will not perform type coercion which, although you don't mention it, can be another source of confusion.
If you leave off an equals, it becomes two equals comparison, a == b, which might not work quite as expected if you are a beginner or unaware of the quirks of this comparison in Javascript, but at least is not an assignment.
The answer in JavaScript is pretty easy: always use strict comparison. This will avoid not only assignment errors, but also some non-intuitive behavior that can come from JavaScript's weak comparison rules.
Edit: Didn't see the questioners requirement to avoid this method.
Use strict comparison operator (===). You can also change the order of the values being compared which will fail if you use assignment statement rather than comparison operator.
Fails:
var test = 1;
if(2 = test) {
console.log(test);
}
The above code will throw an exception since you can't assign a value to the constant value.
Works:
var test = 1;
if(2 == test) {
console.log(test);
}
a = b is an assignment. Meaning a will equal to b.
a == b is a comparison. Meaning does a equal to b.
a === b is the same as == however no type conversion is done. Meaning does a equal to b, but also is it the same object/type?
Where your going wrong with your code is
var test = 1;
if(test = 2) { //this is true, because test now equals 2.
console.log(test);
}
When you assign something the value returned isn't representative of whether or not the assignment was successful, it actually just returns the right hand side of the assignment (e.g, the test = 2 in if (test = 2) would return 2 which is "truthy" in JavaScript, thus causing console.log(test) to evaluate. This can actually be quite useful in certain cases. For example:
while ((value = retrieveSomeValue()) !== null) {
console.log(value);
}
The code above continually assigns some variable value to the result of some function retrieveSomeValue, tests the resulting value to make sure it isn't null, and executes the while body.
To answer your question though: The === operator is more easily distinguished from the = operator and probably behaves more like what you would expect out of ==. Which equals operator (== vs ===) should be used in JavaScript comparisons?

Javascript: Is my variable NaN or is it a Number? [duplicate]

This question already has answers here:
Why does typeof NaN return 'number'?
(21 answers)
Closed 5 years ago.
I'm not able to establish if my javascript variable is a number or not.
Here's what I have:
alert('variable startDateB: ' + startDateB);
Results:
variable startDateB: NaN
In the very next line I have:
alert('typeof startDateB: ' + typeof(startDateB));
Results:
typeof startDateB: number
My end goal is to compare this date with other dates, but I don't know whether a conversion is necessary since I appear to be getting mixed information about the variable's data type.
Any help is greatly appreciated!
Thanks!
By definition, NaN is the return value from operations which have an undefined numerical result.
Aside from being part of the global object, it is also part of the Number object: Number.NaN.
This is why you are seeing the behavior you describe. NaN is part of the Number object.
It is still a numeric data type, but it is undefined as a real number.

Usefulness of the comma operator in comparisons [duplicate]

This question already has answers here:
When is the comma operator useful?
(15 answers)
Closed 5 years ago.
I saw a comparison like the following in a question on SO:
(pNum != ('2','3','4','5','6','7','8','9'))
The OP has been trying to check if a number falls in a certain range but this code is inaccurate as it will always compare with right most value inside the brace(i.e. 9)
This means when pNum = 2 the comparison will return true and not false as was expected by OP who was expecting it to work like inArray or in.
My question is whether this sort of comparison is going to be useful in any real case in any scenario?
My question is whether this sort of comparison is going to be useful in any real case in any scenario?
No. As you observe, the comparison only compares the last item inside the bracket. So all it can accomplish is to confuse the reader.
If you intend to compare a variable with a set of values, you could use array#includes or array#indexOf >= 0. Something like:
console.log(['2','3','4','5','6','7','8','9'].includes('2'));
console.log(['2','3','4','5','6','7','8','9'].includes('6'));
console.log(['2','3','4','5','6','7','8','9'].includes('9'));
// IE
console.log(['2','3','4','5','6','7','8','9'].indexOf('2') >= 0);
console.log(['2','3','4','5','6','7','8','9'].indexOf('6') >= 0);
console.log(['2','3','4','5','6','7','8','9'].indexOf('9') >= 0);

How can jquery || "OR" be used outside of an if statement? [duplicate]

This question already has answers here:
JavaScript OR (||) variable assignment explanation
(12 answers)
What does the construct x = x || y mean?
(12 answers)
In Javascript, what does it mean when there is a logical operator in a variable declaration? [duplicate]
Closed 8 years ago.
I've never seen the OR paramater || used outside of an if statement.
What does this line of code do?
var doc = ($iframe[0].contentWindow || $iframe[0].contentDocument).document
Is it saying making it equal to either one of those???
A || B
evaluates A first. If it is true, A is returned, and B never needs to be looked at.
If A is false, B is evaluated and returned.
For example, if you write
function (x)
{ x = x || 50
...
This would make x=50, if x is nil (or some kind of false value).
Otherwise, x would not be changed.
It is like having a default value, or a failsafe protection. If you know that the answer should never be false, then if A is false, you provide a backup value of B.
A way to get a DOM reference to the iframe's window object is to use:
contentWindow.document
Now, cause IE<8 has problems with it, a small polyfill is to use
var doc = ($iframe[0].contentWindow || $iframe[0].contentDocument).document;
// Browser you get this one ^^^ ? NO? Sh** you're IE7, go with^^
So earlyer versions of IE will skip the contentWindow cause not recognized, and thanks to the || (or) operator will follow up with the next contentDocument.
I don't have to repeat what's the OR operator cause other smart people already explained it: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators
This is just a short form of the ternary operator, which always returns a value depending to a statement. So, e. g.:
var fruit = "apple";
var test = fruit === "apple" ? fruit : "banana";
This sets the variable test to the value of fruit, when fruit is set to "apple". Otherwise, test will be initialized with "banana".

Keep original value with "variable = NEWVAR || variable;" [duplicate]

This question already exists:
In Javascript, what does it mean when there is a logical operator in a variable declaration? [duplicate]
Closed 9 years ago.
Is this a legitimate way to update variables and keep the original value if the new value is undefined?
variable = NEWVAR || variable;
I created a Fiddle and so far it looks fine, but I don't want to get any nasty surprises.
Here is a test case:
var test = "hello";
test = undefined || test;
alert('"' + test + '"');
I would say, yes, i use it quite often. But you have to keep in mind that
Douglas Crockford: Javascript The Good Parts (p. 40)
The || operator produces the value of its first operand if the first operand is truthy. Otherwise, it produces the
value of the second operand.
So if NEWVAR contains any falsy (false,null,undefined,NaN,0,"") value, the second opertand is evaluated.
As long as you are aware of this you can always use the || operator to get default values
Douglas Crockford: Javascript The Good Parts (p. 51)
The || operator can be used to fill in default values:
var middle = stooge["middle-name"] || "(none)";
var status = flight.status || "unknown";
Yes and no. It technically works, but you have to be careful of falsy values because if NEWVAR is 0, false, "", or any other falsy value, it won't be assigned. A wiser way to do this would be to check whether or not NEWVAR is defined, perhaps with a tertiary operator:
variable = (typeof NEWVAR === "undefined") ? variable : NEWVAR;

Categories