NaN counts as false? - javascript

I'm reading a book "Eloquent JavaScript" by Marijn Haverbeke and it says:
"The rules for converting strings and numbers to Boolean values state that 0, NaN, and the empty string ( "" ) count as false, while all the other values count as true."
Would be very nice if someone explains me what did the author mean by saying that NaN counts as false according to the rules of converting?
As I can see it now:
0 == false; // true
"" == false; // true
NaN == false; // false
0 / 0 == false; // false
Yes I know that "NaN is not equal to anything, even to the other NaN", but I just wonder what does the book want me to know?

Basically, if a variable is assigned to NaN, it will evaluate to false if used in a conditional statement. For example:
var b = NaN;
if(b){//code will never enter this block
console.log('the impossible has occurred!')
}
This is true as well if you get invalid input, for example:
var input = "abcd"
var num = parseFloat(input);
if(num){
console.log('the impossible has occurred!')
}

var a = NaN;
var b = null;
var c;
var d = false;
var e = 0;
document.write(a + " " + b + " " + c + " " + d + " "+ e + "<br>");
if(a || b || c || d || e){
document.write("Code won't enter here");
}
if(a || b || c || d || e || true){
document.write("Code finally enters");
}
Reference: link

Other answers are correct, but the significant thing here is that a conversion to a bool takes place in the case that it's used in a condition.
That's why:
NaN === false // false
Yet:
if(NaN) // false because it first does a boolean conversion
// which is the rule you see described
As a side note, NaN == false as used in the question (note == vs ===) actually does a type conversion from false to 0 per the == operator. It's beyond the scope of this question, but the difference in operators is well documented elsewhere.

The book wants you to know that JavaScript evaluates NaN to false.
var notANumber = 500 / 0;
if(notANumber) {
// this code block does not run
}
else {
// this code block runs
}

Related

javascript string expression as if condition

