JavaScript function with optional parameters [duplicate]
Asked Answered
R

4

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?

Reduced answered 21/12, 2015 at 3:41 Comment(10)
google for "JavaScript optional parameters" or "JavaScript named parameters".Consolidation
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 */ }Improvvisatore
@Mike, ever hear of ES6?Consolidation
@torazburo nope, but I just read Moogs link. Thanks for that!Improvvisatore
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.Nordic
See #12797618.Consolidation
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.Canea
@jfriend00 Not sure that's a precise dup, and in any case it doesn't deal with the issue of named argumetns.Consolidation
@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.Platitudinize
@torazaburo - I added info about named arguments and ES6 default argument values to the referenced dup answer.Platitudinize
S
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
});
Spatula answered 21/12, 2015 at 3:49 Comment(2)
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. +1Nordic
This is by far the "best" option and one which I use a lot now.Mathian
H
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'
});
Honeydew answered 21/12, 2015 at 3:44 Comment(5)
A complete answer (which already exists on SO) would show the classic pattern of chart_type = chart_type || "1";.Consolidation
@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.Topknot
@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.Honeydew
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.Spatula
@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.Consolidation
N
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";
}
Nordic answered 21/12, 2015 at 3:49 Comment(4)
See comments under Moogs's answer for why this is not great.Topknot
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.Nordic
As I said there, "It is usually okay, but you need to think about it every time". Recommending it without a caveat is dangerous.Topknot
Considering this is javascript, that's a fair point!Nordic
I
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

Improvvisatore answered 21/12, 2015 at 3:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.