0

I wrote an if statement using the following data.

const data = {
  field: ""
}

const data2 = {
  field: "abc"
}

if (data.field && data.field !== data2.field) {
  console.log('not in')
}

I was expecting that if condition to return true, but it returns an empty string("") so it is not included in the branch.

As shown below, if it is not an empty string(""), true is returned. Why isn't true if an empty string("") is included in the conditional statement?

const data = {
  field: "ccc"
}

const data2 = {
  field: "abc"
}

if (data.field && data.field !== data2.field) {
  console.log('in')
}
COLEAN
  • 665
  • 2
  • 9
  • 24
  • 2
    Empty strings are falsy. Non-empty strings are truthy. – VLAZ Sep 16 '21 at 06:52
  • 2
    Duplicate [In javascript, is an empty string always false as a boolean?](https://stackoverflow.com/questions/8692982/in-javascript-is-an-empty-string-always-false-as-a-boolean) – esqew Sep 16 '21 at 06:52
  • Added `&&` as additional relevant duplicate. While `""` being falsy is indeed relevant, the way the `&&` works is also important for the outcome. `expr1 && expr2 Returns expr1 if it can be converted to false; otherwise, returns expr2`, because if you change the order of operants `data.field !== data2.field && data.field` you will get `""` in the first and `"ccc"` in the second case (It doesn't change anything about if the final expression is truthy or falsy but it changes the resulting value). – t.niese Sep 16 '21 at 06:59

0 Answers0