javascriptobjectparametersoption-type

Javascript - function with optional parameters as object?


I need a function that its parameter is an object, and if I leave it empty it will load default values.

something like:

function loadMap(args) { //args is an object and its optional

   //this is what I want to do, test args and load defauts if necesary
   /*
   pseudocode:
   if args.latitude is not set then
       give it a default value

   if args.longitude is not set then
       give it a default value

    end pseudocode */

   alert("Latitude is "+args.latitude );
   alert("Longitude is "+args.longitude );
}

//outputs the default values
loadMap();

//outputs custom values
loadMap({latitude: "x.xxxx", longitude: "-x.xxxx"});

//and should work too and output one default and one custom value
loadMap({latitude: "x.xxxx"});

I found this solution in this question (Is there a better way to do optional function parameters in Javascript?) but it requires jQuery: http://jsfiddle.net/xy84kwdv/

It's ALMOST what I want but I don't want to depend on a jquery function.


Solution

  • Are you looking for something like:

    function loadMap(args) { 
        args = args || {}; 
        args.latitude = args.latitude || "X.XXX"; 
        args.longitude = args.longitude || "Y.YYY"; 
        alert(args.latitude);
        alert(args.longitude);
    }; 
    
    loadMap({latitude:"custom_latitude"});