1

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.

user3402571
  • 61
  • 1
  • 1
  • 8

2 Answers2

20

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');
}
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62
1

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 == "".

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621