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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With