Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - Passing arguments to function

Tags:

javascript

I've always passed arguments to a function like so:

setValue('foo','#bar')

function setValue(val,ele){
    $(ele).val(val);
};

Forgive the silly example. But recently I have been working on a project that has some functions that take a lot of arguments. So I started passing the arguments through as an object (not sure if that's the correct way to put that), like so:

setValue({
  val:'foo',
  ele:'#bar'
});

And then in the function:

function setValue(options){

    var value = options.val;
    var element = options.ele;  

    $(element).val(value);

};

My question is, is there a better way to do that? Is it common practice (or okay) to call these 'options'? And do you typically need to 'unpack' (for lack of a better term) the options and set local vars inside the function? I have been doing it this way in case one of them was not defined.

I'm really looking to not create bad habits and write a bunch of code that is ugly. Any help is appreciated and + by me. Thanks.

like image 787
jyoseph Avatar asked Feb 04 '11 01:02

jyoseph


People also ask

How do you pass an argument from one function to another in JavaScript?

A function passed as an argument to another function is called a callback. A callback is passed by simply passing the name of the function.

How do you pass an argument to a function?

Arguments are passed by value; that is, when a function is called, the parameter receives a copy of the argument's value, not its address. This rule applies to all scalar values, structures, and unions passed as arguments. Modifying a parameter does not modify the corresponding argument passed by the function call.

How do you get all of the arguments passed to a function JavaScript?

You can access specific arguments by calling their index. var add = function (num1, num2) { // returns the value of `num1` console. log(arguments[0]); // returns the value of `num2` console.

Can a function take a function as an argument JavaScript?

Functions in JavaScript are 'first class', which means they are treated like any other variable — including being passed to or returned from other functions. When they're passed as an argument to another function, they're known as a 'callback' — to be called when the other function is ready for them.


1 Answers

I do the exact same thing, except I don't declare a new variable for each option inside the function.

I think options is a good name for it although I shorten it to opts.

I always have a "default" object within the function that specify default values for each available option, even if its simply null. I use jQuery, so I can just use $.extend to merge the defaults and user-specified options like this: var opts = $.extend({}, defaults, opts);

like image 150
simshaun Avatar answered Oct 14 '22 11:10

simshaun