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
Related
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
}
I'm having difficulty understanding the "atDest" variable declaration in this lesson that appears to be taking on two values (both a boolean and an object).
http://eloquentjavascript.net/07_elife.html
actionTypes.eat = function(critter, vector, action) {
var dest = this.checkDestination(action, vector);
var atDest = dest != null && this.grid.get(dest);
if (!atDest || atDest.energy == null)
return false;
critter.energy += atDest.energy;
this.grid.set(dest, null);
return true;
};
Any tips here would help. When I try testing out variables with similar syntax with console.log I've been noticing that the object value overrides the bool. Is this an inherent Javascript trait where a variable can have more than one value?
The boolean operators || and && actually return the value of one of the specified operands.
var a = 5 || false; // 5 is assigned to a
var b = true && 5; // 5 is assigned to b
The logical && returns the first expression if it can be converted to false, otherwise it returns the second expression (or 5 in the example above)
So if dest != null is not false in the following statement
var atDest = dest != null && this.grid.get(dest);
then atDest is assigned the value of this.grid.get(dest).
Here is the documentation you are looking for.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness
http://dorey.github.io/JavaScript-Equality-Table/
The gist is that in JavaScript everything can be interpreted as boolean. The above doc makes it very clear. Values like null, undefined, NaN, 0, "" will be interpreted as falsy. What !atDest really means is basically to check if atDest is not assigned (likely null or undefined).
The next part is also worthy mentioning. atDest.energy == null is a loose equality check (notice the == instead of ===). This check will actually check for both null and undefined. But the difference between atDest.energy == null and !atDest.energy is that atDest.energy == null will not match 0, "", nor NaN.
JavaScript values can be falsy like
false
0 (zero)
"" (empty string)
null
undefined
NaN (a special Number value meaning Not-a-Number!)
or truthy, which is everything else including the empty object {}. Falsy values are equivalent to false in a boolean check and truthy values are equivalent to true in a boolean check.
Now, if you attempt to read a non-existent property on an object you'll get undefined. However if you attempt to read a non defined property off the special value of null or undefined, you will get an error. Something like
Unable to get property 'energy' of undefined or null reference
if you attempt to read atDest.energy when atDest is null or undefined.
So if you want to check if a property is of value xyz on an object that you are not sure is null or undefined, you have to do 2 things
First check if you can actually read the property without error i.e. that the object is not null or undefined.
Then read the property and do the check.
In your example, this
if (!atDest || atDest.energy == null)
does pretty something equivalent. This part
!atDest
evaluates to false if atDest is null or undefined (because both these values are falsy) and short circuits the loop (i.e. doesn't read atDest.energy). In effect what the code attempts to do is this
if (atDest === undefined || atDest === null) {
.... do something ....
else if (atDest.energy == null) {
.... do same something ....
else
.... do something different ....
I understand that both empty string and null are falsy according to the ECMAScript. If both are falsy then why doesn't the following evaluate to true?
var emptyString = '';
if (emptyString == null) {
console.log('emptyString == null');
}
else {
console.log('emptyString does not == null'); // but why?
}
both empty string and null are falsy
Yes, but that doesn't mean all falsy values would be equal to each other. NaN and 0 are both falsy as well, but they're definitely not equal. The reverse doesn't hold either, "0" == 0 but "0" ain't falsy.
The sloppy equivalence of values is defined by the Abstract Equality Algorithm and its type coercions, and null simply isn't == to anything but undefined.
The more commonly used abstract comparison (e.g. ==) converts the operands to the same Type before making the comparison.
Here, null is a falsy value, but null is not == false
The falsy values null and undefined are not equivalent to anything except themselves:
(null == false); // false
(null == null); // true
(undefined == undefined); // true
(undefined == null); // true
since the other operand is null( which is also a type in javascript ), the abstract comparison of empty string(falsy value) and null doesn't give a truthy value.
I think this will help you.
Comparison Operators
and this too
Truthy and Falsy: When All is Not Equal in JavaScript
I want to check if a value in an object is undefined:
I have the following code
for (i=0; i<extra.points.length; i++){
console.log(extra.points[i].coord)
if (!extra.points[i].coord === undefined){
console.log("creating");
//rest of code
}
}
extra has the following values:
{
points:[
{name:'adp', coord:undefined},
{name:'pdp', coord:{x:324, y:482}}
],
bicetrix:[]
}
But it won't enter the if at all. What am I doing wrong?
The order of operators matters. Not ! is evaluated before ===.
I guess you mean
if (extra.points[i].coord !== undefined){
console.log("creating");
//rest of code
}
What you have written means "if not(something) strictly equals to undefined". Not something is always boolean i.e. true or false. Which by all means can't be equal to undefined.
!undefined is true, and true === undefined is always false.
I am getting the following javascript error:
'value' is null or not an object
Can someone please let me know what is the best way to check whether an object's value is NULL in javascript as I have been using:
if ((pNonUserID !== "") || (pExtUserID !== "")){
Is this correct or is there a better way?
Thanks.
You don't have to do that:
var n=null;
if(n)alert('Not null.'); // not shown
if(!n)alert('Is null.'); // popup is shown
Your error implies otherwise:
var n=null;
alert(n.something); // Error: n is null or not an object.
In the case above, something like this should be used:
if(n)alert(n.something);
The !== operator returns true when two variables are not the same object. It doesn't look at the values of the objects at all
To test if something is null:
myVar == null
Your code was testing to see if the variable 'pNonUserId' referred to the same object as "", which can never be true as "" will always be a new instance of the empty string.
As an aside, a test such as:
var n = something();
// do stuff
if (n)
doSomethingElse();
Is a bad idea. If n was a boolean and false, but you were expecting the if block to test nullify you'll be in for a shock.
if (pNonUserID && pExtUserID)
{
// neither pNonUserId nor pExtUserID are null here
}
Any Javascript variable automatically evaluates to true when it references an object.
What you were doing are comparisons to empty strings, which are not the same as null.
null, undefined and empty string is consider as false in conditional statement.
so
if(!n) alert("n is null or undefined or empty string");
if(n) alert("n has some value");
therefor, inflagranti suggested condition will work perfectly for you
if(pNonUserID && pExtUserID) {
}