Javascript – How to get value from Object, with default value


I constantly find myself passing config values to functions accessing them like this:

var arg1 = 'test1';
  arg1 = config.args.arg1;

var arg2 = 'param2';
  arg2 = config.args.arg2;

var arg3 = '123';
  arg3 = config.args.arg3;

where I later use them like this:

var url = '<some-url>?id='+arg1+'&='+arg2 +'=' + arg3;

Does jQuery/ExtJS or any other framework provide a solution to access variables like this in a simple way, and give variables a default value?

Something like:


Or is there maybe a standard solution for this.


I was also thinking about the common pattern where you have defaults

var defaults = {
   args: {
      args1: ....

and doing an object merge.

And then encoding the object to a param String. But as you can see the object values also sometimes contain parameter names.

Best Solution

Generally, one can use the or operator to assign a default when some variable evaluates to falsy:

var foo = couldBeUndefined || "some default";


var arg1 = config.args.arg1 || "test";
var arg2 = config.args.arg2 || "param2";

assuming that config.args is always defined, as your example code implies.