Number between double quotes - javascript

According to this code
function sayHi(myAge) {
"use strict";
if (isNaN(myAge)) {
return "Ture";
} else {
return "False";
}
}
sayHi("12");
isNan() return false, Why? "12" is not a number.
Because When I do this
var myAge = "12";
alert(myAge === 12);
it will return false, because "12" is a string but 12 a number.

Because NaN is a special value in JS, not a type.
sayHi(NaN) will return true.
If you want to check if the value is the Number type, you should do
if (typeof myAge === "number")
And if you want to be sure, that it's not NaN as well, then
if (typeof myAge === "number" && !isNaN(myAge))

From the spec:
Returns true if the argument coerces to NaN, and otherwise returns false.
Compare to ===:
If Type(x) is different from Type(y), return false.

The isNaN() function determines whether a value is NaN or not. Note: coercion inside the isNaN function has interesting rules; you may alternatively want to use Number.isNaN(), as defined in ECMAScript 6, or you can use typeof to determine if the value is Not-A-Number.
Reference : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN

Related

Remove NaN value, javascript

Index 28:
How do I remove this "NaN" value. Cant use isNaN because I want strings and numbers. But not NaN
Tried:
typeof value === 'undefined'
value == null
No success.
You can test for NaN specifically by using Number.isNaN, which is subtly different from plain isNaN: It only returns true if its argument is a number (whose value is NaN). In other words, it won't try to coerce strings and other values to numbers.
Demo:
const values = [
12,
NaN,
"hello",
{ foo: "bar" },
NaN,
null,
undefined,
-3.14,
];
const filtered = values.filter(x => !Number.isNaN(x));
console.log(filtered);
Number.isNaN is new in ECMAScript 6. It is supported by every browser except Internet Explorer. In case you need to support IE, here's a simple workaround:
if (!Number.isNaN) {
Number.isNaN = function (x) { return x !== x; };
}
you can use typeof (to check that's a number) in combination with isNaN
Note that typeof NaN returns "number"
typeof x === "number" && isNaN(x)
Another solution is to use Number.isNaN which will not trying to convert the parameter into a number. So it will return true only when the parameter is NaN
You should be able to use Number.isNaN
console.log([1, "foo", NaN, "bar"].filter((x) => !Number.isNaN(x)))
I’ve seen this comparison check, not sure if you could make it work for you.
var nanValue = NaN;
if(nanValue !== nanValue) // Returns true!
alert('nanValue is NaN');

Issue with using isNaN()

Actually this is a simple program to check weather the number is divisible by 2 or not divisible by 2 or input given is not a number. According to my information isNaN('berry) should give me true as'berry' is a string but in my code this goes quite wrong.
The code is :
var isNum = function(number) {
// My code goes here!
if (number%2===0){
return true
}
else if (isNaN(number)){
console.log("enter the number not the string");
return number
}
else{
return false
}
};
isNum('berry');
The code above returns me false when I run it. Any help will be appreciated.
This is the screenshot
You can try using parseInt() or parseFloat() to convert variables to their integer or float equivalent before use elsewhere.
You can try using typeof to determine the variable type.
var isNum = function(number) {
var number_parsed = parseFloat( number );
if (isNaN(number) || typeof number == 'string' ){
console.log("enter the number not the string");
return number
} elseif(number_parsed % 2 ===0){
return true
} else{
return false
}
};
isNum('berry');
Your code gives the following output (run it here) and it's correctly working
var isNum = function(number) {
// My code goes here!
if (number%2===0){
return true
}
else if (isNaN(number)){
console.log("enter the number not the string");
return number
}
else{
return false
}
};
isNum('berry');
isNan() returns true when the argument is actually NaN. You provided 'berry', not NaN and so isNan() returns false.
Quoting the documentation:
The isNaN() function determines whether a value is NaN or not.
.
Return value
true if the given value is NaN; otherwise, false.

Javascript Optimal way of checking false statement except zero

In javascript we use shortand notation if(input){} to check for empty or null input. We will get false for Null, Undefined, false, 0, NAN, "". My requirements is that I want to get true for any number including zero so I have created a method as follows
function checkFalseExceptZero(value){
if( value !== undefined && value !== null && value !== false && value !== "" && value.length !== 0 ) return true;
else return false;
}
I have added all possible checks in the above method to get the desired result. I am curious if there is any quick, sweet, short or more robust approach to achieve the same?
A simple to understand answer. The three equal signs in JS will not convert type to check if the values equal unlike the two equal signs.
0 == false //true
0 === false //false, because 0 is a number and false is a boolean
Therefore, the answer, if you want to put it inside a function:
JS:
function isNumber(v) {
return typeof v === "number"
}
The function will check the type of the variable. So it is not actually comparing the value to determine the result. The function will only return true if the type of the variable is called number.
Test runs:
isNumber(0) //true
isNumber(false) //false
isNumber("0") //false
isNumber(undefined) //false
In case you want to know, typeof variable will return a string.
My requirements is that I want to get true for any number including
zero so I have created a method as follows
function checkFalseExceptZero(value){
if ( variable.constructor === Array) return !!value.length;
return value === 0 || !!value;
}
This a shorter version of your function. This returns true only when value is 0 or a trully value.
So :
checkFalseExceptZero(null) ==> false;
checkFalseExceptZero(undefined) ==> false;
checkFalseExceptZero(false) ==> false;
checkFalseExceptZero("") ==> false;
checkFalseExceptZero(0) ==> true;
checkFalseExceptZero([]) ==> false;
checkFalseExcpetZero([1]) ==> true;
For any valid number, including 0, JavaScript already exposes the isFinite function. This returns false for all non-numbers, as well as for infinite and NaN
Examples (excerpt from the linked mdn page):
isFinite(Infinity); // false
isFinite(NaN); // false
isFinite(-Infinity); // false
isFinite(0); // true
isFinite(2e64); // true
isFinite("0"); // true, would've been false with the
// more robust Number.isFinite("0")

Proper way to convert number to string in javascript

According to tutorial by w3schools (http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_tostring_number), we can use toString() method on a integer var. Kindly look at the following code:
var num = 15;
var n = num.toString();
alert(isNaN(n));
If toString() method is working, why isNaN(n) returning false?
The IsNaN method tries converting the string passed to it back to a number, and since "15" is still actually a number, the method returns false.
See: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/isNaN
isNaN() coerces the string '15' into a number value before checking it.
isNaN even coerces booleans, and some falsy values into numbers.
isNaN(true) // >> false
isNaN(false) // >> false
isNaN([]) // >> false
isNaN('') // >> false
Try using typeof to figure out if it's a number or not
var num = 15;
var n = num.toString();
alert(typeof n === 'number');
isNaN() function returns true if the value is NaN, and false if not.
Your code is excute alert(isNaN(15));
So it is return false

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