Last Updated: September 09, 2019
·
25.39K
· nima_shariatian

Better way of passing multiple parameters to a function in javascript

This can get very ugly soon
I magine this :

function Person(firstName, lastName, age, gendre, eyeColo ) {
          //do stuff here 
 }

A better way to do it would be to send the arguments as an object literal

function Person (options) {
    var defaults = {
        firstName: "John",
        lastName: "Smith",
        age:  12,
        gendre: "male",
        eyeColor: "brown"
    },
    o = $.extend(defaults, options )
} 

Now you can easily access the options by doing :

o.firstName 
o.lastName 

And you can call the function like this :

var bob = new Person({ 
        firstName: "Bob", 
        lastName: "Doe",
        age: 50,
        gendre: "male",
        eyeColor: "blue"
}); 

Hope this helps someone!
Nima.

3 Responses
Add your response

Hi all , I just wanted to say this is my first tip and my very first comment!
I am always open to new ideas and ways to improve my code, if you find anything wrong with my codes, please share!

Thanks
Nima

over 1 year ago ·

HI!

I think that, for performance reasons I'd first put what has been passed in local variables :

function Person (options) {
  var self = this
    , firstName = options.firstName || "John"
    , lastName = options.lastName || "Smith"
    , age = options.age || 12
    , gendre = options.gendre || "male"
    , eyeColor = options.eyeColor || "brown"

  // some code here

  $.extend(self, {
    firstName : firstName,
    lastName : lastName, 
    age : age,
    gendre : gendre,
    eyeColor : eyeColor
  })
} 

The basic function is here a little more complex, but minifying local variable names is possible whereas object properties can't be changed (it's interesting if you perform tasks with the passed arguments). Also, as I said : http://mlb.tl/L7eQ

Cheers

over 1 year ago ·

@mlb Thanks for the reply!
Though my focus wasn't really on performance, this clearly seems to win !

over 1 year ago ·