2

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.

3
  • This is the way the language works. First of all, that expression in parentheses will evaluate to "", so it will check for that. That's how it works, and that's that. Commented Jun 19, 2018 at 13:50
  • 1
    why is it so bad to do (value == null || value == "") ?? Commented Jun 19, 2018 at 13:51
  • which values or types are wanted? which not? Commented Jun 19, 2018 at 13:54

2 Answers 2

21

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');
}

Sign up to request clarification or add additional context in comments.

3 Comments

And zero..... so may not be the best option based on the input
javascript check null or empty string OP says string value @epascarello
So when you have value = '0'; then !value is false
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 == "".

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.