Return the correct object type in Javascript I am currently wondering if the following piece of Javascript code could be simplified? I would like to return the correct {},[],"" without having to pass a type as argument. Is it possible?

function getObjectProperty(object,field,type){
    switch (type){
      case "Array":
        return object &amp;&amp; object.hasOwnProperty(field) ? object[field] : [];
        break;
      case "String":
        return object &amp;&amp; object.hasOwnProperty(field) ? object[field] : "";
        break;
      case "Object":
        return object &amp;&amp; object.hasOwnProperty(field) ? object[field] : {};
        break;
      case "Boolean":
        return object &amp;&amp; object.hasOwnProperty(field) ? object[field] : false;
        break;
    }
  }
1)   I am currently wondering if the following piece of Javascript code could be simplified?


yes, something like this, would be more accurate and simpler to read

var defaultValues = {
  "Array": [],
  "Boolean": true,
  "Object": {},
  "String": ""
}

function getObjectProperty(object,field,type){
  if (object.hasOwnProperty(field)) return object[field]
  return defaultValues[type]
}



  2) I would like to return the correct {},[],"" without having to pass a type as argument. Is it possible?


This is only possible, if the field exist.
Otherwise whats the type of foo in {bar: "bar"} ?

But what are you actually doing:


check if the field is in the object
If true, return the value, otherwise a defaultValue 


So you could simplify it to this:

function getValue(obj, field, defaultValue) {
   return obj.hasOwnProperty(field) ? obj[field] : defaultValue
}