user3040830
user3040830

Reputation:

Can a boolean be compared with a string

I have a variable isRefreshed which is declared in the below manner

var isRefreshed ='';

and isRefreshed can be assigned a boolean value in some scenario like:

isRefreshed=false;

now there is a if check to be performed like below

if(isRefreshed != '')
{
   // Some action
}

the problem is that when a boolean value is assigned to isRefreshed then in that case my condition is satisfied like

true != ''

is returning true which is not desired. So my question is can we compare a boolean with a string in jquery.

Upvotes: 1

Views: 80

Answers (1)

James Donnelly
James Donnelly

Reputation: 128791

You should use !== to compare type as well as content.

false != ''  // false - both false and '' are falsy values
false !== '' // true - Boolean isn't equal to string type

Further reading: falsy values, comparison operators.

In your situation, however, you could get away with just using:

if (isRefreshed) { ... }

This is equal to if (isRefreshed == true), but as mentioned above both false and '' are falsy values and will evaluate to false.

Upvotes: 5

Related Questions