skip to Main Content

Why does an empty string in a vue template return as truthy?

<div>{{ "" ?? "empty string is not truthy" }}</div>

This will just display the empty string. I have a bunch of empty string fields which I can’t check with the nullish coalescing operator (??) but instead have to use ternaries:

<div>{{ "" ? "string empty" : "string not empty" }}</div>

Shouldn’t "" ?? be faulty?

2

Answers


  1. "" is not null nor undefined. Just like 0. These are just ‘falsey’, so won’t work with ??:

    // Not null or undefined
    console.log("" ?? "If my empty string is null or undefined, then log this, else log empty string");
    // Not null or undefined
    console.log(0 ?? "If 0 is null or undefined, then log this, else log 0");
    // Actually null or undefined
    console.log(undefined ?? "If undefined is null or undefined, then log this, else log undefined"); 
    Login or Signup to reply.
  2. The Nullish coalescing operator (??) tests if a value is not null or undefined, not if it is truthy.

    "" is a falsy value, but it isn’t null and it isn’t undefined.

    Use the Logical OR (||) operator to test for truthiness.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search