The following function will return an array of the parameter names of any function passed in.

var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
var ARGUMENT_NAMES = /([^\s,]+)/g;
function getParamNames(func) {
  var fnStr = func.toString().replace(STRIP_COMMENTS, '');
  var result = fnStr.slice(fnStr.indexOf('(')+1, fnStr.indexOf(')')).match(ARGUMENT_NAMES);
  if(result === null)
     result = [];
  return result;
}

Example usage:

getParamNames(getParamNames) // returns ['func']
getParamNames(function (a,b,c,d){}) // returns ['a','b','c','d']
getParamNames(function (a,/*b,c,*/d){}) // returns ['a','d']
getParamNames(function (){}) // returns []

Edit:

With the invent of ES6 this function can be tripped up by default parameters. Here is a quick hack which should work in most cases:

var STRIP_COMMENTS = /(\/\/.*$)|(\/\*[\s\S]*?\*\/)|(\s*=[^,\)]*(('(?:\\'|[^'\r\n])*')|("(?:\\"|[^"\r\n])*"))|(\s*=[^,\)]*))/mg;

I say most cases because there are some things that will trip it up

function (a=4*(5/3), b) {} // returns ['a']

Edit: I also note vikasde wants the parameter values in an array also. This is already provided in a local variable named arguments.

excerpt from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope/arguments:

The arguments object is not an Array. It is similar to an Array, but does not have any Array properties except length. For example, it does not have the pop method. However it can be converted to a real Array:

var args = Array.prototype.slice.call(arguments);

If Array generics are available, one can use the following instead:

var args = Array.slice(arguments);
Answer from Jack Allan on Stack Overflow
🌐
W3Schools
w3schools.com › js › js_function_parameters.asp
JavaScript Function Parameters
In JavaScript, function parameters and arguments are distinct concepts: Parameters are the names listed in the function definition.
Top answer
1 of 16
372

The following function will return an array of the parameter names of any function passed in.

var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
var ARGUMENT_NAMES = /([^\s,]+)/g;
function getParamNames(func) {
  var fnStr = func.toString().replace(STRIP_COMMENTS, '');
  var result = fnStr.slice(fnStr.indexOf('(')+1, fnStr.indexOf(')')).match(ARGUMENT_NAMES);
  if(result === null)
     result = [];
  return result;
}

Example usage:

getParamNames(getParamNames) // returns ['func']
getParamNames(function (a,b,c,d){}) // returns ['a','b','c','d']
getParamNames(function (a,/*b,c,*/d){}) // returns ['a','d']
getParamNames(function (){}) // returns []

Edit:

With the invent of ES6 this function can be tripped up by default parameters. Here is a quick hack which should work in most cases:

var STRIP_COMMENTS = /(\/\/.*$)|(\/\*[\s\S]*?\*\/)|(\s*=[^,\)]*(('(?:\\'|[^'\r\n])*')|("(?:\\"|[^"\r\n])*"))|(\s*=[^,\)]*))/mg;

I say most cases because there are some things that will trip it up

function (a=4*(5/3), b) {} // returns ['a']

Edit: I also note vikasde wants the parameter values in an array also. This is already provided in a local variable named arguments.

excerpt from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope/arguments:

The arguments object is not an Array. It is similar to an Array, but does not have any Array properties except length. For example, it does not have the pop method. However it can be converted to a real Array:

var args = Array.prototype.slice.call(arguments);

If Array generics are available, one can use the following instead:

var args = Array.slice(arguments);
2 of 16
131

Below is the code taken from AngularJS which uses the technique for its dependency injection mechanism.

And here is an explanation of it taken from http://docs.angularjs.org/tutorial/step_05

Angular's dependency injector provides services to your controller when the controller is being constructed. The dependency injector also takes care of creating any transitive dependencies the service may have (services often depend upon other services).

Note that the names of arguments are significant, because the injector uses these to look up the dependencies.

/**
 * @ngdoc overview
 * @name AUTO
 * @description
 *
 * Implicit module which gets automatically added to each {@link AUTO.$injector $injector}.
 */

var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m;
var FN_ARG_SPLIT = /,/;
var FN_ARG = /^\s*(_?)(.+?)\1\s*$/;
var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
function annotate(fn) {
  var $inject,
      fnText,
      argDecl,
      last;

  if (typeof fn == 'function') {
    if (!($inject = fn.$inject)) {
      $inject = [];
      fnText = fn.toString().replace(STRIP_COMMENTS, '');
      argDecl = fnText.match(FN_ARGS);
      forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg){
        arg.replace(FN_ARG, function(all, underscore, name){
          $inject.push(name);
        });
      });
      fn.$inject = $inject;
    }
  } else if (isArray(fn)) {
    last = fn.length - 1;
    assertArgFn(fn[last], 'fn')
    $inject = fn.slice(0, last);
  } else {
    assertArgFn(fn, 'fn', true);
  }
  return $inject;
}
People also ask

