Javascript Optimal way of checking false statement except zero - javascript

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")

Related

Why parseInt(key) === NaN always evaluates to false

I'm doing decision based on dictionary key, i have only two types of keys, numeric and alpha,
var _dict = { 'a':'one', 'b':'two', '1':'three' };
$.each( _dict, function( key, value ){
if( parseInt( key ) === NaN ) {
// this statement always evalute to false
} else {
}
});
if i print console.log(parseInt('a')), it will also return NaN
I alreay found the solution from this question javascript parseInt return NaN for empty string
But i was wondering why it always evaluates to false.
That's because NaN is defined to be not equal to anything (including itself). Check it:
>> NaN === NaN
False
You should use isNaN() function instead:
>> isNaN(NaN)
true
>> isNaN(0/0)
true
>> isNaN(parseInt('a'))
true

Checking whether variable is empty in JavaScript?

There is two kind of JavaScript code for investigating empty/full variable:
if(variable == ''){}
if(!variable){}
I tested both of them, and I achieved identical result. Now I want to know, (first) are they equivalent? And (second) which one is more standard for checking empty/full variable?
var variable1 = 'string';
var variable2 = 12;
var variable3 = true;
if(variable1 == ''){alert('empty-one');}
if(variable2 == ''){alert('empty-one');}
if(variable3 == ''){alert('empty-one');}
if(!variable1){alert('empty-two');}
if(!variable2){alert('empty-two');}
if(!variable3){alert('empty-two');}
As you see, there is no alert.
First is not standard, it only works for defined empty string.
Other will work if value is not truthy ( means something meaningful)
e.g var a;
a == '' will give false result
! a will produce true
e.g. var a = null;
a == '', // false
! a // true
var a = false;
a == '' // fase
! a // true
var a = NaN
a == '' // false
! NaN // true
true == 'true' // false, Boolean true is first converted to number and then compared
0 == '' // true, string is first converted to integer and then compared
== uses The Abstract Equality Comparison Algorithm to compare two operands
For more detail visit http://www.ecma-international.org/ecma-262/5.1/#sec-11.9.3
In javascript null,'',0,NaN,undefined consider falsey in javascript.
In one sense you can check empty both way
But your first code are checking is it ''
and your 2nd condition is checking is your value are one of them (null,'',0,NaN,undefined)
In my view your 2nd condition is better then first as i don't have to check null,'',0,NaN,undefined seperately
No they are not equivalent. In case first it checks whether the value of variable is equal to the empty string('') or not. So case first will be true iff variable's value is ''. But second case will be true for all the values which are falsey i.e. false, 0, '', null, undefined.

why in jquery did developers use confusing inverse over straight forward comparisons

function grep( elems, callback, invert ) {
var callbackInverse,
matches = [],
i = 0,
length = elems.length,
callbackExpect = !invert;
// Go through the array, only saving the items
// that pass the validator function
for ( ; i < length; i++ ) {
callbackInverse = !callback( elems[ i ], i );
if ( callbackInverse !== callbackExpect ) {
matches.push( elems[ i ] );
}
}
return matches;
}
wouldn't this be more straight forward
for ( ; i < length; i++ ) {
callbackInverse = callback( elems[ i ], i );
if ( callbackInverse == callbackExpect ) {
matches.push( elems[ i ] );
}
}
I guess it's to make sure both variables are booleans.
For example, imagine callback returns NaN when running
callbackInverse = callback( elems[ i ], i );
That could be problematic, given that
NaN == true; // false
NaN == false; // false
(It happens because the comparisson of a boolean and a number coerced the boolean to a number, instead of coercing the number to boolean)
But negating the values with ! converts them to booleans, avoiding those problems.
Note that callbackExpect is set to !invert:
callbackExpect = !invert;
This forces callbackExpect to be a "boolean" (so exactly true or false).
Then they compare using !== which is not the same as != in that it compares the content of the variable without conversion. In other words, if callbackInverse is not exactly 0 or 1, it returns true.
Note that the inverse of !== is === and not == as in your example. i.e. compare without first converting the parameters.
Update:
As pointed out by Walter Tross in a comment, Boolean is a separate type:
// Booleans
typeof true === 'boolean';
typeof false === 'boolean';
typeof Boolean(true) === 'boolean'; // but never use this form!
Therefore the !invert generates a Boolean and if callbackInverse is not a Boolean, then !== is going to be true. However, like the callbackExpect variable, it is set to !(of something) which means it will always be a Boolean too. So you could use == and != since the ! operator is used to canonicalize the returned values.
Because this way both the invert param and the return value of the callback are cast to boolean by the !, so that they can be safely compared as booleans.
E.g., imagine callback returns undefined. But undefined != false, while you probably want undefined to be treated like false. In fact, casting it to boolean yields false:
!!undefined === false (!! is an easy way of casting to boolean).
Instead of doing the double negation, jQuery does a single one, negating the other side just once, before the loop, so that the comparison becomes:
!undefined === !false (this is a bit like changing the sign of both sides of an equation.)
Quoting the ECMAScript 5.1 standard:
Boolean comparison can be forced by: !a == !b.
The price of doing a single negation instead of a double negation inside the loop is readability (which is always impaired when using "negative logic"), but in a highly optimized library like jQuery this is acceptable.
As to your example, you should rename callbackInverse to something like callbackValue, since it's not inverted (and not cast to boolean) any more. But the problem remains: your code will only work correctly if callback is guaranteed to return booleans.

