Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Help with JS and functions parameters

Tags:

Does JS support two functions with the same name and different parameters ?

function f1(a, b) { // a and b are numbers }  function f1(a, b, c) { // a is a string //b and c are numbers } 

Can I use those JS function for IE7, FF, Opera with no problem?

like image 253
Sorin Avatar asked Feb 02 '10 21:02

Sorin


People also ask

How do function parameters work in JavaScript?

Arguments are Passed by Value The parameters, in a function call, are the function's arguments. JavaScript arguments are passed by value: The function only gets to know the values, not the argument's locations. If a function changes an argument's value, it does not change the parameter's original value.

Can JavaScript functions have parameters?

A JavaScript function can have any number of parameters. The 3 functions above were called with the same number of arguments as the number of parameters. But you can call a function with fewer arguments than the number of parameters.

How can I pass multiple parameters in JavaScript function?

function ceshi(test,lyj,param1,parm2){ console. log(arguments) } var params = [2,3]; ceshi(eval('2,3'));

How do you use parameters in a function?

These parameters are just like variables except that the values of these variables are defined when we call the function and are not assigned values within the function itself. Parameters are specified within the pair of parentheses in the function definition, separated by commas.


2 Answers

JavaScript doesn't support what you would call in other languages method overloading, but there are multiple workarounds, like using the arguments object, to check with how many arguments a function has been invoked:

function f1(a, b, c) {   if (arguments.length == 2) {     // f1 called with two arguments   } else if (arguments.length == 3) {     // f1 called with three arguments   } } 

Additionally you could type-check your arguments, for Number and String primitives is safe to use the typeof operator:

function f1(a, b, c) {   if (typeof a == 'number' && typeof b == 'number') {     // a and b are numbers   } else if (typeof a == 'string' && typeof b == 'number' &&              typeof c == 'number') {     // a is a string, b and c are numbers   } } 

And there are much more sophisticated techniques like the one in the following article, that takes advantage of some JavaScript language features like closures, function application, etc, to mimic method overloading:

  • JavaScript method overloading
like image 178
Christian C. Salvadó Avatar answered Sep 23 '22 20:09

Christian C. Salvadó


No, you can't use function overloading in JS.

But, you can declare just the version with 3 parameters, and then check whether the third argument === undefined, and provide differentiated behaviour on that basis.

like image 30
Chris Jester-Young Avatar answered Sep 25 '22 20:09

Chris Jester-Young