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.
Related
Im trying to understand why comparing standard functions always returns a Boolean false
Like for the isNaN function
>isNaN === true
false
>isNaN === false
false
But
>Boolean(isNaN)
true
Now to make things a little more interesting
>!isNaN === false
true
>!isNaN === true
false
This occurs with standard function like Number, Object etc.
Does anyone know what happens under the hood in JavaScript ?
I recommend you read truthy and falsy values, in short, isNaN is a function, it actually exists, so you can use it as a short hand for true checking, very useful for everyday programming.
When you use === type checking is done, and then a bool != a function.
When you pre-pend ! to it, you are actually casting to boolean type and reversing the value to true so that is why the comparison changes.
Here are the lists of Truthy and Falsy values.
isNaN is truthy because it's a function.
>isNaN === true
false
>isNaN === false
false
Because isNaN is a function.
>Boolean(isNaN)
true
Because again, isNaN is a function and functions are truthy values. Please refer following to see output specs for Boolean
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.
This question already has answers here:
Does a javascript if statement with multiple conditions test all of them?
(10 answers)
Closed 6 years ago.
I'm checking the number of digits in a string using the match and length properties. Here is the codepen with my function http://codepen.io/PiotrBerebecki/pen/redMLE
Initially when returning numberOfDigits.length I was getting an error message (Cannot read property 'length' of null). I've solved this issue by changing the line to (numberOfDigits && numberOfDigits.length).
This works but I would like to get a better understanding why the new statement can be executed now. Does the interpreter execute the `numberOfDigits.length now?
Also, why are we getting the same errors when the operands are reversed (numberOfDigits.length && numberOfDigits)?
Here is the full JavaScript code:
function checkLength(str) {
let numberOfDigits = str.match(/\d/g);
return (numberOfDigits && numberOfDigits.length);
}
console.log( checkLength('T3xt w1th sOme numb3rs') );
console.log( checkLength('Text with some numbers') );
UPDATE 1:
The answers below explained that:
The order of the operands in the && expression counts.
JavaScript optimises the && operator and if the first operand evaluates to null then JavaScript does not check the second one as the expression cannot evaluate to nothing else than null / false.
JavaScript tries to optimise the && operator:
numberOfDigits && numberOfDigits.length
If numberOfDigits is a falsy value (and null is falsy), then the entire expression will be falsy and there is no need to evaluate numberOfDigits.length.
Falsy values are: undefined, null, 0, '', false, NaN. One way to check if something is falsy is to use the Boolean(falsyValue) === false (or more practical but less verbose ! falsyValue).
This is a side effect of the && operator. I can recommend to avoid using it and transform the code to something readable:
function checkLength(str) {
let numberOfDigits = str.match(/\d/g);
return Array.isArray(numberOfDigits) ? numberOfDigits.length : 0;
}
"Does the interpreter execute the `numberOfDigits.length now?"
No, JavaScript short-circuits logical expressions - as soon as result is known (i.e. first operand in and is falsy or first operand in or is truthy), no further operations are executed in the expression.
Docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators
also, beware: && and || do not necessarily return Booleans in JavaScript
the reason is that when the interpreter sees two operations connected with a logical and (&&) it will first execute the former, and only if it is evaluted to true then it will execute the latter.
that is why since it found numberOfDigits to be null, which in JS is equivalent to false, it stops execution and never crashes on numberOfDigits.length.
the other way around will, of course, crash.
on a logical OR (||) the interpreter will stop evaluating after the first statement to be true.
I believe the reason is that the order of conditions counts.
The numberOfDigits condition gets evaluated first, so if that is false, the rest of the conditions are not evaluated and you won't get an error.
In the other order you would try to read "length" property of null, generating an error.
"And" logic will be executed as below.
true & true = true
false & anything = false`
If first condition fails then there is no point of executing second one.
so it wont execute numberOfDigits.length if numberOfDigits is null or undefined so no error in the below case.
(numberOfDigits && numberOfDigits.length) => false
false && anything => false
In same way if first condtion is not null then it will execute second condition.
(numberOfDigits && numberOfDigits.length) => true
true && true (must be) => true
Note : In javascript null and undefined are interpreted as false
in conditional statements.
I use jslint to check my javascript and I got a JSLint error which I can't find.
The expression is:
var foo = (bar === true ? true : false);
The Error is:
Expected '!!' and instead saw '?'.
The purpose of the expression is that I want the value of var to be the boolean true and not 1 or "not null" or any of the other "truthy" values. only the value true will result in an assignment of true
What is the best way to express that?
jslint is suggesting the following, as x?true:false is equvivalent to !!x:
var foo = !!(bar === true);
However you can simplify it more, as === always returns a boolean:
var foo = bar === true;
If bar is true, bar === true will evaluate to true. You don't need the ternary at all.
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).