javascriptundefinedstring

Is it possible to convert an empty string ("") to undefined in one line in JavaScript?


I have a method (URItemplate) which I need to return undefined in case variables are not defined. Currently I'm doing this:

var x = UriTemplate.parse(value || "").expand({"some":"properties"} || {});

In case value and my expand object {} are passed as empty string and empty object, x equates to "".

I'm wondering if there is anything I can do with an empty string to convert it to undefined, so I can later call...

$.ajax({"url": x || default_url})...

Of course there is if-else or ?: and my || is also an if-else, but I'm wondering if there is another way to do this as a one-liner.


Solution

  • You can use ||:

    x = x || undefined;
    

    If "x" has any falsy value (including the empty string), it will end up as undefined.

    edit—Now it's 2024, and the above is fine, but there's a better way to make the above sort of "fix" to values when you do care about things like 0 and the empty string:

    x ??= undefined;
    

    The ?? operator, and the assignment operator ??=, work like || but it only tests for null and undefined. Thus you don't have the annoying problem with other "falsy" values. The statement above will make sure that the value of x is undefined if it's currently either null or undefined.

    So good old || still works when you want to "normalize" any falsy value, and ?? is great for when you're just worried about null and undefined.