This question already has answers here:
Convert NaN to 0 in JavaScript
(11 answers)
Closed 6 years ago.
I have a code that return to me result of javascript average function in bootstrap modal. But when one of inputs are blank, he return NaN . How i can change NaN to 0?
Here is my code that return result:
$(".average").click(function () {
var result = average();
$("#myModal .modal-body h2").text(result);
$("#myModal").modal();
});
You can check whether a value is NaN using the isNaN function:
var result = average();
if (isNaN(result)) result = 0;
In the future, when ECMAScript 6 is widely available one may consider switching to Number.isNaN, as isNaN does not properly handle strings as parameters.
In comparison to the global isNaN function, Number.isNaN doesn't suffer the problem of forcefully converting the parameter to a number. This means it is now safe to pass values that would normally convert to NaN, but aren't actually the same value as NaN. This also means that only values of the type number, that are also NaN, return true.
Compare:
isNaN("a"); // true
Number.isNaN("a"); // false
Why not just OR, this is one of the most common ways to set a "fallback" value
var result = average() || 0;
as null, undefined and NaN are all falsy, you'd end up with 0, just be aware that 0 is also falsy and would in this case also return 0, which shouldn't be an issue.
var result = average();
result = (isNaN(result) ? 0 : result); //ternary operator check the number is NaN if so reset the result to 0
Use isNaN function.
Related
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?
This question already has answers here:
JavaScript OR (||) variable assignment explanation
(12 answers)
Closed 5 years ago.
Little question, maybe it's a basic one .... but
What should be the value of ub ?
Suppose that getuploadedBytes return an Int,
the value of ub should suppose to be what ?
The min or max value between method and right operator ?
ub = that._getUploadedBytes(jqXHR) || (ub + o.chunkSize);
In summary, if that._getUploadedBytes(jqXHR) is non-zero, that value will be returned, otherwise (ub + o.chunkSize) is returned.
The || operator prefers the left value if it is truthy, and the right value otherwise.
Assuming that that._getUploadedBytes(jqXHR) returns an integer, then the only integer that is falsey is 0.
The value will be the result of _getUploadedBytes unless that function returns 0, in which case it will be ub + o.chunkSize.
0 is a falsy value, which means the condition will fail and the other calculation will produce the result.
This question already has answers here:
Which equals operator (== vs ===) should be used in JavaScript comparisons?
(48 answers)
Closed 6 years ago.
When and why should we use '===' in javascript or jquery.
Is it recommended to test string using === and if yes why.
I have a code where i am checking a condition on the string like.
if(a == "some-thing") is this right or should i use '==='
=== means exactly equal - compare value and type.
'1' == 1 // true
'1' === 1 // false
=== is used for strictly type check, when you want to check value as well as its type.
For Example
var x = 5;
var y = "5";
var z=5;
alert(x==y);//string and int value same though type different - TRUE
alert(x===y);//value same but type different - FALSE
alert(x===z);//value same and type same- TRUE
More Information
with === you will compare the value AND the type of data. With == you only compare the value. So 1000 == "1000" it's true, while 1000 === "1000" is false.
In a simple answer:
Triple equals does a check for type equality. So it'll check the types as well as the contents.
e.g.
var a = '1' === 1;
Would be false.
A double equals would only check the contents, so the code above would return true.
As a good practice, as much as possible.
As a minimum : if you want to check specifically for 0/false/null value because when you use == they're all the same :
0 == false // true
0 === false // false
And f you test the existence of a value but that value can be false or 0 this won't work.
if(value){} // false is value === false or value === 0
There is also the type equality but i don't really think that much relevant unless you depend on some 3rd-party where you need this.
A === "some string" means equal value and moreover equal type.
It's a double test: In your case you obtain true not simply if the values are equal but moreover if the variable A is a string.
You should almost always use the === operator.
An example why:
1 == '1' //is true
1 === '1' //is false
And you want to achieve the second result, because === checks if also the type is the same.
This question already has answers here:
What is the !! (not not) operator in JavaScript?
(42 answers)
Can someone explain this 'double negative' trick? [duplicate]
(9 answers)
Closed 8 years ago.
I just ran into this
var strict = !! argStrict;
I can't help but wonder, what is the meaning of !!? Is it a double negative? Seems pretty redundant, not likely that the guys from php.js would use that in such case?
source: http://phpjs.org/functions/in_array/
It forces the type to become a true boolean value rather than a "truthy" value.
Examples:
var a = (1 === true) // comes out as false because 1 and true are different types and not exactly the same
var b = ((!!1) === true) // comes out as true because the 1 is first converted to a boolean value by means of negation (becomes false) and then negated a second time (becomes true)
It means basically "convert to boolean".
It's negating it twice, so it argStrict is "falsy", then !argStrict is true, and !!argStrict is false.
It returns a boolean value. false for undefined, null, 0, '' and true any truthy value.
This is an example of slacker parsing.
If you have a variable, for example a string, and you want to convert it into a boolean, you could do this:
if (myString) {
result = true;
}
This says, if myString is NOT undefined, null, empty, the number 0, the boolean false then set my string to the boolean value to true...
But it is faster, and way cooler to double bang it:
result = !! myString;
Other examples include....
//Convert to number
result = +myString;
//Bang Bang Wiggle - coerces an indexOf check into a boolean
result !!~myString.indexOf('e');
This question already has answers here:
Closed 12 years ago.
Possible Duplicates:
myVar = !!someOtherVar
What does the !! operator (double exclamation point) mean in JavaScript?
Came across this line of code
strict = !!argStrict
... here and wondered what effect the !! has on the line? Pretty new to JS!
It converts your value to a boolean type:
var x = '1';
var y = !!x;
// (typeof y === 'boolean')
Also note the following:
var x = 0;
var y = '0'; // non empty string is truthy
var z = '';
console.log(!!x); // false
console.log(!!y); // true
console.log(!!z); // false
It converts the value to a value of the boolean type by negating it twice. It's used when you want to make sure that a value is a boolean value, and not a value of another type.
In JS everything that deals with booleans accepts values of other types, and some can even return non-booleans (for instance, || and &&). ! however always returns a boolean value so it can be used to convert things to boolean.
It is a pair of logical not operators.
It converts a falsey value (such as 0 or false) to true and then false and a truthy value (such as true or "hello") to false and then true.
The net result is you get a boolean version of whatever the value is.
It converts to boolean
Its a "not not" arg
commonly used to convert (shortcut) string values to bool
like this..
if(!!'true') { alert('its true')}