SNos SNos - 1 year ago 85
Javascript Question

JS - Argument with default value

I need to create a function where I send custom arguments to it.
I am trying to have arguments that have a default value it is undefined.

But I cannot get t right, the code I have always gives me the default argument. What am I doing wrong?


type: "image",
file: "test.jpg",
breakingPoint: 100



function sn_test(args) {
var options = {
Type: args.type,
File: args.file

var default_options = {
breakingPoint: 2000

args = $.extend({}, default_options, args);


Answer Source

There are a few errors in your code:

  • Your 'options' object is using different case in the keys: Type is used, while type is being passed through.
  • You are extending default_options with args and not options which you have initialised, rendering it kind of useless.
  • you are using default_options.breakPoint instead of options.breakPoint for #result3.

It seems like there's just a bit of confusion in terms of your variables and what your assigning to them.

What you want is:

  • args - these are the arguments passed through to the method (the options being passed through)
  • default_options - an object containing default options.
  • options - an object containing the merged options.

These all need to be matching case.

Here's a fixed example

Edit: Also consider moving your default_options declaration outside of the function scope if possible, this will mean it's not being created on each call to the function, improving performance. Here.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download