JavaScript If statement not operating correctly - javascript

Below is my code and it always returns the IF statement as if it's false. Shouldn't it be true?
The variables asscostied with the IF statement:
var coloredUI = '';
var coloredText = '';
And here's the IF statement:
if (coloredText && coloredUI == '') {
} else {
}

In JavaScript, values can be "truthy" or "falsy". You set both your variables to empty strings, which are "falsy" (no characters == false). Other falsy values are:
undefined, 0, false, null
An if statement always wants to test a condition for a truthy Boolean result. If you give it an expression, that expression is evaluated, and if the result is not a Boolean, the JavaScript engine will coerce it into one. Falsy values become false and truthy values become true, so:
if(coloredText) {}
Evaluates to:
if(false) {}
because coloredText was intialized to a falsy value (''). And because you used the short-circuited logical AND, both expressions would have to be true for the entire if to be true. But, since the first one was coerced to false, the if statement proceeds to the false branch.
To avoid this, you can write an expression that compares the expression rather than coerces it alone, as in:
if(coloredText == '') // true
This concept of implicit type coercion is also why JavaScript provides two mechanisms for equality testing. Take this for example:
var x = 0;
if(x == false)
This will result in true because the double equal sign means equality with conversion. The false is converted to a number (0) and then checked against the number (0), so we get true.
But this:
var x = 0;
if(x === false)
will result in a false result because the triple equal sign means strict equality, where no conversion takes place and the two values/expression are compared as is.
Getting back to your original scenario. We leverage this implicit type coercion often when checking for feature support. For example, older browsers don't have support for Geolocation (they don't implement the object that provides that feature). We can test for support like this:
if(navigator.geolocation)
If the navigator object doesn't have a geolocation property, the expression will evaluate to undefined (falsy) and the if will head into its false branch. But, if the browser does support geolocation, then the expression will evaluate to an object reference (truthy) and we proceed into the true branch.

Empty string('') is falsey value
Following example will test whether both the values holds truthy values.
var coloredUI = '';
var coloredText = '';
if (coloredText && coloredUI) {
alert('if');
} else {
alert('else');
}
To test both values as ''
var coloredUI = '';
var coloredText = '';
if (coloredText == '' && coloredUI == '') {
alert('if');
} else {
alert('else');
}
Truthy and Falsy Values

if (coloredText == '' && coloredUI == '') {
} else {
}

if (coloredText == '' && coloredUI == '') {
} else {
}

if ((coloredText==='') && (coloredUI == '')){
} else {
}
OR if you want to check if there is a value in coloredText then use this:
if ((coloredText) && (coloredUI == '')){
} else {
}

Related

Difference between exclamation equals sign and exlamation 2x equals sign when checking with null

What is the difference between next if statements in javascript when checking with null?
var a = "";
if( a != null ) // one equality sign
....
if( a !== null ) // two equality sign
....
When comparing to null I can't find any difference.
According to http://www.w3schools.com/js/js_comparisons.asp
!= - not equal
!== - not equal value or not equal type
In JavaScript, null has type: object (try yourself executing the following sentence typeof null).
That is, !== will check that a is also object before checking if the reference equals.
Actually you know that === and !== are meant to check that both left and right side of the equality have the same type without implicit conversions involved. For example:
"0" == 0 // true
"0" === 0 // false
Same reasoning works on null checking.
!= checks
negative equality
while !== checks for
negative identity
For example,
var a = "";
a != false; //returns false since "" is equal false
a !== false; //returns true since "" is not same as false
but if you are comparing it with null, then value will be true in both ocassion since "" is neither equal nor identical to null
There is no difference between them when comparing to null.
When we use strict equality (!==) it is obvious because they have different types, but when we use loose equality (!=) it is an important thing to remember about JavaScript language design.
Because of language design there are also some common questions:
How do you check for an empty string in JavaScript?
Is there a standard function to check for null, undefined, or blank variables in JavaScript?
var a = "";
(1) if( a != null ) // one equality sign
Above condition(1) checks value only and not data-type, this will return true.
....
(2) if( a !== null ) // two equality sign
This checks value and data-type both, this will true as well.
To understand it more precisely,
var a = "1";
if( a == 1) {
alert("works and doesn't check data type string");
}
if( a === 1) {
alert('doesn't works because "1" is string');
}
if( a === "1") {
alert('works because "1" is string');
}
There is a difference if variable has value undefined:
var a = undefined;
if( a != null ) // doesn't pass
console.log("ok");
if( a !== null ) // passes
console.log("ok");
Got idea from reading this great post Why ==null, Not ===null. Also != is faster.

Why doesn't empty string == null in JavaScript

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

how to check falsy with undefined or null?

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)

difference between assignments given to a variable?