Javascript if condition on boolean

Can you explain why the if condition doesn't work without the eval function:
var myBoolean= document.getElementById("someBoolean").value; //This is a 'false'
if(myBoolean)
{
alert(Your boolean is True); //This condition always getting executed even though myBoolean is false;
}
if(eval(myBoolean))
{
alert("You will never see this alert bcoz boolean is false");
}
In Javascript the following values are treated as false for conditionals:
false
null
undefined
The empty string ''
The number 0
The number NaN
Everything else is treated as true.
'false' is none of the above, so it's true.
The string 'false' evaluates to the boolean true
This is because it's not actually a boolean, it's a the string 'false'. When you convert a string to a boolean, '' is false and anything else is true.
You check if it's equal to the string 'false' (or 'true') or not.
var myBoolean = 'false'; // (string)
myBoolean = myBoolean !== 'false'; //false (boolean)
'false' == true, crazily enough because of JavaScript's implicit type coercion. Check out these other examples from Crockford's The Elements of JavaScript Style.
'' == '0' // false
0 == '' // true
0 == '0' // true
false == 'false' // false
false == '0' // true
false == undefined // false
false == null // false
null == undefined
// true
' \t\r\n ' == 0 // true
You could solve this particular problem by changing your code to something like
var myBoolean = document.getElementById("someBoolean").value === "true"
Also, it is almost always better to use !! and === rather than ! and ==
document.getElementById("someBoolean") does not return a boolean true/false it returns an element or undefined / null
you could reverse your logic and get the expected result:
if(!myBoolean)
{
alert('This element does not exist');
}
if(!eval(myBoolean))
{
alert("Do not know why you would ever want to do this");
// you could do typeof()
}
Try:
var myBoolean= document.getElementById("someBoolean").value; //This is a 'false'
if(myBoolean != "false")
{
alert(Your boolean is True); //This condition always getting executed even though myBoolean is false;
}
Like others have said, a string isn't a boolean value, so using it as though it was will give you a logical error.
A string IS a boolean truth value according to ECMA
var a = ""<br/>
a&&false //-> false<br/>
a||false //-> "" (truthy)<br/>

How do I check if a number evaluates to infinity?

I have a series of Javascript calculations that (only under IE) show Infinity depending on user choices.
How does one stop the word Infinity appearing and for example, show 0.0 instead?
if (result == Number.POSITIVE_INFINITY || result == Number.NEGATIVE_INFINITY)
{
// ...
}
You could possibly use the isFinite function instead, depending on how you want to treat NaN. isFinite returns false if your number is POSITIVE_INFINITY, NEGATIVE_INFINITY or NaN.
if (isFinite(result))
{
// ...
}
In ES6, The Number.isFinite() method determines whether the passed value is a finite number.
Number.isFinite(Infinity); // false
Number.isFinite(NaN); // false
Number.isFinite(-Infinity); // false
Number.isFinite(0); // true
Number.isFinite(2e64); // true
A simple n === n+1 or n === n/0 works:
function isInfinite(n) {
return n === n/0;
}
Be aware that the native isFinite() coerces inputs to numbers. isFinite([]) and isFinite(null) are both true for example.
Perform the plain ol’ comparison:
(number === Infinity || number === -Infinity)
or to save several characters:
Math.abs(number) === Infinity
Why to use this
!(Number.isFinite(number)) breaks on NaN inputs.
Number.POSITIVE_INFINITY and Number.NEGATIVE_INFINITY can be redefined; they are configurable.
Infinity and -Infinity are read-only in the strict mode.
It is the shortest solution.
Actually n === n + 1 will work for numbers bigger than 51 bit, e.g.
1e16 + 1 === 1e16; // true
1e16 === Infinity; // false
I like to use Lodash for a variety of defensive coding reasons as well as readability. ES6 Number.isFinite is great and does not have issues with non-numeric values, but if ES6 isn't possible, you already have lodash, or want briefer code: _.isFinite
_.isFinite(Infinity); // false
_.isFinite(NaN); // false
_.isFinite(-Infinity); // false
_.isFinite(null); // false
_.isFinite(3); // true
_.isFinite('3'); // true
I've ran into a scenario that required me to check if the value is of the NaN or Infinity type but pass strings as valid results. Because many text strings will produce false-positive NaN, I've made a simple solution to circumvent that:
const testInput = input => input + "" === "NaN" || input + "" === "Infinity";
The above code converts values to strings and checks whether they are strictly equal to NaN or Infinity (you'll need to add another case for negative infinity).
So:
testInput(1/0); // true
testInput(parseInt("String")); // true
testInput("String"); // false
You can use isFinite in window, isFinite(123):
You can write a function like:
function isInfinite(num) {
return !isFinite(num);
}
And use like:
isInfinite(null); //false
isInfinite(1); //false
isInfinite(0); //false
isInfinite(0.00); //false
isInfinite(NaN); //true
isInfinite(-1.797693134862316E+308); //true
isInfinite(Infinity); //true
isInfinite(-Infinity); //true
isInfinite(+Infinity); //true
isInfinite(undefined); //true
You can also Number.isFinite which also check if the value is Number too and is more accurate for checking undefined and null etc...
Or you can polyfill it like this:
Number.isFinite = Number.isFinite || function(value) {
return typeof value === 'number' && isFinite(value);
}

Categories

Resources