What is the rest parameter in JavaScript?
The rest parameter (...args) collects all remaining arguments into an array. It must be the last parameter. Example: function sum(...numbers) {} can accept any number of arguments.
🌐
playcode.io
playcode.io › javascript › function-parameters
JavaScript Function Parameters: Default, Rest & Destructuring | ...
What are default parameters in JavaScript?
Default parameters allow you to set fallback values when arguments are not provided or are undefined. Example: function greet(name = "Guest") {}. If no argument is passed, name will be "Guest".
🌐
playcode.io
playcode.io › javascript › function-parameters
JavaScript Function Parameters: Default, Rest & Destructuring | ...
Can I destructure objects in function parameters?
Yes! You can destructure objects and arrays directly in the parameter list. Example: function greet({ name, age }) {} extracts name and age from the passed object.
🌐
playcode.io
playcode.io › javascript › function-parameters
JavaScript Function Parameters: Default, Rest & Destructuring | ...
🌐
TutorialsPoint
tutorialspoint.com › javascript › javascript_function_parameters.htm
JavaScript - Function Parameters
In the above syntax, the function parameters are 'parameter1', 'parameter2', and 'parameter3'. JavaScript functions don't check the number of arguments passed while invoking the function.
🌐
Playcode
playcode.io › javascript › function-parameters
JavaScript Function Parameters: Default, Rest & Destructuring | Playcode
Master JavaScript function parameters: default values, rest parameters (...args), destructuring, and the arguments object. Interactive examples included.
🌐
Mozilla
developer.mozilla.org › en-US › docs › Web › JavaScript › Guide › Functions
Functions - JavaScript - MDN Web Docs
See also the exhaustive reference chapter about JavaScript functions to get to know the details. A function definition (also called a function declaration, or function statement) consists of the function keyword, followed by: The name of the function. A list of parameters to the function, enclosed in parentheses and separated by commas.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Functions › arguments
The arguments object - JavaScript - MDN Web Docs - Mozilla
You can use arguments.length to count how many arguments the function was called with. If you instead want to count how many parameters a function is declared to accept, inspect that function's length property.
🌐
W3Schools
w3schools.com › js › js_function_arguments.asp
JavaScript Function Arguments
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.
Find elsewhere
🌐
JavaScript.info
javascript.info › tutorial › the javascript language › javascript fundamentals
Functions
The function keyword goes first, then goes the name of the function, then a list of parameters between the parentheses (comma-separated, empty in the example above, we’ll see examples later) and finally the code of the function, also named “the function body”, between curly braces.
🌐
GeeksforGeeks
geeksforgeeks.org › javascript-function-parameters
JavaScript Function Parameters | GeeksforGeeks
December 17, 2024 - It is represented by three dots (...) followed by the parameter name and must be the last parameter in the function, enabling flexible and dynamic argument handling.Syntax//... is the rest parame ... The Javascript Function.length property of the function object in Javascript is used to return the number of parameters required by a function.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Functions › Default_parameters
Default parameters - JavaScript - MDN Web Docs
This function will print the value of the parameter a, because the variable var a is hoisted only to the top of the scope created for the function body, not the parent scope created for the parameter list, so its value is not visible to b.
🌐
DEV Community
dev.to › anik_sikder_313 › the-ultimate-guide-to-javascript-function-parameters-57dg
The Ultimate Guide to JavaScript Function Parameters - DEV Community
August 20, 2025 - In this deep dive, we’ll explore everything about parameters and arguments in JavaScript. Buckle up, because by the end, you’ll be handling function parameters like a pro magician pulling endless tricks from a hat! Let’s clear the confusion first. Parameters are the names listed in the ...
🌐
Medium
medium.com › @AlexanderObregon › what-happens-when-you-reassign-function-parameters-in-javascript-2e303cb2dfb2
What Happens When You Reassign Function Parameters in JavaScript
May 19, 2025 - Every regular function (not an arrow function) gets a built-in object called arguments in JavaScript. It looks like an array, but it’s not quite one. It holds all the values that were passed into the function, whether or not those values were given names in the parameter list.
🌐
Smashing Magazine
smashingmagazine.com › 2016 › 07 › how-to-use-arguments-and-parameters-in-ecmascript-6
How To Use ES6 Arguments And Parameters — Smashing Magazine
In this function, even though param3 has a default value, it’s not equal to arguments[2] because only two argument are passed to the function. In other words, setting default values has no effect on the arguments object. ECMAScript 6 has brought hundreds of small and big improvements to JavaScript. More and more, developers are using ECMAScript 6 features, and soon these features will be unavoidable. In this tutorial, we’ve learned how ECMAScript 6 has upgraded parameter handling in JavaScript, but we’ve just scratched the surface of ECMAScript 6.
🌐
Mimo
mimo.org › glossary › javascript › parameters
Learn about JavaScript Parameters' Syntax and Usage
Creating JavaScript function parameters involves listing them in the parentheses of a function declaration. You can add as many parameters as you like.
🌐
Wes Bos
wesbos.com › javascript › 02-functions › functions-parameters-and-arguments
Functions - Parameters and Arguments - Wes Bos
A best practice in JavaScript is to keep your code DRY, which stands for Don't Repeat Yourself. calculateBill would not be useful if it could only calculate the value assuming the bill is $100 and a 15% tax rate, so we need to modify those hardcoded values. To solve that, above the calculateBill function, we can declare variables for the bill total and taxRate. ... const bill = 100; const taxRate = 0.13; function calculateBill() { console.log("Running calculate bill!!"); const total = bill * 1 + taxRate; return total; }
Top answer
1 of 16
1205

