Javascript if expression evaluation - javascript

I was wondering when the Javascript if expression actually evaluates to false and when to true. When is the if statement false, and is that true for all JS interpreters?
I guess the condition is false on
false
undefined
null
0
otherwise true. Is that correct for all implementations (tested in Safari/WebKit console), or am I better off with explicit checking like (typeof a === "undefined")?

The following values will evaluate to false:
false
undefined
null
0
NaN
the empty string ("")
https://developer.mozilla.org/en/JavaScript/Guide/Statements#if...else_Statement

If you want to check for variable existence, and a is not declared anywhere in your script, typeof a === 'undefined' is the way, or you can use if (!window.a). Otherwise a ReferenceError is thrown.
Your guessing seems to be correct. An empty string and NaN also evaluate to false (or, as some like it falsy). The fact that 0 evaluates to false may be tricky, but it's handy too, in statements like while (i--) (if i has the value of 0 it evaluates to false and the while loop stops).

Related

Why does NaN = !NaN return true?

NaN is one of those vestigial implementations of questionable origins, but for the most part I get it. However, I typed this into a Node prompt today and couldn't really make sense of it...
NaN = !NaN
> true
Is this simply returning the evaluated result of !NaN? This makes sense, but I'm surprised that there's not an error when attempting to assign NaN to another value.
Note: this question is about this specific syntax structure; there are a lot of questions related to NaN and isNaN out there but I couldn't find an answer after googling. Thanks to Ori Drori for the best answer thus far.
console.log(NaN = !NaN);
You are assigning true to NaN instead of comparing NaN to !NaN using === or ==, so the operation returns the assigned value -> true. Javascript ignores this assignment silently because NaN is read only.
console.log(NaN = true);
// NaN hasn't changed
console.log(NaN);
If you'll add use strict to your code, JS will throw a read only error instead:
'use strict';
NaN = true;
= is the asignment operator.
== and === are comparison operators.
NaN == !NaN
false
NaN === !NaN
false
Perhaps more surprisingly:
NaN == NaN
false
NaN === NaN
false
For more about NaN: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/NaN
Try running Javascript in a strict mode to avoid most of the problems.
NaN, null, false, "", null, undefined, 0 etc they are considered as falsy values (remember falsy !== false) in javascript, no matter you use a strict mode or not.
// 'use strict';
console.log(!NaN); // true
console.log(!null); // true
console.log(!false); // true
console.log(!""); // true
console.log(!null); // true
console.log(!undefined); // true
console.log(!0); // true
It is true in Python as well, except for NaN. For example,
print(not False) # True
print(not None) # True
print(not float("NaN")) # False
print(not "") # True
print(not 0) # True
Source of confusion
When we use multiple languages sometimes it can be a source of confusion.
For example,
In Python 'cat' in ['fat', 'cat', 'rat', 'hat'] returns True.
In Javascript 'cat' in ['fat', 'cat', 'rat', 'hat'] (exactly the same piece of code) returns false no matter you use a strict mode or not.
In Python print(not []) returns True.
In Javascript console.log(![]); returns false.
This is one of the reasons why I always love to use debuggers, REPL etc no matter how simple the code is.
Using = operator, you assign the value to a variable. However, what you don't know is by doing that, it returns the value of what is being assigned. Typing:
v = 1
in a JavaScript REPL will display 1, because that is what was assigned to v. So, doing:
NaN = !NaN
Will assign the opposite value of NaN to NaN itself. Since NaN in boolean is false, then !NaN in boolean must be true.
Javascript is really weird: When you write
NaN = true // true
which you basically do in your statement, you get "true". This is the same behavior as when you write
a = true // true
where the right side of the assignment is returned. But if you add var and write
var a = true // undefined
then nothing is returned. Also if you replace NaN with an expression that evaluates to NaN, for example
1/"a" = true // error!
then you get a ReferenceError. I recommend to never use the return values of assignments. The behavior is inconclusive and your code will be hard to read. You can enable "strict mode" to check this for you.

Why does the following evaluate to 'hi'?

Why does the following evaluate to 'hi'?
'hi' || true || 50
I'm not super new to javascript, but I'm rebeefing my knowledge by going through some old books and I for the life of me do not understand why this evaluates to 'hi' instead of true.. Can someone explain this??
Welcome to the world of truthy and falsey values.
If a value can be converted to true, the value is so-called truthy. If
a value can be converted to false, the value is so-called falsy.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators
This means that basically everything except
false
null
undefined
NaN
""
0
Will evaluate to true in || conditions, returning the first value that is truthy. This is sometimes used in a coalesce-like way:
a = a || {}
Which will set a to a if a is none of the values above, else an empty javascript object.
Because 'hi' is a non-empty string literal which evaluates to true when treated as a boolean. The expression a || b || c returns the first expression which evaluates to true, in this case 'hi'.
From MDN (Logical Operators):
Returns expr1 if it can be converted to true; otherwise, returns expr2. Thus, when used with Boolean values, || returns true if either operand can be converted to true; if both can be converted to false, returns false.
Hey thanks everybody for your input. Yeah, now it makes sense because I remember how the first value that evaluates to true is the one that it will evaluate to. I guess I have to do some more studying on the truthy stuff because yeah, it is simple, but in a way it is somewhat confusing at times. Thanks again!!

