sdsd
sdsd

Reputation: 517

How can i make check for empty string to be considered as truthy value

In js empty string is considered as falsy value.


let str = '';

if (str) {
  alert('success')
} else {
  alert('failure')
}

i get printed failure.

I have a scenario where i want to consider everything as falsy value in my string except ''.

Is there other way except with this explicit checking ?

if (str == '') {

Upvotes: 1

Views: 2676

Answers (4)

RobG
RobG

Reputation: 147503

If you want an empty string to return true and everything else false, then:

!String(str)

does the job. But there might be certain values of str (e.g. reference to a host object perhaps) that are not strings where the above will return true.

A slightly shorter version is:

!(''+str)

But

str === ''

seems what you're actually after.

Upvotes: 0

Phil
Phil

Reputation: 21

This seems to be the solution to your problem, simply use

Boolean(str);

Upvotes: 2

dale landry
dale landry

Reputation: 8610

Use !str in your conditional stmt, which equates to is not.

let str = '';
if(!str){
  console.log(false)
}else{
  console.log(true)
}

Upvotes: 0

Jynss-3231
Jynss-3231

Reputation: 21

This should help '!

let str = '';

if (!str) {
  console.log('success')
} else {
 console.log('failure')
}

Upvotes: 2

Related Questions