I am building a string which is to be evaluated as if condition, like
if (location_val.length == 1) {
condition = condition + " v.location === '" + location_val + "' &&";
} else {
for (var i = 0; i < location_val.length; i++) {
condition = condition + " v.location === '" + location_val[i] + "' && ";
}
}
but javascript evaluates the variable if it is not null, undefined, 0 or empty string, how to evaluate string as expression? I am using condition variable as follows, but it always returns true because of the above reason.
if(condition)
Build your expression properly - not using string concatenation, its something like this:
var condition = (location_val.length == 1 && v.location == location_val)
|| (location_val.every(function(loc){ return v.location === loc; } );
if(condition) {
....
}
I suspect there is more to this (you have && at the end of both strings) but the same applies to everything else. Boolean's can be combined in parts
var condition1 = (location_val.length == 1 && v.location == location_val)
|| (location_val.every(function(loc){ return v.location === loc; } );
var condition2 = ...
var condition3 = ...
if(condition1 && condition2 && condition3){
....
}
In JavaScript there's the eval function. You can use it to evaluate a string as an expression.
eval('3 + 2 === 5') //true
I would recommend you to rethink your solution, though, since working with strings as expressions when you could solve your problem differently, is really error prone and literally the worst practise.
Also use === instead of ==
(=== works as you'd expect == to work, == doesn't)

How this variable is going to do in this function:

I want to know about what exactly is being done with variable a in below function :
function c(a) {
var b = new Date;
return Math.round(b.getTime() / 1e3 + (a ? a : 0))
}
Code that needs clarity:
(a?a:0)
Just want to know what is the logic of highlighted text.
If a is undefined or false or null or NaN it will return 0 else it will return value of a
Lets assume
var someVar = 23;
function c(a) {
return a ? a : 0; //Also true for negative values
}
c(someVar); //will return 23
And
var someVar = -22;
c(someVar); //will return -22
And
var someVar = false;
c(someVar); //will return 0
And
var someVar; //someVar is undefined
c(someVar); //will return 0
You probably wanted to use bold style, aren't you?
The statement x > 5 ? true : false is a shortened version of an if...else statement. You put the statement before the "?". The ":" separates the if and else part. If the statement is true, then the part before the : fires, if false, then the one after it. Because javascript likes to convert anything into booleans, the statement you have is the same as if (a > 0) { b = a } else { b = 0}
If you want to know more about these statements, search for ternary operators
these two lines
var b = new Date;
return Math.round(b.getTime() / 1e3 + (a ? a : 0))
can also be written as (for better readability)
var b = new Date;
var c = b.getTime() / 1e3 ; // 1e3 is 1000, so c is basically number of seconds since 1970
if ( !a ) //if a is either undefined, null or false
{
a = 0;
}
return Math.round(c+a); //now c+a is adding these seconds to the paramter you have passed
So this function is basically passing the number of seconds since 1970 to the value you are passing.
the "? : " is known as a ternary operator. It is a shortcut for an if else. For example, var b = a ? a : 0 is equivalent to:
var b;
if(a){
b = a;
}else{
b = 0;
}
Also, for the sake of clarity, your code misses () and ;. Here is a correct version:
function c(a) {
var b = new Date();
return Math.round(b.getTime() / 1e3 + (a ? a : 0));
}
Have a look at this question for further explanation.
if(a){
return a;
}
else{
return 0;
}

Why is `exp && "t" || "f"` much slower than inline-if-else?

Why is the logical expression twice slower than if-else or inline-if-else?
function logicalExp(val) {
return val && "t" || "f";
}
function inlineIfElse(val) {
return val ? "t" : "f";
}
function ifElse(val) {
if (val) return "t";
else return "f";
}
All functions evaluate with same results.
All functions are being passed a value from an array of 1 and 0, see this jsperf test.
Because it does need to evaluate whether "t" is truthy or not. The short-circuit expression return ((val && "t") || "f") can be expanded to
var and = val ? "t" : val;
var or = and ? and : "f";
return or;
Of course, an optimising compiler could statically determine the truthiness of the "t" literal, and avoid doing ToBoolean(val) twice, but apparently this is not done in any JS engine.
Because
val && "t" || "f"
has to evaluate val and, if val evaluates to true, "t" as well.
Using only false is therefore significantly faster than only true, but still quite slow.

How to clear text field using javascript with a condition?

I want if I clear the text field #t1, text field #d1 should clear. But last two lines dont do it....
function utl()
{
var a = document.getElementById('t1');
var z = document.getElementById('d1');
if (a!=0)
{
var y = parseFloat(a.value) * 100;
y = y || 0;
z.value = y.toFixed(2);
}
else if (a==0)
z.value = 0;
else if (a=='')
z='';
a is a DOM element, and so it will always be != 0 as the != operator will coerce it to a string, and then to a number, and that number will be != 0.
You probably wanted to use the .value property:
var a = document.getElementById('t1').value;
But you'd still have a problem: The value of an input is always a string. In JavaScript, the == and != operators do type coercion, and "" is == 0. So your third statement, z='', will never be reached.
You can use the strict equality operators to figure out what's going on:
var a = document.getElementById('t1').value;
var z = document.getElementById('d1');
if (a === "") { // <== Note! === rather than ==
z.value = "";
} else {
a = +a; // Convert to number intentionally
if (a != 0) {
var y = a * 100;
y = y || 0;
z.value = y.toFixed(2);
} else if (a == 0) {
z.value = "0";
}
}
The strict equality (===) and inequality (!==) operators don't do type coercion, so although "" == 0 is true, "" === 0 is false.
That line where I converted to a number:
a = +a;
...is only one of the many options available. Using +str to convert to a number is the strictest way, but you don't have direct control over the number base. You could also use:
a = parseInt(a, 10); // If you're expecting an integer, or
a = parseFloat(a); // If it may have a fractional portion
...assuming you want base 10 (decimal), but note that they ignore trailing characters, and so parseInt("123laksdjflk", 10) is 123. In contrast, +str (or Number(str)) will say that's Nan because they consider the entire string, not just the first part.

When can != be used instead of !==?

Consider the code snippet below from this AngularJS tutorial:
app.factory('Auth',
function ($firebaseSimpleLogin, FIREBASE_URL, $rootScope) {
var ref = new Firebase(FIREBASE_URL);
var auth = $firebaseSimpleLogin(ref);
var Auth = {
register: function (user) {
return auth.$createUser(user.email, user.password);
},
signedIn: function () {
return auth.user !== null;
},
logout: function () {
auth.$logout();
}
};
$rootScope.signedIn = function () {
return Auth.signedIn();
};
return Auth;
});
I understand the difference between != and !== is the first compares by reference and the second compares by value. Since the comparison here is to null, then why has the developer chosen to use !== instead of !=? Is my understanding correct that both would work here?
== / != operator only compares the value of the variables, not the type
=== / !== operator compares the type and the value of the variables
Some examples:
var varA = 5; // int
var varB = '5'; // string
var varC = 5; // int
if(varA == varB) // true (only value compared)
if(varA === varB) // false: because varB is of type string and varA of type int
if(varA == varC) // true
if(varA === varC) // true: because varA and varC are of the same type and have the same value
I often use "if(x != null)" to check if x is either null or undefined. It's safer than just saying "if(x)" since there are other falsey values besides null and undefined.
Here's an overview table, for your convenience: http://jsfiddle.net/QQcVw/1/
0 "" false null undefined
0 Y Y Y n n
"" Y Y Y n n
false Y Y Y n n
null n n n Y Y
undefined n n n Y Y
As you can see, == considers equal three empty "values" (0, "" and false) and two "non-values" (null and undefined). See javascript standard for the exact algorithm.
In most cases, it's a good idea to avoid == and always stick to ===.

Categories

Resources