0

I can't find the similiar problem, I guess it's because i can't find a correct question/answer. I want to create a function that will use default values if there is not arguments passed when calling a function, if so, replace default values with the values passed in function's parameters. For example:

function openBlock(false){
  // if parameter was passed with 'false' value, it will do this

  // else it will put automatically a 'true' value to an function's argument
}

So if call a function openBlock() without any params, it will consider that it's param true by default. If i call a function with argument false like openBlock(false) it will override the default behavior.

Thanks

aspirinemaga
  • 3,753
  • 10
  • 52
  • 95

2 Answers2

2

JavaScript doesn't really have default parameters implemented like other languages do.

You'll have to implement them yourself:

function openBlock(argument) {
  argument = typeof argument !== 'undefined';
}

Take a look at Is there a better way to do optional function parameters in Javascript? for a more generic approach.

Community
  • 1
  • 1
Blender
  • 289,723
  • 53
  • 439
  • 496
2

There are various ways to do this in Javascript, though none are built in. The easiest pattern is:

function(option) {
    option = option || "default";
    // do stuff
}

But as @FelixKling notes, this won't work in your case, as it will replace any false-y value (including explicitly setting the argument to false) with the default. For boolean arguments that you want to default to true, you need:

function(option) {
    // default to "true"
    option = option !== undefined ? option : true;
    // do stuff
}

When you're dealing with more than one or two arguments, the best option is often to use a single options or config argument and check for the existence of properties:

function(options) {
    var arg1 = option.arg1 !== undefined ? false : true;
    var arg2 = option.arg2 || "default";
    // do stuff
}

If you're using a library like jQuery or underscore, the extend method makes it quite easy to set up an object with default values and then overwrite them with supplied values if they exist:

function(options) {
    var defaults = {
        arg1: true,
        arg2: "default"
    };
    options _.extend(defaults, options);
    // do stuff
}
nrabinowitz
  • 55,314
  • 10
  • 149
  • 165