I'm confused with the code below:
if(undefined){
//code will not be executed
}
and
if(!undefined){
//code will be executed
}
Is that mean the "undefined" equals with false?
Here the question related,but no one point above situation out.
It means that undefined is a falsy value, list of falsy values are:
"" // Empty string
null // null
undefined // undefined, which you get when doing: var a;
false // Boolean false
0 // Number 0
NaN // Not A Number eg: "a" * 2
If you negate a falsy value you will get true:
!"" === true
!null === true
!undefined === true
!0 === true
!NaN === true
And when you nagate a truthy value you will get false:
!"hello" === false
!1 === false
But undefined is not equal false:
undefined === false // false
undefined == false // false
And just for the fun if it:
undefined == null // true
In javascript strict mode, undefined is not false, but javascript try to convert the object or var to a boolean value (this is called in javascript truthy value), that's the reason you got an undefined as false. This happens with null also, for example.
You can force that with this strict no equality:
if(undefined!==false) console.log("Is not false");
Please take a look below checked falsy values:
""==false?
Ans: true
null == false?
Ans: false
undefined == false?
Ans: false
0 == false?
Ans: true
NaN == false?
Ans: false
null == NaN?
Ans: false
We can see that null == false,undefined == false,null == NaN, and NaN == false are not true
That means they are not equal. From the above result, we got 3 falsy values group:
The False group
The Null group and
The NaN group
But a negative falsy value is always true:
!"" === true
!null === true
!undefined === true
!0 === true
!NaN === true
For example:
To check true value of dataTitle variable
if(dataTitle && (dataTitle != null))
{
console.log('hi');
}
The above statement will check the false group as well as the null group
To check false value of dataTitle variable
if(!dataTitle)
{
console.log('hi');
}
//or
if(dataTitle==null || dataTitle===false)
console.log('hi');
In javascript, undefined and null are empty properties declared on the global scope.
Their value doesn't equal false; they both have the initial value of primitive undefined.
undefined == false // false
With that said, both will result in false value upon a programmatic true/false evaluation. In your example, you used a logical NOT operator (MDN):
Returns false if its single operand can be converted to true; otherwise, returns true
The negation operator first evaluated undefined as false, and then negated the value to true. You can illustrate the process roughly like this:
if (!(!!undefined)) {
// code will be executed
}
Related
Is there a difference between !a and a===null in JavaScript?
I am working on a project where it is behaving differently.
I am not talking in terms of Boolean values though as !true will not me same as true===null
if (!this.props.user) is resulting to true,
where as if (this.props.user === null) is resulting to false
!a will return true if a is any Falsy value (e.g, false, undefined, null, 0...)
a === null will only return true if a is null.
like #Spectric answer.
a === null need to have same type to return true.
even the value has falsy value (e.g, false, undefined, 0). it will return false because the value is not same with null
As we all know null & undefined are falsy values.
But why does the first snippet of code work and the second does not?
// #1
if (!undefined) { // or (!null)
console.log("hi"); // => hi
}
enter code here
// #2
if (undefined == false) { // or (null == false)
console.log("hi"); => never gets executed
}
Is there a specific reason for this or is it just a language specification?
Other falsy values such as 0, "", false (except NaN) work and I guess they are being converted to false.
Because being "falsey" is not the same as being equal to false, which is why that term needed to be invented.
undefined only equals null, but not false by definition:
undefined == null // true
undefined == false // false
And yes thats not really for a specific reason, just to confuse people:
[] == false // true
So all you can learn from thisis, is that you should always use ===
First of all, undefined and null are two different primitive values.
undefined means that the variable is created but not been assigned any value
and so it acts as a falsy value, while null represents a non-existing reference and so it's falsy too,
Now in your case,
if(undefined==false){
//the code in here will never be executed
}
->As undefined has no value while false does.so,
undefined==false
//is false as false(with a value) can't be
//equal to undefined which has no value
undefined and null are falsy in javascript but,
var n = null;
if(n===false){
console.log('null');
} else{
console.log('has value');
}
but it returns 'has value' when tried in console, why not 'null' ?
To solve your problem:
You can use not operator(!):
var n = null;
if(!n){ //if n is undefined, null or false
console.log('null');
} else{
console.log('has value');
}
// logs null
To answer your question:
It is considered falsy or truthy for Boolean. So if you use like this:
var n = Boolean(null);
if(n===false){
console.log('null');
} else{
console.log('has value');
}
//you'll be logged null
You can check for falsy values using
var n = null;
if (!n) {
console.log('null');
} else {
console.log('has value');
}
Demo: Fiddle
Or check for truthiness like
var n = null;
if (n) { //true if n is truthy
console.log('has value');
} else {
console.log('null');
}
Demo: Fiddle
A value being "falsy" means that the result of converting it to a Boolean is false:
Boolean(null) // false
Boolean(undefined) // false
// but
Boolean("0") // true
This is very different from comparing it against a Boolean:
null == false // not equal, null == true is not equal either
undefined == false // not equal, undefined == true is not equal either
// but
"0" == true // not equal, however, `"0" == false` is equal
Since you are using strict comparison, the case is even simpler: the strict equality comparison operator returns false if operands are not of the same data type. null is of type Null and false is of type Boolean.
But even if you used loose comparison, the abstract equality algorithm defines that only null and undefined are equal to each other.
Depending on what exactly you want to test for, you have a couple of options:
if (!value) // true for all falsy values
if (value == null) // true for null and undefined
if (value === null) // true for null
In general you should always prefer strict comparison because JS' type conversion rules can be surprising. One of the exceptions is comparing a value against null, since loose comparison also catches undefined.
=== checks for identity - the exact same type and value. So null !== false firstly because they are not the same type, thus will not match when using ===.
If you just want to check for any falsey value, then check with:
if (!n)
If you want to specifically check for null, then check for null like this:
if (n === null)
I have a method hitTest that check for collision detection and can return a Point object (if a collision is happened) or (if there is no collision) it returns null or undefined (i haven't deeply understand when it return null or undefined but i trust chrome console).
I have to test collision on 2 objects. And check if one or the two collisions are happening. I have tried this code:
var result1 = hitTest(player, object1);
var result2 = hitTest(player, object2);
if( result1 || result2 ) { blabla() };
but it doesn't work.
now.. i know that js is reallly a tricky language and i think about a smart way to do this without writing typeof 4 times. I'm thinking about python short-circuit logical operators...
You can use &&, it returns the first detected false/null/undefined/0, i.e. if won't pass, if either result1 or result2 is null.
for this type of thing, underscore.js is beautifull: http://underscorejs.org/#isNull and http://underscorejs.org/#isUndefined
I use these helpers frequently to get around edge cases in JS such as the ones you mentioned
You wouldn't need to write typeof 4 times already but anyway;
Coercion paradigm for conditional statements and operators:
//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
From Mozilla:
Logical AND (&&)
expr1 && expr2
If the first operand (expr1) can be converted to false, the && operator returns false rather than the value of expr1.
Logical OR (||)
expr1 || expr2
Returns expr1 if it can be converted to true; otherwise, returns expr2. Thus, when used with Boolean values, || returns true if either operand is true; if both are false, returns false.
true || false // returns true
true || true // returns true
false || true // returns true
false || false // returns false
"Cat" || "Dog" // returns Cat
false || "Cat" // returns Cat
"Cat" || false // returns Cat
true && false // returns false
true && true // returns true
false && true // returns false
false && false // returns false
"Cat" && "Dog" // returns Dog
false && "Cat" // returns false
"Cat" && false // returns false
Additionally, you can use a shortcut isset() method just like in PHP to properly validate your objects:
function isSet(value) {
return typeof(value) !== 'undefined' && value != null;
}
So; your code would be:
var result1 = hitTest(player, object1),
result2 = hitTest(player, object2);
if ( isSet(result1) && isSet(result2) ) { blabla(); };
Can someone explain why in javascript,
alert({} == true) shows false
if ({}) alert('true') shows true ?
What's different in the if condition that changes the result?
I wanted to write some shorthand argument validator obj || (obj = {}); and I was baffled by this discovery.
if ({}) alert('true') -> true
{} is an object, which, when evaluated in the context of an if statement, gets coerced to a Boolean, and since Boolean({}) evaluates to true, you get if (true). This is documented in the ECMAScript specification, Section 12.5 The if Statement:
The production If Statement : if ( Expression ) Statement is evaluated
as follows:
Let exprRef be the result of evaluating Expression.
If ToBoolean(GetValue(exprRef)) is false, return (normal, empty, empty).
Return the result of evaluating Statement.
alert({} == true) -> false
This one is more tricky. 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, {} == true will be evaluated as {} == Number(true), which is evaluated to {} == 1, which is false.
This is also why 1 == true evaluates to true, but 2 == true evaluates to false.
{} is not true so it won't show up in your first example. In your second example {} is not false so it will pass the test.
Like my teacher used to say, you can't compare potatoes and carrots.
It's not only with arrays, it will work with anything:
alert(3 == true); // shows false
if (3) alert('true'); // shows true
In boolean operations, generally anything that is not 0 evaluates to true.
http://jsfiddle.net/QF8GW/
if (0) console.log("0 shows true"); // does not log a value
if (-1) console.log("-1 shows true");
if (12345) console.log("12345 shows true");
if ({}) console.log("{} shows true");
if ([]) console.log("[] shows true");
All of these except 0 will evaluate to true.
However, their values, when compared to true will not evaluate to true.
// logs the statement (1 and true are the same.)
if (1 == true) console.log("1==true shows true");
if (12345 == true) console.log("12345==true shows true"); // does not log
I tried in jsfiddle.net and only try in the first alert says false, the IF does not alert true.
alert({} == true) //display "false"
if({} == true)
{
alert("it's true");
}else
{
alert("it's false"); // <-- alert this
}
( snippet )