You just need to remove the parenthesis:

addContact(entityId, refreshContactList);

This then passes the function without executing it first.

Here is an example:

function addContact(id, refreshCallback) {
    refreshCallback();
    // You can also pass arguments if you need to
    // refreshCallback(id);
}

function refreshContactList() {
    alert('Hello World');
}

addContact(1, refreshContactList);

You can also pass anonymous functions:

function addContact(id, refreshCallback) {
    refreshCallback();
    // You can also pass arguments if you need to
    // refreshCallback(id);
}

addContact(1, () => alert('hello world'));

2 of 16
560

If you want to pass a function, just reference it by name without the parentheses:

function foo(x) {
    alert(x);
}
function bar(func) {
    func("Hello World!");
}

//alerts "Hello World!"
bar(foo);

But sometimes you might want to pass a function with arguments included, but not have it called until the callback is invoked. To do this, when calling it, just wrap it in an anonymous function, like this:

function foo(x) {
   alert(x);
}
function bar(func) {
   func();
}

//alerts "Hello World!" (from within bar AFTER being passed)
bar(function(){ foo("Hello World!") });

If you prefer, you could also use the apply function and have a third parameter that is an array of the arguments, like such:

function eat(food1, food2) {
    alert("I like to eat " + food1 + " and " + food2 );
}
function myFunc(callback, args) {
    //do stuff
    //...
    //execute callback when finished
    callback.apply(this, args);
}

//alerts "I like to eat pickles and peanut butter"
myFunc(eat, ["pickles", "peanut butter"]); 

🌐
2N2L Web Tutorials
munnelly.com › webdesign › javascript › 6-functions-parameters.html
Functions with Parameters | Web Design & Development Tutorials | Brendan Munnelly
The parameters x and y are declared within the function definition. But their variable type – such as string or numeric – is not specified. Also, a JavaScript function does not check the number of parameters passed to it from elsewhere in the code.
Top answer
1 of 4
7
$("a").click(function(event){
    event.preventDefault();
});

The parameter you are passing to the function click is, itself a function. It looks like this:

function(event){
        event.preventDefault();
}

So event is the parameter that will be passed to that function by whatever calls that function. What calls that function is jQuery, when a click event happens on the targeted element(s).

If you look at the documentation for click you'll see this:

.click( handler )

handler

Type: Function( Event eventObject ) A function to execute each time the event is triggered.

So your function that you are passing is handler. Handler is a function that takes an eventObject (which you called simply event, which is fine - it doesn't matter here) argument of the type Event

So simply put, you don't need to worry about how that function gets called. The library will call it at the appropriate time and pass the appropriate object as event to that function. All you need to worry about is what to do in that handler which may or may not involve actually using event.

It might be confusing you that the function you are passing to click is anonymous. It doesn't have a name. If it helps, you can do this:

 function MyClickHander(event) {
     // do something here
 }

 $("a").click(MyClickHandler);

Which is essentially the same. But people often prefer to use anonymous functions rather than write potentially dozens of named handler functions for all the various events they might need to worry about.

EDIT:

It might help to also think about how you might write a function that took a function as a parameter (e.g. a function that takes a callback):

function Foo(callback) {
    bar = someValue;
    callback(bar);
}

Which you might use like this:

Foo(function(bar) {
    console.log(bar);
});

So here bar comes from inside Foo - just like event comes from inside click. You don't have to worry about exactly where in click event comes from (although you can dig through the source code if you are really so inclined), the jQuery documentation tells you what click will do with your handler so you don't have to.

2 of 4
2

Functions are first class citizens in javascript. So you can pass them around and assign them to variables. Don't think of them as control structures, but as things themselves. In the case of your click listener, the argument you are passing actually IS the function. You are telling the jQuery library "here is a function I want you to call whenever a click happens." And the jQuery documentation promises that, at the time it calls your function, it will call it with an argument of event.

Maybe it helps you to see the code this way:

var callMeOnClick = function(event){
    console.log(event);
};//nothing has happened yet. The function is being assigned to a variable, not invoked.
$("a").click(callMeOnClick);//giving the function to jQuery to execute later.

I think I understand the question you are asking, I'm just not sure how to explain it best. I hope that helps somewhat though.

🌐
Codeutopia
codeutopia.net › blog › 2016 › 11 › 24 › best-practices-for-javascript-function-parameters
Best practices for JavaScript function parameters | CodeUtopia
The problem with passing an object as a parameter to a function is that it’s not clear what values you should put into it. With libraries like jQuery, it isn’t a big deal – just look at the docs and oh there you go. But in the custom code you’ll run into at work? Just look at the docs… oh wait, what docs? Yeah. As much as documentation would be nice, custom codebases never have the kind of docs you’d need. If you need to figure out what parameters some function takes, you’re going to have to dig up the source code for it.