why sometime variable are used as condition in if statement in javascript?

e.g if(variable name) or
var x;if(x){some code} else{some code}
I understand
if(x>7)
conditions but only variable name inside bracket followed by if does not make me any sense.
Here variable can be a boolean value or sometime to check variable existence you check it in if statement. Condition you might test with if statement.
Element exist or not
Input value empty or not
collection length zero or greater
So following code:
if(result){
//do something
}
will cause false in the following condition(also called falsy):
false
0 (zero)
"" (empty string)
null
undefined
NaN (a special Number value meaning Not-a-Number!)
Either they contain a true or false value or the if statement checks if the variable is defined or undefined or even null.
If contains an expression. And a single variable is an expression that evaluates to its value. Hence it can be used in if condition.
Moreover, if extracts the the Boolean value of the expression. So any non zero variable becomes true and others become false. This helps to write less.
The value should first be converted to a boolean and this is how it's done:
if (x) means if (x != 0 && !isNaN(x)) for numeric values
means x != "" for string values
means x != null && x != undefined for objects
In JS, if a variable has a value, it is true, otherwise, it is false.
For example, "", 0, -0, NaN, etc., all evaluate to false.
http://www.w3schools.com/JS/js_booleans.asp

javascript catching errors, null

When using the following syntax, would the output in console be out ?
I am making sure that I'm catching errors in callbacks and responding properly.
var err = null;
if (err) {
console.log ("in");
} else {
console.log ("out");
}
If your value is one of the following:
0
null
""
false
undefined
NaN
the object is set to false. For any other value it is set to true.
Using either your browser's JavaScript console or a site like http://repl.it/ can be really helpful to test logical expressions. One thing you can always do if you're not sure about the truthiness of an expression (doesn't matter as much for a simple case like this, but can be especially helpful when debugging with watch expressions or conditional breakpoints) is cast it to boolean (true/false) by using the ! operator twice. For example:
!!null === false // true
!!0 === false // true
!![] === true // true
The answer is Yes. But you can test it yourself by running in the browser.

Does Javascript eval correctly evaluate tri-state boolean logic which includes null variables, i.e. unknowns?

I know that Javascript's eval can evaluate expressions like
(true) && (false)
(true) || (false)
etc.
However, does the specification of eval include evaluating statements involving unknowns like
(true) && (null)
(true) || (null)
(null) && (null)
(null) || (null)
etc.
I have tried this in code and seen that it does it, but is this expected behavior? Do the Javascript eval specifications say this?
Does Javascript eval correctly evaluate tri-state boolean logic?
Define "correct". Javascript defines the behavior. Eval in Javascript evaluates the string as a javascript code. SQL defines the behavior as well. The behavior is different in both.
In javascript, null acts like false in boolean expressions (is falsy).
0, NaN, "", null, undefined (and of course false) are all falsy. Objects, non-empty strings and non-zero numbers (and of course true) are all truthy.
&& returns the first falsy argument (if any) or the last argument (lazy AND) and does not evaluate the rest. null && "anything" is null. This can be used in statements like console && console.log && console.log().
|| returns the first truthy argument (if any) or the last argument (lazy OR) and does not evaluate the rest. null || "something" is "something". This can be used in statements like var xhr = XmlHttpRequest || ItsReplacementInOlderBrowsers
!null evaluates to true. if(null) ... evaluates the else branch. The same applies to anything falsy.
Technically, undefined variables are undefined, not null. Both are falsy, though.
null evaluates to false, but keep in mind that there are more details involving null (eg: the use of ===).
Please check out this page. It covers this in more detail:
http://www.mapbender.org/JavaScript_pitfalls:_null,_false,_undefined,_NaN
null is not "unknown", when placed as an operand in a comparison it is simply coerced to a boolean (false). See the row for null in this "truthy table" for more information.
I don't believe there is any "specification" for behavior of eval - all it does it take a string representation of javascript and execute it as javascript in the current context. There is no reason that
eval('(true) && (null)');
would give you different results than
(true) && (null)
Also, eval is evil.

Categories