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

javascript, string, undefined

Solution

You can use `||`:

x = x || undefined;

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

Problem

Just wondering. 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. Thanks!

Original source