Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript inline replace undefined with empty string

I have this function:

function callWS(input) {
    var output = {
        "type"  : input["type"]  || "",
        "mark"  : input["mark"]  || "",
        "model" : input["model"] || "",
        "year"  : input["year"]  || ""
    };

    return output;
}

I want the user to call this function in many ways:

callWS(); ==> {"type":"","mark":"","model":"","year":""}
callWS({"type":"moto"}); ==> {"type":"moto","mark":"","model":"","year":""}
callWS({"type":"moto","mark":"audi"}); ==> {"type":"moto","mark":"audi","model":"","year":""}

And in case a parameters is undefined, to initialize it as an empty string. Currently my function does not work in the first case, but in the other is working.

When I call it like callWS() I get:

Uncaught TypeError: Cannot read property 'type' of undefined

To be honest I don't know why it works for the 2 and 3 case but I need to make it work for the first case also. I know that if I use:

if (input["type"])

will do the trick but I need an inline solution. Is this possible somehow?

like image 362
paulinho Avatar asked Sep 20 '25 06:09

paulinho


1 Answers

You have to supply input variable itself with default value too.

function callWS(input) {
   input = input || {};
   ...
}

Otherwise you access properties on unexisting (undefined) object which lead to error (what you have now).

On other hand accessing unexisting properties on existing object isn't treated as error in JS.

like image 87
hindmost Avatar answered Sep 21 '25 20:09

hindmost