false
0
null
undefined
empty string
I use them,but I am still unaware of the marginal difference each prospect in the above list have.
I mostly use 0,false.But I have come across many scripts that uses undefined ,empty string.
I want to know the exact differnce between them.
I know its a silly question,but would be great If i get a small conscise answer.
It's called "truthy and falsy values" if you want to know how to refer to it.
Here is a link to explain the answer to your question: http://www.sitepoint.com/javascript-truthy-falsy/
(Keep in mind when reading the link at the beginning that !!(value) forces the value to be either true or false)
The type is the difference.
false is a boolean, 0 is a number, null is an object, undefined is undefined, and '' is a string.
You pick the type based on what it is being used as. For example:
// There is nothing wrong with this block of code
var num_cats = 7;
if(num_cats){
// num_cats is truthy
}
// This block works but it could be made more clear
var has_cat = num_cats;
if(has_cat){
// This would work, but it doesn't make sense. As a developer I would
// expect that has_cat should be either true or false, not 7.
// One way to convert the number to a boolean would be:
has_cat = !!num_cats
}
The two most confusing falsey values are probably null and undefined.
null basically means that the variable exists, but it's value is unknown.
undefined means that the variable doesn't exist (although a variable can be explicity set to undefined like var x = undefined; and then the variable x exists but it is explicitly not being defined which means that you can treat it as though it doesn't exist.
The list you have are 5 of the 6 "falsy" values in javascript. If you add "NaN" to that, you would have all the falsy values in javascript. So the complete "falsy" list is
1)0
2)""
3)false
4)undefined
5)null and
6)NaN
When used in a "if" statement, these all behave the same way so
if(0)
if("")
if(false)
if(undefined)
if(null) and
if(NaN) would behave the same
You asked for a short concise answer but I think the best way is just showing how it works with some basic test. Apologies for the long answer
//Checking if all the "falsy" values evaluate the same way in a "if" statement
console.log("Checking if(0)");
if(0) {
console.log(" if(0) Will not be reached");
}
console.log('Checking if("")');
if("") {
console.log(' if("") Will not be reached');
}
console.log("Checking if(undefined)");
if(undefined) {
console.log("if(undefined) Will not be reached");
}
console.log("Checking if(null)");
if(null) {
console.log("if(null) Will not be reached");
}
console.log("Checking if(Nan)");
if(NaN) {
console.log("if(NaN) Will not be reached");
}
console.log("Checking if(false)");
if(false) {
console.log("if(false) Will not be reached");
}
//Checking if all the falsy values are equal(==) to each other in a if statement
if(0 == "") {
console.log('if(0 == "") is true');
}
if(0 == false) {
console.log("if(0 == false) is true");
}
if("" == false) {
console.log('if("" == false) is true');
}
if(0 == undefined) {
console.log("if(0 == undefined) Will not be reached");
}
if("" == null) {
console.log('if("" == null) Will not be reached');
}
if(undefined == null) {
console.log("if(undefined == null) is true");
}
if(NaN == "") {
console.log('if(NaN == "") Will not be reached');
}
//Checking for strictly equality between false and falsy values
if(undefined === false) {
console.log("Will not be reached");
}
if(null === false) {
console.log("Will not be reached");
}
if(undefined ===false) {
console.log("Will not be reached");
}
if(0 === false) {
console.log("Will not be reached");
}
if("" === false) {
console.log("Will not be reached");
}
if(NaN === false) {
console.log("Will not be reached");
}
What this means that though these "falsy" values might be used in a "if" statement interchangeably, they all are not equal(==) to each other(particular the set of 0,"" and false with the other three). If a stricter equals(====) is used, none of these would be equal to false, hence perhaps the classification "falsy" instead of false.
Only two of the values you've mentioned are what I would call designated "special values".
null - In most cases this is equivalent to not applicable.
undefined - The implicit version of null
An example for both:
function findByTitle(arr, title)
{
for (var i = 0; i < arr.length; ++i) {
if (arr[i].title === title) {
return arr[i];
}
}
return null;
}
The return value of null indicates that the record could not be found, otherwise it's an object.
function increment(x, by)
{
return x + (by || 1); // by may be undefined
}
increment(4); // 5
In this case, the by argument is not passed, so JavaScript passes it as undefined implicitly. I wouldn't recommend assigning this to a variable though; rather, I would use null.
The other values you have mentioned are not particularly special; they can be used as a starting value, such as building a string value or calculating a sum, but they're not special in their own right.
"" is a string
false is a boolean
0 and NaN are numbers

How do i compare against an empty variable?

If I set a variable to 0, I get the weird behavior that a comparison to "" (empty) is true. How do I check that the variable is really empty?
tmp = 0;
if ( tmp != "")
{
//do something - This is where the code goes.
}
else
{
//isEmpty - I would expect to be here
}
Use strict comparison operators
=== and !==
With == and != (called abstract comparison operators),
If the two operands are not of the same type, JavaScript attempts to
convert the operands to an appropriate type for the comparison.
If by empty, you want to check if the variable hasn't been defined, use:
if (typeof tmp !== "undefined") {
// it exists!
}
What do you mean by empty variable? If you mean an empty string, then you should use !== to check it.
if (tmp !== "")
JavaScript implicitly converts values to other types. To check type also, use the !== operator:
if ( tmp !== "")
In JavaScript everything except 0, NaN, undefined, false and null are considered to be false. "" is considered as true.
if (tmp) {
}
Above if will be executed if variable contains any value other than 0, NaN, undefined, false and null.
If tmp is a string then you can use the following code:
if (tmp !== "") {
}
=== and !== operators compare without doing type-conversion.

Categories