How to Convert nAn to 0 [duplicate] - javascript

This question already has answers here:
Convert NaN to 0 in JavaScript
(11 answers)
Closed 9 years ago.
Array with json
how to convert isNaN to number zero
so if you ahve array 1,2,3 and subtract 1,2 how to subtract
1-1
2-2
3- NaN
NaN should be 0 for 3-0
// Create variables to append player's + or - score per hole
var golfStroke = scores[y].strokes[q];
var parStroke = pars[z];
var scoreStroke = parStroke - golfStroke;
// Create if statement to change undefined array values to number 0 for calculation
var isNum = function () {
if (isNaN(golfStroke)) {
return 0;
} else {
return golfStroke;
}
if (isNaN(parStroke)) {
return 0;
} else {
return parStroke;
};
}
console.log("The over or minus par is: " + scoreStroke);
Thanks

A simple shorthand way of using 0 if you have NaN is to use JavaScript's curiously-powerful || operator:
var x = somethingThatMayBeNaN || 0;
Since NaN is falsey, if somethingThatMayBeNaN is NaN (or 0 or any other falsey value), x will be set to 0. If somethingThatMayBeNaN is truthy, x will be set to somethingThatMayBeNaN. When you're dealing with a numeric calculation, usually the only falsey values that you may have are 0 or NaN.
"Falsey" and "truthy": The "falsey" values are 0, "", NaN, undefined, null, and of course, false. Everything is is "truthy".

This will check if the value is NaN and then it assigns 0 to it.
anyNan = isNaN(anyNan) ? 0 : anyNan;

Assuming is golfStroke that could be NaN, for example:
var scoreStroke = parStroke - ~~golfStroke;
In that way any number would remains the same, and any "falsy" value – like NaN – would become 0.

Related

Why is [0] === [0] false

