I came across a condition which made me strange. I am working on React in that I have given a condition on a render method like this:
if (!this.props.allYearData || !this.props.Growth)
return <Loading />;
However, my page always shows the loading symbol. I console data what I have given in if condition and both data was in define state, but my Growth was showing 0 value., so I commented out this.props.Growth and my page loaded. So I am just wondering why JavasSript didn't consider 0 as a defined value? I always has impression that ! means undefined. Can someone explain this?
0 is falsy. ! is a negation operator. Thus !0 is going to be "not falsy" or truthy. Truthy values in an if statement condition result in the if block will be evaluated.
Details
See MDN for more information on Truthy/Falsy.
Here are a few examples:
true // truthy
false // falsy
!true // falsy (negation operator, it says "opposite of")
!false // truthy
0 // falsy (this is because booleans are represented as 0 and 1 in binary,
// 0 being false)
!0 // truthy
undefined // falsy
!undefined // truthy
Your impression of the ! operator is fairly off in JS (and most other languages). It doesn't mean undefined, it generally always means "not", so:
if (!condition)
means "if condition is not true"
false, undefined, null, 0 and an empty string like '' will all return "falsey" in javascript if used in a conditional operator like if, while everything else will return "truthy". This is a fairly standard practice in most loosely typed languages, you find similar behavior in python, though one important difference is that in JS, an empty array is NOT falsey, whereas in python it is.
If you ONLY want to know if the value is not undefined, it's simple:
if (this.props.allYearData !== undefined || this.props.Growth !== undefined)
Related
I've encountered something which seems inconsistent on the part of the interpreter, though I know it probably makes sense and I just don't understand it. It has to do with evaluating the equality of a truthy/falsy values and Booleans.
Example 1:
if (document.getElementById('header')) {
//run code here
}
If the element with an id of 'header' is found in the document, the condition is true because the presence of an object is considered truthy.
Example 2:
if (document.getElementById('header) == true) {
// run code here
}
Presuppose the referenced element is found within the document. It was explained to me that this condition will evaluate to false because a truthy value does not equal a Boolean value of true.
This doesn't seem to make sense. The presence of the object is considered truthy due to type coercion, so therefore it should equal true even though the data types are different.
Consider the following:
(false == 0) // evaluates to true
(false === 0) // evaluates to false
This is a case where false equals 0 is true when you use the equals to operator. Because 0 is considered a falsy value, it is equal to the Boolean value of false. The values are the same and the data types are different.
To me, (document.getElementById('header') == true) and (false == 0) are the same thing. And yet, they both evaluate to something different.
Can someone please explain to me why this is the case? I've been reading different descriptions of this, but no one seems to explain it in-depth.
document.getElementById('header') returns a DOM object or null. So, in your second comparison (assuming it is resolving to an object), you're comparing:
if (obj == true)
A DOM object is not == to true.
To see why, you have to go to the ECMAScript rules for automatic type conversion which you can see in the ECMAScript 5 specification here: http://www.ecma-international.org/ecma-262/5.1/#sec-11.9.3.
The operative rules when comparing an object == boolean are all the way down to rules 9 and 10.
If Type(x) is Object and Type(y) is either String or Number, return the result of the comparison ToPrimitive(x) == y.
Return false.
Rule 9 is the first rule where Type(x) is Object and the two types are not the same, so it's the first one to check.
Since Type(y) is Boolean, it does not pass rule 9.
Thus, when it hasn't passed any rules 1-9, it evaluates to false.
When you do this comparison:
(false == 0) // evaluates to true
you're looking at rule #6 in the type conversion rules which will do:
ToNumber(false) == 0
which will resolve to:
0 == 0
which will be true.
For this one:
(false === 0)
Whenever you use ===, if the two types are different, then the result is immediately false so this evaluates to false. === requires type AND value to be the same so if the type is not the same, then it doesn't even attempt to compare the value. No type conversion is ever done with === which is one of the useful reasons to use it.
You should understand that the truthy and falsey rules apply to only a single check like this with no == or === in the comparison:
if (obj)
They do not apply when you are comparing x == y. For that, you have to refer to the type conversion rules in section 11.9.3 of the specification (linked above).
Presuppose the referenced element is found within the document. It was explained to me that this condition will evaluate to false because a truthy value does not equal a Boolean value of true.
You're right, it doesn't make sense because whoever explained that to you is wrong.
The presence of a DOM element will evaluate to true and if it doesn't exist, it will evaluate to false (with a double-equals vs. triple). If in the event they are using triple equals, you can simply try:
!!document.getElementById('someNodeId') and it will return a boolean value.
You can always try this in the console if you want to be sure.
!!document.getElementById('notify-container');
>> true
!!document.getElementById('non-existing-node-goes-here');
>> false
Edit: I didn't read the example clearly or the example was updated. Yeah, you're using double equal. The element is truthy, but it's not "true".
When the if() statement is executing, it's checking if there is a truthy value inside the parenthesis. The == operator is checking whether the two values are equal in nature. In JavaScript, true and false are == to 1 and 0, respectively; hence why you can type (4 + true) and get 5, or false*6 and get 0!
When you type something == true, you're really checking if something == 1.
If something isn't a boolean value it's not going to be the same as 1.
Perhaps an explanation of your postulate "The presence of the object is considered truthy due to type coercion, so therefore it should equal true."
If any truthy value is equal to true,
then any truthy value is equal to any truthy value (by transitive property, a=b,c=b, therefore a=c),
however, this would not hold true for all cases! ("blue" == "green", 5 == "six" simply because they are each non-false values. This would make the == fairly worthless!)
The conclusion does not follow, so therefore the postulate is invalid. In general, you should use === if you need to check if two things are truly the same thing.
Hopefully this clears things up!
I have a question concerning some concepts in JavaScript such as (truthy, true) and (falsy, false).
I know the type of 1 is not true but the question is: why 1 == true?
What was the main reason of ECMAScript to consider 1 or "ghsagh" as true?
I also cannot understand the meaning of truthy and falsy.
What was the benefit of this consideration?!
JavaScript likes to convert values to other types implicitly whenever possible. Because of that, when comparing booleans to other types of variables, JavaScript uses the same logic as older programming languages. A value that represents empty, null, or zero (such as 0, or "") evaluates to false, and any other value (such as 1, 5, -19, "ghsfsah", or other meaningful content) evaluates to true.
Why does it do this? Well for one it allows developers a small shortcut when checking to see if a variable has content. For example, if a user doesn't give input in a text field, we can easily check to see if a field is empty and prompt the user.
if ( !textfield.value ) {
alert( "Please enter something in the text box" );
}
If you need to see if something is actually true or false, you can use ===.
JavaScript is very flexible about the types of values it requires. If JavaScript wants a boolean, it will convert whatever value you give it to a boolean.
Some values (“truthy” values) convert to true and others (“falsy” values) convert to false.
The following values convert to, and therefore work like, false:
undefined
null
0
-0
NaN
"" // the empty string
All other values, including all objects (and arrays) convert to, and work like, true.
As an example, suppose that the variable o either holds an object or the value null. You can test explicitly to see if o is non-null with an if statement like this:
if (o !== null){
....
}
The strict not-equal operator !== compares o to null and evaluates to either true or false. But you can omit the comparison and instead rely on the fact that null is falsy and objects are truthy:
if (o){
....
}
In the first case, the body of the if will be executed only if o is not null. So the code block will execute even if o is set to undefined.
The second case is less strict: it will execute the body of the if only if o is not false or any falsy value (such as null or undefined). Which if statement is appropriate for your program really depends on what values you expect to be assigned to o. If you need to distinguish null from 0 and "", then you should use an explicit comparison.
This question already has answers here:
What is the !! (not not) operator in JavaScript?
(42 answers)
Closed 8 years ago.
Recently - learning and working with angularjs api. Looked at the source code for angular.isElement(). I understand foundationally what "!!" does to the return value of the expression when using it, but not understanding why use it - is it not redundant? Searched for !! not much info. Link to api page.
function isElement(node) {
return !!(node &&
(node.nodeName // we are a direct element
|| (node.prop && node.attr && node.find))); // we have an on and find method part of jQuery API
}
Update: regarding being marked as a duplicate — Thx. Weird that i did not see that question on original search.
Though many long answers- reading them - they don't really answer where I am confused. Is it not redundant in this case? Wouldn't it return true without !!. thx
!! is used to convert a "truthy" or "falsey" value into true or false, and is equivalent to Boolean(). For example
!!0 // false
!!1 // true
function Obj() {}
o = new Obj()
!!o // true
!!'' // false
!!'hi' // true
(1 && 3 && 4) // 4
!!(1 && 3 && 4) // true
!!x can be read out loud as 'not not x'. The first ! turns a truthy value to false and a falsey value to true. Then the second ! reverses this so that the truthy value becomes true and the falsey value becomes false.
As to why people use that rather than Boolean, this appears to be just a convention. It is concise and easily understood by most programmers, and there is possibly some resemblance to how people do things in C or C++. It is not particularly faster.
EDIT. You want to know why it is not redundant in this particular case. We may have no idea what type of object is being passed to the function as node. && in javascript works from left to right and if all of the operands are truthy, returns the right-most operand, rather than true or false. Try redefining isElement without the !!. We get the following responses:
isElement('hi') // undefined
isElement(0) // 0
isElement(3) // undefined
isElement({nodeName: 'something'}) // 'something'
isElement({prop: 100, attr: this, find: Infinity}) // Infinity
These results will in fact be handled well most of the time -- in any if statement the truthy values ('something', Infinity) will be treated as true and the falsey values (undefined, 0) treated as false. But still, the user of the API will expect it to return only true or false and there will occasionally be unexpected behaviours if it is allowed to return any of these things.
!!var === Boolean(var). This was not always true, but it is for modern interpreters. In the old interpreters, Boolean(var) always returned true, because it is an object, so people used !! to get the equivalent value.
...and of course it is shorter
It converts the value to a boolean. !! isn't an operator itself. It is just the negation operator ! twice.
The && operator does not always return a Boolean. It actually returns either false or the second value.
That's why !! is used to force it to be a Boolean, because the APIA is apparently supposed to return one.
I'm wondering what the core difference is between the conditional syntax below?
if (something) {
// do something
}
vs.
if (something == true) {
// do something
}
Are there any differences?
Edit: I apologize. I made a typo when the question was asked. I did not mean to put a triple equals sign. I know that triple equals is a strict operator. I was meaning to ask if '==' is the equivalent of if (something).
The difference is that in if(something), something is evaluated as boolean. It is basically
if(ToBoolean(something))
where ToBoolean is an internal function that is called to convert the argument to a boolean value. You can simulate ToBoolean with a double negation: !!something.
In the second case, both operands are (eventually) converted to numbers first, so you end up with
if(ToNumber(something) == ToNumber(true))
which can lead to very different results. Again, ToNumber is an internal function. It can be simulated (to some degree) using the unary plus operator: +something == +true. In the actual algorithm, something is first passed ToPrimitive if something is an object.
Example:
Assume that
var something = '0'; // or any other number (not 0) / numeric string != 1
if(something) will be true, since '0' is a non-empty string.
if(something == true) will be false, since ToNumber('0') is 0, ToNumber(true) is 1 and 0 == 1 is false.
EDIT: Below only holds true for the original question, in which the === operator was used.
The first one will execute the body of the if-statement if something is "truthy" while the second will only execute it if it is equal in type and value to true.
So, what is "truthy"? To understand that, you need to know what is its opposite: falsey. All values in JavaScript will be coerced into a Boolean value if placed in a conditional expression. Here's a list of falsey values:
false
0 (zero)
"" (empty string)
null
undefined
NaN
All other values are truthy, though I've probably missed some obscure corner case that someone will point out in the comments.
Here's my answer to the updated question:
The conditional if (something) and if (something == true) are equivalent, though the second is redundant. something will be type coerced in the same way in either case. This is wrong. See Felix Kling's answer.
if(something) is equivalent to if(someting == true).
The == operator checks for equality while === checks for sameness. In this case, any truthy value will cause the condition to be met for the first one, but only true will cause the condition to be met for the second one.
EDIT: Felix Kling's answer is correct. Please reference that instead.
Now that the question has changed from === to ==, no, there is no practical difference.
There are a couple ways to look at it. The first example evaluates to see if "something" has a true-like or positive value. So as long as it is not 0, negative, null, or empty it should evaluate the contents of that if statement.
In your second statement you are testing to see if "something" is the equivalent of boolean true. Another words "TRUE" or 1. You could also do a "===" comparison so that it has to be identical to what your comparing it to. So in this case if you did something === true then "something" would have to be boolean true, the value of 1 would not suffice.
There is no difference between the two conditions thing == true and just thing.
There is a large difference between thing === true and just thing, however.
In javascript, values are coerced to a boolean when they are put in a condition. This means all values of all types must be able to be coerced to either true or false. A value that coerces to true is generally called "truthy", and a value that coerces to false is called "falsey".
The "falsey" values are as follows:
NaN (not a number)
'' (empty string)
undefined
null
0 (numeric 0)
Everything else evaluates to true when coerced. This jsFiddle will help you keep track of what is "truthy" and what is "falsey".
The identity operator (===) does NOT perform any type coercion: if the types are different, the comparison immediately fails.
I use the following code currently
if (oldValue) ...
It works well in case oldValue is null, but in case it is 0, it also returns false, when I expect true. So, how should I check for null value? I was thinking about
if (oldValue!=null) ...
but it doesn't work as I've expected.
To answer your question directly, if your allowed values are 0 and 1 the if statement should look like:
if (0 === oldValue || 1 === oldValue) {
...
}
This is (in my opinion) the clearest way to state which values are allowed.
For a more details explanation see below:
This has to do with truthy and falsy values.
null evaluates to false, as do 0, "", undefined and NaN, these are called falsy values.
Likewise, some values evaluate to true. Such as: "a string", "0" (non empty string "0"), any number other than 0 (including negative numbers), Arrays and Objects (even empty ones). These are truthy values.
There are some unexpected results:
"" == false // true
0 == false // true
but:
NaN == false // false
null == false // false
In practice you should always use the identity operator === instead of equality (==). This ensures that you know what type your variable is expected to be (String, Number, Object) and what the exceptional states are.
Some examples:
If you're getting a value from an input field it will always be a string - the special case is the empty string. Coincidentally this is a falsy value.
If you're counting elements and you need to do something special in case there are no elements - the special case is 0. Coincidentally this is a falsy value.
If you're trying to parse a number from a string using parseInt or parseFloat - the special case NaN (check with isNaN()). Coincidentally this is a falsy value.
If you're checking if a substring occurs within a string using indexOf - the special case is -1 (because 0 is a valid index). This is not a falsy value, but if(str.indexOf(substr)) is most certainly wrong because it is unclear the author knows about the possibly allowed value 0 (which is falsy)
The point here is: the special cases usually are well defined. Harnessing that allows you to always use the identity operator ===. The equality operator == and falsiness is a common source of bugs.
For reference:
"" === false // false
0 === false // false
NaN === false // false
null === false // false
false === false // true (of course)
NaN === NaN // strange, but makes sense
"a" === "a" // yay!
Short answer: If you want to test exactly whether the variable does not have the value null, then change your code to:
if (oldValue !== null) ...
(However, you should think about whether the oldValue might be undefined rather than null, which would have to be a separate case.)
See Frits van Campen's answer for the details of the difference between ==/!= and ===/!==.