Friday, May 10, 2024
67
rated 0 times [  70] [ 3]  / answers: 1 / hits: 23874  / 9 Years ago, mon, december 21, 2015, 12:00:00

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?


More From » named-parameters

 Answers
113

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

[#63997] Friday, December 18, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
george

Total Points: 2
Total Questions: 98
Total Answers: 105

Location: Equatorial Guinea
Member since Sun, Feb 14, 2021
3 Years ago
;