If debugging shows that a variable is 0, then I think that I should be able to catch it with either ==='0' or ===0 but that didn't work. I had to use only == instead, then it worked:
var offset = 0;
alert("## DEBUG non_sortable_columns " + non_sortable_columns)
if (non_sortable_columns == '0' || non_sortable_columns == 0) {
offset = 1;
}
I first tried this but it didn't work:
var offset = 0;
alert("## DEBUG non_sortable_columns " + non_sortable_columns)
if (non_sortable_columns === '0' || non_sortable_columns === 0) {
offset = 1;
}
The value was [0] and [0] === [0] is false. How can it be false?
1. [0] === [0] is false because each [0] is actually a declaration that creates an array with the number 0 as its first index. Arrays are objects and in JavaScript, 2 objects are == or === only and only if they point at the same location in memory. This means:
var a = [];
var b = a;
console.log(a == b); // "true". They both point at the same location in memory.
a = [];
b = [];
console.log(a == b); // "false". They don't point at the same location in memory.
2. [0] == "0" evaluates to true, because: In JavaScript, due to the nature of the == operator, when you compare an object with a primitive, the object will be coerced to a primitive, and then that primitive will be coerced to the specific type of primitive you are trying to compare it with.
"0" is a string, so [0] will have to be coerced to a string. How ? First, JavaScript will invoke its valueOf method to see if it returns a primitive, the array version of valueOf will just return that array, so valueOf doesn't yield a primitive; now JavaScript will try the object's (aka array's) toString method, an array's toString method will return a string that is the result of a comma-separated concatenation of its elements (each element will be coerced to a string as well, but that is irrelevant here), this would have been more visible if your array contained more than one element (e.g if it were [0,1], toString would return "0,1"), but your array only has 1 element, so the result of its stringification is "0" (if toString didn't return a string but another primitive, that primitive would be used in a ToString abstract operation; if neither valueOf nor toString returned a primitive, a TypeError would be thrown).
Now, our end comparison, with all the coercions and stuff, has changed to "0" == "0", which is true.
3. [0] == 0, mostly the same as #2, except after JavaScript has the string "0", it will coerce it to a number, the result of coercing the string "0" to a number is the number 0. So we have 0 == 0 which is true.
4. [0] === 0 and [0] === "0", these 2 are very simple, no coercions will happen because you are using ===.
In the first one, the reference (aka location pointed at in memory) held by [0] will be compared to the number 0, this will obviously evaluate to false;
In the second one, again, the reference held by [0] will be compared with the string "0", this again, is false.
So, as you can see, good ser, all your misery comes from ==, this operator, along with !=, are called "the evil counterparts of === and !==" by Douglas Crockford, for the same reasons which are causing your confusions.
Feel free to request any elaborations you might want and ask any questions you might have.
Additionally, see this article about object coercion, this MDN article about Array#toString, and this StackOverflow question which outlines the differences between == and ===.
I just did the following test
var num = 0;
console.log("Number: ", num);
if(num === '0' || num === 0) {
console.log("Num is 0 (===)");
}
if(num == '0' || num == 0) {
console.log("Num is 0 (==)");
}
and got the output
Number: 0
Num is 0 (===)
Num is 0 (==)
Try console.log the value itself, if you alert or append strings to a number in JS it will always output as a string. This can be misleading when trying to debug code.
The value of non_sortable_columns might be false.
The basic difference between the === and == is that the 3 equals to comparison operator also checks the type of the variable, that means: '0' which is a string would not be equal to: 0 which is a number.
In your case the variable non_sortable_columns value might be false which means 0in JavaScript therefore the value of the == finds it same as it doesn't check the type but === fails as it checks the type of it.
For better understanding refer to: Which equals operator (== vs ===) should be used in JavaScript comparisons?

Why is Infinity a number? [duplicate]

This question already has answers here:
Infinity is some number in javascript?
(3 answers)
Closed 6 years ago.
In JavaScript, isNaN(Infinity) returns false, as if Infinity were a number; but several arithmetic operations on Infinity behave as if it were the mathematical infinity, which is not a number:
So, why doesn't isNaN(Infinity) return true? Is it because its value defaults to a Number object?
Infinity is not NaN because you are able to use it in mathematical expressions. Obviously 1 + NaN would never work, but 1 + Infinity returns Infinity (See here). Many of the examples that you have in your link are mathematically indeterminate, which is why they return as Nan. For example, Infinity * 0 is indeterminate (See here).
Hope this helps.
The reason isNaN(Infinity) returns false has nothing to do with mathematical technicalities, it's simply because its implementation is equal to this:
function isNaN(object) {
var coerced = +object;
return coerced !== coerced;
}
In other words, it coerces the input to a Number. If the coerced value is determined to be NaN (by checking if it is not strictly equal to itself), then it returns true. Otherwise it returns false.
[Infinity, null, undefined, true, new Date(), {}, [], [1], [1,2,3], 'blah', '4'].forEach(function (object) {
console.log('object: ' + (typeof object !== 'number' ? JSON.stringify(object) : object));
console.log('coerced: ' + (+object));
console.log('isNaN: ' + isNaN(object));
console.log('==================');
});

(!n%2) is the same as (!n%2 == 0)?

I am trying to understand this code from Eloquent JavaScript:
function unless(test, then) {
if (!test) then();
}
function repeat(times, body) {
for (var i = 0; i < times; i++) body(i);
}
repeat(3, function(n) {
unless(n % 2, function() {
console.log(n, "is even");
});
});
// → 0 is even
// → 2 is even
I get that it says, run the following code 3 times testing with 0,1,2:
if (!n%2) function(n) {
console.log(n, "is even");
});
What I don't get is how we get true/false from (!n%2)?
Is (!n%2) the same as (!n%2 == 0)?
Logical NOT ! has higher precedence than modulo operator %.
Thus, (!n%2) is equivalent to (!n) % 2 which will always return 0 a falsy value except when n = 0.
Whereas (!n%2 == 0) will return true(again except 0).
They both are not equal, in fact they are opposite of each other(falsy vs truthy value).
You need !(n % 2).
Or simply to check if number is even
n % 2 === 0
Your test code you wrote is not equivalent to the sample code from the article.
In the sample code, n % 2 is evaluated first, and the result is passed into the unless function. There, you are performing a Logical Not operation against the result.
If n is even, n % 2 will pass 0 to unless. A Boolean comparison of 0 returns false, and the ! negates the result (logical not), so !0 == true. this, in turn, causes the then function to fire.
If n is odd, the opposite occurs. Some value other than 0 is passed, which evaluates to false, causing then to not fire.
In contrast, your attempt to reproduce the sample code without using Higher-Order functions won't work the same way. !n % 2 will perform the Logical Not on n first, then try to modulo the result. !(n % 2) is a better representation of the sample code.
!Boolean(n%2) should work as a way to determine whether one is even or odd.
Remember that Boolean does not follow BIDMAS.
It does !n first where n is treated as a Boolean so that the numerical value of 0 is treated as false and any other numerical value is treated as true. The exclamation mark inverts the logic state of n.
Now the %2 converts the Boolean back to an integer where true is 1 and 0 is false. !n = 0 returns 0 and !n = 1 returns 1.
Using !n%2 in an if statement converts it back to a Boolean (1 = true, 0 = false).
Thus if n = 0 then the if statements proceeds because it returned true. If n != 0 (!= meaning not equal) then if statement is skipped because it returned false.
No, it's not. As stated here the "!" operator has highest precedence than "%" so the expression will return true if n is 0 and false if n is different from 0.
More in detail, suppose n is 2. the execution of the expression is:
(!n)%2
(!2)%2
0%2
0
so it is false, now for n=0
(!0)%2
1%2
1
so it is true. It is the opposite behavior of (!n%2 == 0) that returns true if n is different from 0 and false otherwise since == has less precendence and the comparison with 0 is executed at the end of the calculation above. You can easily convince yourself by using this simple javascript with different values of n:
n = 1;
if(!n%2)
{
document.getElementById("par1").innerHTML="true";
}
if(!n%2 == 0)
{
document.getElementById("par2").innerHTML="true";
}

What does "|| 0" do in JavaScript? [duplicate]

This question already has answers here:
What does the || operator do?
(4 answers)
What does "options = options || {}" mean in Javascript? [duplicate]
(5 answers)
Closed 8 years ago.
I have a piece of JavaScript code that shows:
function(next, feather) {
var l = Number(171) + (next || 0);
var m = Math.max(1, l - 9);
return {
lc: 300 * (l + 1) * m + (5 * feather || 0)
}
}
Now I've simplified it a little bit. But can anyone explain what the "|| 0" does? As far as I can tell it does nothing.
(Notice I replaced a function with Number(171), as that function effectively returns a number, feather is also supposed to be a number, 0 most of the time, 1 sometimes).
If next is falsy, 0 will be used in its place. JavaScript has no default value operator, so users have leveraged this approach, even though the language's creator has called it an abusage.
Well if you know next and feather are numbers, then yes, it has no function. However, if you were to pass in a value like undefined, which is effectively what will happen if you call the function without specifying any parameters, you'll see some difference:
var next = undefined;
console.log(171 + next); // NaN
console.log(171 + (next || 0)); // 171
Of course, this isn't a foolproof method. Passing in null has no effect on the computation, and passing a non-empty string (e.g. "1"), will result in something very different.
variable || 0 looks up the variable, and if it is undefined, null, or empty (i.e. zero), it will use the number 0 instead. This actually makes sense because if it was anything other than zero itself, it would return NaN.
If that didn't make any sense, this should:
undefined * 1 == NaN;
(undefined || 0) * 1 == 0;
If the next is falsy (false-like value) zero is used instead.
E.g.
next || 0
equals something like
if(!next) { return 0 } else { return next; }
It forces false-like values to be an actual zero number.
If the context before the logical or || is falsy (this includes nulls and undefineds), then it will take the value after it. So in your case, if next or feather is not defined or 0, then the value of 0 will be used in those calculations within the parenthesis, essentially the code will read as the following if both are 0 or undefined:
function(next, feather) {
var l = Number(171) + 0;
var m = Math.max(1, l - 9);
return {
lc: 300 * (l + 1) * m + 0
}
}
Using the OR operator || in this scenario is basically short hand for checking weather or not next was included. If it were coming from some sort of number calculation, perhaps it was possible that next was NaN at times (which is always falsy) and so this was the workaround to make it 0.
var l = Number(171) + (next || 0);
A more readable approach would be to test for that case at the inset of the function
if( isNaN(next) )next = 0;
Or to also include other tests as well
if( isNaN(next) || next === null || typeof(next) === "undefined" )next = 0;
The && and || operators in JavaScript will shortcut evaluation. The way it's set up in the example you gave, if 'next' evaluates to a boolean TRUE then that will be added to 'l', otherwise '0' will be added.

What causes isNaN to malfunction? [duplicate]

This question already has answers here:
Validate decimal numbers in JavaScript - IsNumeric()
(52 answers)
Closed 9 years ago.
I'm simply trying to evaluate if an input is a number, and figured isNaN would be the best way to go. However, this causes unreliable results. For instance, using the following method:
function isNumerical(value) {
var isNum = !isNaN(value);
return isNum ? "<mark>numerical</mark>" : "not numerical";
}
on these values:
isNumerical(123)); // => numerical
isNumerical("123")); // => numerical
isNumerical(null)); // => numerical
isNumerical(false)); // => numerical
isNumerical(true)); // => numerical
isNumerical()); // => not numerical
shown in this fiddle: http://jsfiddle.net/4nm7r/1
Why doesn't isNaN always work for me?
isNaN returns true if the value passed is not a number(NaN)(or if it cannot be converted to a number, so, null, true and false will be converted to 0), otherwise it returns false. In your case, you have to remove the ! before the function call!
It is very easy to understand the behaviour of your script. isNaN simply checks if a value can be converted to an int. To do this, you have just to multiply or divide it by 1, or subtract or add 0. In your case, if you do, inside your function, alert(value * 1); you will see that all those passed values will be replaced by a number(0, 1, 123) except for undefined, whose numerical value is NaN.
You can't compare any value to NaN because it will never return false(even NaN === NaN), I think that's because NaN is dynamically generated... But I'm not sure.
Anyway you can fix your code by simply doing this:
function isNumerical(value) {
var isNum = !isNaN(value / 1); //this will force the conversion to NaN or a number
return isNum ? "<mark>numerical</mark>" : "not numerical";
}
Your ternary statement is backward, if !isNaN() returns true you want to say "numerical"
return isNum ? "not numerical" : "<mark>numerical</mark>";
should be:
return isNum ? "<mark>numerical</mark>" : "not numerical";
See updated fiddle:
http://jsfiddle.net/4nm7r/1/
Now that you already fixed the reversed logic pointed out on other answers, use parseFloat to get rid of the false positives for true, false and null:
var isNum = !isNaN(parseFloat(value));
Just keep in mind the following kinds of outputs from parseFloat:
parseFloat("200$"); // 200
parseFloat("200,100"); // 200
parseFloat("200 foo"); // 200
parseFloat("$200"); // NaN
(i.e, if the string starts with a number, parseFloat will extract the first numeric part it can find)
I suggest you use additional checks:
function isNumerical(value) {
var isNum = !isNaN(value) && value !== null && value !== undefined;
return isNum ? "<mark>numerical</mark>" : "not numerical";
}
If you would like treat strings like 123 like not numerical than you should add one more check:
var isNum = !isNaN(value) && value !== null && value !== undefined && (typeof value === 'number');

Categories

Resources