JavaScript function with additional parameters

I am new to JavaScript based on Python background. In Python, parameters can be passed as a key and value as such:

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

Then the function could be called such:

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

Can such parameters pass in JavaScript functions?

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

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

I want to be able to transfer only data, and the type of chart and labels are optional, for example:

plotChart(data, chart_type="pie")

Is this possible with JavaScript?

+4
source share
4 answers

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

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
});
+10

- , undefined, , .

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

EcmaScript 2016 (ES6) . , , babel, ES5.

, python, , , .

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);
}

plotChart({
  xlabel: 'my label',
  chart_type: 'pie'
});
+4

, , .

var myFunc = function(param1) {
    var someData = param1 || "defaultValue";
}
+3
source

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

eg.

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

ETA:

ES6 accepts default parameter values ​​(did not know about this when I sent the response).

Link

+1
source

Source: https://habr.com/ru/post/1621047/


All Articles