This seems to be a common issue, but I didn't find anything that would help me understand.
I have a bunch of items with introduced member of type bool. Some items have introduced value of true, some of false. So coming from c++ I don't expect this to return 'false' (item.introduced is boolean)
if ((show_introduced == "false") && (item.introduced)) {console.log(item.introduced)};
but I acctually see 'false' an well as 'true'.
For me it is the same as, which, of course, never output anything.
var a = false;
if (true && a) {console.log(a)};
Does && works differently in js, or I should find the problem somewhere in the rest of the code?
EDITED: Because item.introduced was read from JSON, it was actually a string, so that's the reason why it didn't work.
'false' in quotes makes it a string, which is true. So, "false" != false
write it like
(show_introduced === false)
EDIT:
Falsy values in Javascript:
false (boolean)
"" (an empty string)
0 (zero)
null
undefined
NaN
if you get anything from above, they are falsy value, and everything else if truthy.
Don't attempt to compare boolean values with true or false, just use them as booleans
if ( showIntroduced )
or
if ( ! showIntroduced )
Logical operators such as && and || in JavaScript behave as you would expect from C/C++, with the same short-circuit rules.
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)
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
I have a simple function in my library that checks the validity of an object reference (object here meaning, a reference to a created HTML element, mostly DIV's). It looks like this:
function varIsValidRef(aRef) {
return ( !(aRef == null || aRef == undefined) && typeof(aRef) == "object");
}
While experimenting i found that this has the same effect:
function varIsValidRef(aRef) {
return (aRef) && typeof(aRef) == "object";
}
I understand there are some controversies regarding the short hand () test? While testing against various datatypes (null, undefined, integer, float, string, array) i could find no difference in the final outcome. The function seem to work as expected.
Is it safe to say that these two versions does the exact same thing?
No, in my opinion these functions don't work the same:
First option
If aRef is not undefined or null and the type of the var is object it returns true.
Second option
First we convert aRef to a boolean. Values like null, undefined and 0 become false, everything else become true. If it is true (so not one of those values) it checks if the type is object.
So the second option return false if aRef is 0, something you don't want. And it isn't option a elegant way to check it, because you check if an object or string or something is equal to a boolean.
And at least they don't return the same thing. The first option returns a boolean, but the second option returns the value you put in the function if (aRef) is false:
varIsValidRef(0);
>>> 0
varIsValidRef('');
>>> ""
varIsValidRef(undefined);
>>> undefined
varIsValidref(null);
>>> null
Because JavaScript use these values as falsy values you don't see the difference between these return values if you use if statements or something like that.
So I suggest you to use the first option.
they are strongly different:
!(aRef == null || aRef == undefined)
this part is evaluated to false with any of these "null", null, "undefined", undefined
(aRef)
while this other with any of these 0, "", false, null, undefined, NaN
Interesting case, but it seems logical for both to behave the same way despite being totally different. Lets see the first staement.
return ( !(aRef == null || aRef == undefined) && typeof(aRef) == "object");
Here,
null and undefined both denote a false state combined with the ! infront, makes it equal to the expression aRef which will return true in case both are either not null or not undefined.
They don't do the same, though they end up with the same results.
The first function is more strict in what it will count as false together, or if it's not, if its an object.
The second function will check if aRef is !false or not any of the falsy values (ie [], null, undefined) and check if the type is an object if it isn't.
I would prefer the first function, since its stricter in what it accepts, but if its all the same the function which performs the best should be used.
As for the controversy, its true that you have to be careful about how/when you use falsy values in equations but if it does what you want it to do (and for that you'll need to know what falsy values are) and you implement it correctly it should be no problem. The two are hard to put together though. So with that, if this does what you want it to do, and nothing more or less, by all means use it.
Is there any better way of doing this?
if(borrar() !== false)
{
alert('tatatata bum bum bum prapra');
}
return false;
If you want to check for false and alert if not, then no there isn't.
If you use if(val), then anything that evaluates to 'truthy', like a non-empty string, will also pass. So it depends on how stringent your criterion is. Using === and !== is generally considered good practice, to avoid accidentally matching truthy or falsy conditions via JavaScript's implicit boolean tests.
If you want an explicit check against false (and not undefined, null and others which I assume as you are using !== instead of !=) then yes, you have to use that.
Also, this is the same in a slightly smaller footprint:
if(borrar() !== !1)
You can use something simpler:
if(!var){
console.log('var is false');
}
If you want it to check explicit for it to not be false (boolean value) you have to use
if(borrar() !== false)
But in JavaScript we usually use falsy and truthy and you could use
if(!borrar())
but then values 0, '', null, undefined, null and NaN would not generate the alert.
The following values are always falsy:
false,
,0 (zero)
,'' or "" (empty string)
,null
,undefined
,NaN
Everything else is truthy. That includes:
'0' (a string containing a single zero)
,'false' (a string containing the text “false”)
,[] (an empty array)
,{} (an empty object)
,function(){} (an “empty” function)
Source: https://www.sitepoint.com/javascript-truthy-falsy/
As an extra perk to convert any value to true or false (boolean type), use double exclamation mark:
!![] === true
!!'false' === true
!!false === false
!!undefined === false
Checking if something isn't false... So it's true, just if you're doing something that is quantum physics.
if(!(borrar() === false))
or
if(borrar() === true)
Like this:
if(borrar())
{
// Do something
}
If borrar() returns true then do something (if it is not false).
I always (thing != undefined || thing != null)?...:...; check. Is there any method will return bool after this check in javascript or jquery ?
And how would you add this check in jquery as a function?
if (thing)
{
//your code
}
Is that what you are looking for?
In Javascript, the values null, undefined, "", 0, NaN, and false are all "falsy" and will fail a conditional.
All other values are "truthy" and will pass a conditional.
Therefore, you can simply write thing ? ... : ....
Try this
function SringisEmpty(str) {
str=str.trim();
return (!str || 0 === str.length);
}
As the others here have mentioned, several things evaluate as "falsy" that you might not want to (such as empty strings or zero). The simplest way I've found in JavaScript to check for both null and undefined in one statement is:
thing != null
This is using type coercion (double equals instead of triple equals), so undefined values are coerced to null here, while empty strings, zero, etc. do not.