0

var a = '';
if (a) {
  console.log("True Value");
} else {
  console.log("False Value");
}

The above code logs "False Value" for obvious reasons, I want to set variable 'a' to a empty value such that it return true when used with if and logs "True Value".

Setting 'a' to empty object/array works fine but, I also want to do comparison between two variables but that is not possible with objects as they are compared by reference and not value.

Also I can not change the if else condition as it handles many cases other than this.

cweiske
  • 30,033
  • 14
  • 133
  • 194
Utkarsh Prakash
  • 169
  • 2
  • 12

4 Answers4

0

I'm not sure you worded the question correctly. this will check if the value is not null or undefined therefore any other falsey value will evaluate to true in the if statement. eg. [], 0 and false will pass

var a  = '';
if(a != null){
  console.log("True Value");
}else{
  console.log("False Value" );
}
synthet1c
  • 6,152
  • 2
  • 24
  • 39
0

Probably this?

// allow empty values inside, but false if undefined
if (typeof a !== 'undefined') {
  // true
}
Alex K
  • 6,737
  • 9
  • 41
  • 63
0

You need to change your if else condition or assignment of var 'a' because we can't change javascript behavior. It will always consider empty string as falsy value!

I hope it works for you

var a = '';
var a = (a) ? false : true;
if (a) {
  console.log("True Value");
} else {
  console.log("False Value");
}
Gaurav Chaudhary
  • 1,491
  • 13
  • 28
0

OP, I infer your requirements to be:

  1. Cannot change any Javascript code, only the contents of a
  2. The code snip must output "True Value".
  3. Must be a value type.
  4. Must be "empty," whatever that means.

Anyway how about this:

var a = '\0';  //Null
if (a) {
  console.log("True Value");
} else {
  console.log("False Value");
}

alert("See? It's empty. No space.>>>" + a + "<<<");
John Wu
  • 50,556
  • 8
  • 44
  • 80