7

I'm new to JavaScript coming from Python background. In Python parameters can be passed as key and value as such:

def printinfo( name, age = 35 ):
   print "Name: ", name
   print "Age ", age
   return;

Then the function could be called as such:

printinfo( age=50, name="miki" )
printinfo( name="miki" )

Can such parameters be passing in JavaScript functions?

I want to be able to pass one or more parameter. For example a JavaScript function as such:

function plotChart(data, xlabel, ylabel, chart_type="l"){
    ...
} 

I want to be able to pass only data and chart type and labels are optional such as :

plotChart(data, chart_type="pie")

Is this possible with JavaScript?

codeBarer
  • 2,238
  • 7
  • 44
  • 75
  • 1
    google for "JavaScript optional parameters" or "JavaScript named parameters". –  Dec 21 '15 at 03:43
  • Not directly. You can check if parameters are defined and hard code that into your functions. e.g. var preDefined = function(param) { if(param === undefined) { param = predefinedValue } /* Rest of code goes here */ } – Mike Dec 21 '15 at 03:44
  • @Mike, ever hear of ES6? –  Dec 21 '15 at 03:44
  • @torazburo nope, but I just read Moogs link. Thanks for that! – Mike Dec 21 '15 at 03:47
  • ES6 is a specification of Javascript, commonly referred to as ES2015. It's not fully supported across browsers, however you can use transpilers to get the functionality. Anyway, default parameters are coming to JS once the support for them is there. – Sinistralis Dec 21 '15 at 03:48
  • See http://stackoverflow.com/questions/12797118/how-can-i-declare-optional-function-parameters-in-javascript. –  Dec 21 '15 at 03:49
  • JavaScript doesn't currently support named arguments. Arguments are simply passed based on their order, even when optional/default parameters are used by the function. Using `chart_type="pie"` will assign the `chart_type` variable outside of the function (or create a global) and pass `"pie"` to `xlabel`. – Jonathan Lonowski Dec 21 '15 at 03:50
  • 1
    @jfriend00 Not sure that's a precise dup, and in any case it doesn't deal with the issue of named argumetns. –  Dec 21 '15 at 04:03
  • @torazaburo - there's way, way more info in that answer about optional and variable arguments than any of these answers. It did not seem to make sense to duplicate all that in a new answer here. If you share what you think is missing from that answer, I will add it to that answer in the spirit of continually improving good answers rather than copying pieces of information among multiple related answers because that tends to make a more valuable reference in the long run. – jfriend00 Dec 21 '15 at 04:05
  • 1
    @torazaburo - I added info about named arguments and ES6 default argument values to the referenced dup answer. – jfriend00 Dec 21 '15 at 04:49

4 Answers4

14

A good way to do this would be to use an object for all of the arguments. Something like:

function plotChart(options) {
  // Set defaults
  options.chart_type = options.chart_type || '1';

  // Check if each required option is set
  // Whatever is used by the data
}

Then when the function is called:

plotChart({
  data: 'some data',
  xlabel: 'some xlabel',
  ylabel: 'some ylabel',
  chart_type: '5' // This is optional
});
Sam
  • 1,115
  • 1
  • 8
  • 23
  • This answer goes a step beyond mine so I'm recommending it. This also has the benefit of easily building on the paramters. JS has no overloading, so if you forsee a function going through a large amount of changes in the future, or takes more than 1-2 args, it's usually a good idea to make it take an object instead. +1 – Sinistralis Dec 21 '15 at 03:51
  • This is by far the "best" option and one which I use a lot now. – TheTechy Jul 25 '16 at 09:37
6

One way is to check if the parameter value is undefined and if so then assign a value.

function plotChart(data, xlabel, ylabel, chart_type) {
  if (typeof chart_type === 'undefined') {
     chart_type = 'l';
  }
} 

Also EcmaScript 2016 (ES6) offers Default Parameters. Since some browser don't yet support this feature you can use a transpiler such as babel to convert the code to ES5.

To make it work like in your python example you would have to pass an object containing the values instead of individual parameters.

function plotChart(options) {
    var data = options.data;
    var xlabel = options.xlabel;
    var ylabel = options.ylabel;
    var chart_type = (typeof options.chart_type === 'undefined' ? 'l' : options.chart_type);
}

Example usage

plotChart({
  xlabel: 'my label',
  chart_type: 'pie'
});
Miguel Mota
  • 20,135
  • 5
  • 45
  • 64
  • A complete answer (which already exists on SO) would show the classic pattern of `chart_type = chart_type || "1";`. –  Dec 21 '15 at 03:48
  • 5
    @torazaburo: This pattern is almost always okay in Ruby, but in JavaScript you need to be aware of potential values of the variable, in case the value legitimately has one of the falsy values in its domain. It is usually okay, but you need to think about it every time; `if (typeof(chart_type) == "undefined") chart_type = "1"` is the safe variant. – Amadan Dec 21 '15 at 03:49
  • 2
    @torazaburo I don't like that pattern because in some cases you might want to actually pass a value of `0` which would be *falsey*. I guess for this question it's fine but I don't want to complicate things. – Miguel Mota Dec 21 '15 at 03:50
  • The problem with this comes when you want one of the first arguments to have a default value. What if you give `data` a default value? You won't be able to use it, because if you omit the `data` argument and your first argument is meant for `xlabel`, you're actually setting `data` to the value you want in `xlabel`. – Sam Dec 21 '15 at 03:59
  • @Moogs yes, I'm not suggesting it for all situations, obviously not where a falsy value could be passed in, but it's a common idiom for cases where, for example, the parameter is either omitted or an object, and that's why I said it's worth mentioning. –  Dec 21 '15 at 04:01
3

There's a ton of answers for this already, but I havn't seen what I considered to be the simplest solution to this.

var myFunc = function(param1) {
    var someData = param1 || "defaultValue";
}
Sinistralis
  • 412
  • 3
  • 16
  • 2
    See comments under [Moogs's answer](http://stackoverflow.com/a/34388663/240443) for why this is not great. – Amadan Dec 21 '15 at 03:54
  • Depends on what args you are expecting in, but it's certainly a valid point. I very rarely deal with values that can be 0 so it's a pattern I commonly use. Either way, a case can certainly be made for not following a pattern with exceptions. – Sinistralis Dec 21 '15 at 03:56
  • 1
    As I said there, "It is usually okay, but you need to think about it every time". Recommending it without a caveat is dangerous. – Amadan Dec 21 '15 at 03:57
  • Considering this is javascript, that's a fair point! – Sinistralis Dec 21 '15 at 03:58
1

You can check if parameters are defined and hard code that into your functions.

e.g.

 var preDefined = function(param) { 
    if(param === undefined) { 
        param = preDefinedValue
     }
     /* Rest of code goes here */
 }

ETA:

ES6 was allows for default parameter values (was unaware of this when I posted the answer).

Link

Mike
  • 3,830
  • 2
  • 16
  • 23