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.
Related
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)
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!
If we alert(null==undefined) it outputs to true.
What is the logical reason for this.
Is this something that is hard coded in javascript or is there an explanation for this.
The language specification explicitly says:
If x is null and y is undefined, return true
I'm not aware of any records of the language design process that explain the reasoning for that decision, but == has rules for handling different types, and "null" and "undefined" are both things that mean "nothing", so having them be equal makes intuitive sense.
(If you don't want type fiddling, use === instead).
Using the double-equal operator forces Javascript to do type coercion.
In other words, when you do x == y, if x and y are not of the same type, JavaScript will cast one value to another before comparing, like if string and number are compared, the string is always cast into a number and then compared
For this reason, many comparisons of mixed types in JavaScript can result in results that may be unexpected or counter-intuitive.
If you want to do comparisons in JavaScript, it is usually a better idea to use the triple-equal operator === rather than double-equal. This does not do a type coercion; instead if the types are different, it returns false. This is more usually what you need.
You should only use double-equal if you are absolutely certain that you need it.
For the same reason that 0 == "0" - javascript is loosely typed - if something can be converted to something else then it will be unless you use ===
alert(null===undefined);
Will give you false.
As for why these particular conversions happen - the answer is quite simply "the spec says that is what should happen". There doesn't need to be a reason other than "because it says so" for why programming language behave in certain ways.
Edit: Slightly better answer - in Javascript, certain objects/values are 'truthy' or 'falsey' when converted to a boolean. 0 (integer zero), "0" (character zero in a string), "" (empty string) are all false. If there isn't a better comparison to use then the boolean operation applies.
This is why "0" is not equal to an empty string, but both "0" and "" are both equal to false.
we know,
If x is null and y is undefined, return true
undefined == null => true, reason might be both are converted to boolean, as we know javascript performs the type conversion. so that will be resulting the null and undefined converted to false and false == false is true
A better explanation...
In the case of "==" or Loose Equality Operator, if one of the operands is null or undefined and the other is null or undefined, always return true. Otherwise return false. Unlike what other posters falsely state, these are not converted or coerced into new types when using equality operators, but simply follow the rule above.
// TRUE - loose equality operator says use the null vs. undefined rule above which equates them
console.log(null == undefined);
// FALSE - strict equality operator says these are not of the same type, so always return false
console.log(null === undefined);
The == comparison operator doesn't check the types. null and undefined both return false. That's why your code is actually checking if false is equal to false.
> null == undefined;
< true
> false == false
< true
However their types are not equal.
> typeof undefined;
< "undefined"
> typeof null;
< "object"
Because of that, the next statement will return false, as the === comparison operator checks both the types and their value.
> undefined === null;
< false
Today I've gotten a remark about code considering the way I check whether a variable is true or false in a school assignment.
The code which I had written was something like this:
var booleanValue = true;
function someFunction(){
if(booleanValue === true){
return "something";
}
}
They said it was better/neater to write it like this:
var booleanValue = true;
function someFunction(){
if(booleanValue){
return "something";
}
}
The remark which I have gotten about the "=== true" part was that it was not needed and could create confusion.
However my idea is that it is better to check whether the variable is a boolean or not, especially since Javascript is a loosetyped language.
In the second example a string would also return "something";
So my question; Is it neater to loose the "=== true" part in the future, or is it good practise to check the type of the variable as well.
Edit:
In my "real" code the boolean represents whether an image has been deleted or not, so the only values boolValue should ever have is true or false.
0 and 1 for example shouldn't be in that variable.
First off, the facts:
if (booleanValue)
Will satisfy the if statement for any truthy value of booleanValue including true, any non-zero number, any non-empty string value, any object or array reference, etc...
On the other hand:
if (booleanValue === true)
This will only satisfy the if condition if booleanValue is exactly equal to true. No other truthy value will satisfy it.
On the other hand if you do this:
if (someVar == true)
Then, what Javascript will do is type coerce true to match the type of someVar and then compare the two variables. There are lots of situations where this is likely not what one would intend. Because of this, in most cases you want to avoid == because there's a fairly long set of rules on how Javascript will type coerce two things to be the same type and unless you understand all those rules and can anticipate everything that the JS interpreter might do when given two different types (which most JS developers cannot), you probably want to avoid == entirely.
As an example of how confusing it can be:
var x;
x = 0;
console.log(x == true); // false, as expected
console.log(x == false); // true as expected
x = 1;
console.log(x == true); // true, as expected
console.log(x == false); // false as expected
x = 2;
console.log(x == true); // false, ??
console.log(x == false); // false
For the value 2, you would think that 2 is a truthy value so it would compare favorably to true, but that isn't how the type coercion works. It is converting the right hand value to match the type of the left hand value so its converting true to the number 1 so it's comparing 2 == 1 which is certainly not what you likely intended.
So, buyer beware. It's likely best to avoid == in nearly all cases unless you explicitly know the types you will be comparing and know how all the possible types coercion algorithms work.
So, it really depends upon the expected values for booleanValue and how you want the code to work. If you know in advance that it's only ever going to have a true or false value, then comparing it explicitly with
if (booleanValue === true)
is just extra code and unnecessary and
if (booleanValue)
is more compact and arguably cleaner/better.
If, on the other hand, you don't know what booleanValue might be and you want to test if it is truly set to true with no other automatic type conversions allowed, then
if (booleanValue === true)
is not only a good idea, but required.
For example, if you look at the implementation of .on() in jQuery, it has an optional return value. If the callback returns false, then jQuery will automatically stop propagation of the event. In this specific case, since jQuery wants to ONLY stop propagation if false was returned, they check the return value explicity for === false because they don't want undefined or 0 or "" or anything else that will automatically type-convert to false to also satisfy the comparison.
For example, here's the jQuery event handling callback code:
ret = ( specialHandle || handleObj.handler ).apply( matched.elem, args );
if ( ret !== undefined ) {
event.result = ret;
if ( ret === false ) {
event.preventDefault();
event.stopPropagation();
}
}
You can see that jQuery is explicitly looking for ret === false.
But, there are also many other places in the jQuery code where a simpler check is appropriate given the desire of the code. For example:
// The DOM ready check for Internet Explorer
function doScrollCheck() {
if ( jQuery.isReady ) {
return;
}
...
If you write: if(x === true) , It will be true for only x = true
If you write: if(x) , it will be true for any x that is not: '' (empty string), false, null, undefined, 0, NaN.
In general, it is cleaner and simpler to omit the === true.
However, in Javascript, those statements are different.
if (booleanValue) will execute if booleanValue is truthy – anything other than 0, false, '', NaN, null, and undefined.
if (booleanValue === true) will only execute if booleanValue is precisely equal to true.
In the plain "if" the variable will be coerced to a Boolean and it uses toBoolean on the object:-
Argument Type Result
Undefined false
Null false
Boolean The result equals the input argument (no conversion).
Number The result is false if the argument is +0, −0, or NaN;
otherwise the result is true.
String The result is false if the argument is the empty
String (its length is zero); otherwise the result is true.
Object true.
But comparison with === does not have any type coercion, so they must be equal without coercion.
If you are saying that the object may not even be a Boolean then you may have to consider more than just true/false.
if(x===true){
...
} else if(x===false){
....
} else {
....
}
It depends on your usecase. It may make sense to check the type too, but if it's just a flag, it does not.
If the variable can only ever take on boolean values, then it's reasonable to use the shorter syntax.
If it can potentially be assigned other types, and you need to distinguish true from 1 or "foo", then you must use === true.
The identity (===) operator behaves identically to the equality (==) operator except no type conversion is done, and the types must be the same to be considered equal.
Since the checked value is Boolean it's preferred to use it directly for less coding and at all it did same ==true
Since you already initialized clearly as bool, I think === operator is not required.
I think that your reasoning is sound. But in practice I have found that it is far more common to omit the === comparison. I think that there are three reasons for that:
It does not usually add to the meaning of the expression - that's in cases where the value is known to be boolean anyway.
Because there is a great deal of type-uncertainty in JavaScript, forcing a type check tends to bite you when you get an unexpected undefined or null value. Often you just want your test to fail in such cases. (Though I try to balance this view with the "fail fast" motto).
JavaScript programmers like to play fast-and-loose with types - especially in boolean expressions - because we can.
Consider this example:
var someString = getInput();
var normalized = someString && trim(someString);
// trim() removes leading and trailing whitespace
if (normalized) {
submitInput(normalized);
}
I think that this kind of code is not uncommon. It handles cases where getInput() returns undefined, null, or an empty string. Due to the two boolean evaluations submitInput() is only called if the given input is a string that contains non-whitespace characters.
In JavaScript && returns its first argument if it is falsy or its second argument if the first argument is truthy; so normalized will be undefined if someString was undefined and so forth. That means that none of the inputs to the boolean expressions above are actually boolean values.
I know that a lot of programmers who are accustomed to strong type-checking cringe when seeing code like this. But note applying strong typing would likely require explicit checks for null or undefined values, which would clutter up the code. In JavaScript that is not needed.
In Javascript the idea of boolean is fairly ambiguous. Consider this:
var bool = 0
if(bool){..} //evaluates to false
if(//uninitialized var) //evaluates to false
So when you're using an if statement, (or any other control statement), one does not have to use a "boolean" type var. Therefore, in my opinion, the "=== true" part of your statement is unnecessary if you know it is a boolean, but absolutely necessary if your value is an ambiguous "truthy" var. More on booleans in javscript can be found here.
Also can be tested with Boolean object, if you need to test an object
error={Boolean(errors.email)}
This depends. If you are concerned that your variable could end up as something that resolves to TRUE. Then hard checking is a must. Otherwise it is up to you. However, I doubt that the syntax whatever == TRUE would ever confuse anyone who knew what they were doing.
Revisa https://www.w3schools.com/js/js_comparisons.asp
example:
var p=5;
p==5 ? true
p=="5" ? true
p==="5" ? false
=== means same type also same value
== just same value
I was reading a good book on JavaScript.
It started with:
Boolean type take only two literal values: true and false. These are distinct from numeric values, so true is not equal to 1, and false is not equal to 0.
However, I observed following:
if(1==true)
document.write("oh!!! that's true"); //**this is displayed**
I know, that every type in JavaScript has a Boolean equivalent.
But then, what's the truth?
It's true that true and false don't represent any numerical values in Javascript.
In some languages (e.g. C, VB), the boolean values are defined as actual numerical values, so they are just different names for 1 and 0 (or -1 and 0).
In some other languages (e.g. Pascal, C#), there is a distinct boolean type that is not numerical. It's possible to convert between boolean values and numerical values, but it doesn't happen automatically.
Javascript falls in the category that has a distinct boolean type, but on the other hand Javascript is quite keen to convert values between different data types.
For example, eventhough a number is not a boolean, you can use a numeric value where a boolean value is expected. Using if (1) {...} works just as well as if (true) {...}.
When comparing values, like in your example, there is a difference between the == operator and the === operator. The == equality operator happily converts between types to find a match, so 1 == true evaluates to true because true is converted to 1. The === type equality operator doesn't do type conversions, so 1 === true evaluates to false because the values are of different types.
In JavaScript, == is pronounced "Probably Equals".
What I mean by that is that JavaScript will automatically convert the Boolean into an integer and then attempt to compare the two sides.
For real equality, use the === operator.
Try the strict equality comparison:
if(1 === true)
document.write("oh!!! that's true"); //**this is not displayed**
The == operator does conversion from one type to another, the === operator doesn't.
From the ECMAScript specification, Section 11.9.3 The Abstract Equality Comparison Algorithm:
The comparison x == y, where x and y are values, produces true or
false. Such a comparison is performed as follows:
If Type(y) is Boolean, return the result of the comparison x == ToNumber(y).
Thus, in, if (1 == true), true gets coerced to a Number, i.e. Number(true), which results in the value of 1, yielding the final if (1 == 1) which is true.
if (0 == false) is the exact same logic, since Number(false) == 0.
This doesn't happen when you use the strict equals operator === instead:
11.9.6 The Strict Equality Comparison Algorithm
The comparison x === y, where x and y are values, produces true or
false. Such a comparison is performed as follows:
If Type(x) is different from Type(y), return false.
Ah, the dreaded loose comparison operator strikes again. Never use it. Always use strict comparison, === or !== instead.
Bonus fact: 0 == ''
When compare something with Boolean it works like following
Step 1: Convert boolean to Number Number(true) // 1 and Number(false) // 0
Step 2: Compare both sides
boolean == someting
-> Number(boolean) === someting
If compare 1 and 2 with true you will get the following results
true == 1
-> Number(true) === 1
-> 1 === 1
-> true
And
true == 2
-> Number(true) === 1
-> 1 === 2
-> false
Actually every object in javascript resolves to true if it has "a real value" as W3Cschools puts it. That means everything except "", NaN, undefined, null or 0.
Testing a number against a boolean with the == operator indeed is a tad weird, since the boolean gets converted into numerical 1 before comparing, which defies a little bit the logic behind the definition.
This gets even more confusing when you do something like this:
var fred = !!3; // will set fred to true
var joe = !!0; // will set joe to false
alert("fred = "+ fred + ", joe = "+ joe);
not everything in javascript makes a lot of sense ;)
Use === to equate the variables instead of ==.
== checks if the value of the variables is similar
=== checks if the value of the variables and the type of the variables are similar
Notice how
if(0===false) {
document.write("oh!!! that's true");
}
and
if(0==false) {
document.write("oh!!! that's true");
}
give different results
In a way, yes it is 1.
Try these examples in Chrome console:
> 2==true
false
> 1==true
true
> true + 1
2
> true + 2
3
> true + true
2
So, the answer is:
yes, as soon as you use true in any arithmetical context, it's treated as numeric 1, or as Bruce Lee would say, it becomes one. The same way, false is practically zero. But also,
no, if you ask Javascript what it thinks of true, it will say it's a boolean:
> typeof true
'boolean'
It's no surprise in a loosely typed language that sometimes things are not what they are but how you look at them. And if you add true to a string, it will not add 1 but "true" as a string, so at the end of the day, it's by no means equivalent to one. Let me end this with a horrible pun:
true is not a number - but it looks like one
with == you are essentially comparing whether a variable is falsey when comparing to false or truthey when comparing to true. If you use ===, it will compare the exact value of the variables so true will not === 1