8

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?

10
  • 1
    google for "JavaScript optional parameters" or "JavaScript named parameters". Commented Dec 21, 2015 at 3: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 */ } Commented Dec 21, 2015 at 3:44
  • @Mike, ever hear of ES6? Commented Dec 21, 2015 at 3:44
  • 1
    @jfriend00 Not sure that's a precise dup, and in any case it doesn't deal with the issue of named argumetns. Commented Dec 21, 2015 at 4:03
  • 1
    @torazaburo - I added info about named arguments and ES6 default argument values to the referenced dup answer. Commented Dec 21, 2015 at 4:49

4 Answers 4

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
});
Sign up to request clarification or add additional context in comments.

2 Comments

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
This is by far the "best" option and one which I use a lot now.
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'
});

5 Comments

A complete answer (which already exists on SO) would show the classic pattern of chart_type = chart_type || "1";.
@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.
@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.
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.
@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.
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";
}

4 Comments

See comments under Moogs's answer for why this is not great.
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.
As I said there, "It is usually okay, but you need to think about it every time". Recommending it without a caveat is dangerous.
Considering this is javascript, that's a fair point!
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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.