Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript check null or empty string [duplicate]

Tags:

javascript

Why is this not possible?

var value = null;

if(value == (null || ""))
{
   //do something
}

I would like to check a value if it is null or empty without using the variable over and over again.

like image 360
user3402571 Avatar asked Mar 04 '26 19:03

user3402571


2 Answers

Use !value. It works for undefined, null and even '' value:

var value = null;

if(!value)
{
  console.log('null value');
}

value = undefined;

if(!value)
{
  console.log('undefined value');
}

value = '';

if(!value)
{
  console.log('blank value');
}
like image 94
Ankit Agarwal Avatar answered Mar 06 '26 09:03

Ankit Agarwal


If we split the condition into its two relevant parts, you first have null || "". The result of that will be equal to the empty string "".

Then you have value == ""., which will be false if value is null.

The correct way to write your condition is value == null || value == "".

like image 25
Some programmer dude Avatar answered Mar 06 '26 10:03

Some programmer dude