arguments on function use array and argument?

Recommended Posts


i would reduce my function to create my levels.

acutally i create my level directly inside my state in my main.js.

i would use them on another file so i have a function with a lot of arguments eg:


var level0= init_level0(player,enemy,flag,otherparam)

//is it possible to do this

var level0= init_level(config,otherparam)
//where config is equivalent to config=[player,enemy,flag] 

in fact i have always the same argument in my init_level[number] and for a question of readability i would reduce the arguments. is there a way for that ?

Share this post

Link to post
Share on other sites

Yep, whack them in to an object. There is an argument to be had here that single-arity functions (just one argument, often an object) are best as it means redundant arguments can be ignored easily and setting up defaults becomes easier etc etc

// before
function create (name, health, strength, etc etc) {

// after
function create (params) {
  var character = new Character() =

const PC = create({
  name: 'Dave',
  health: 100,

The biggest advantage here is that you can use defaults easily, e.g. in the example above presume health is not necessary but I want to set strength, how do you do that with multiple arity functions?

`create('dave', null, 10)` Adding null parameters is fairly rubbish and what happens when null (or false) is a valid entry but you in fact want to just ignore it completely and use whatever the default is set to be? You don't want your consumer to have to manually plug in defaults and exposing defaults for each parameter is also pretty rubbish for many use-cases.

You can always try reordering your arguments so that less-used ones come last and can be omitted but this is brittle and often a poor solution.

With a single object you can just ignore those parameters you dont want and ensure your callers only specify the parameters they care about.

There are lots of articles about the benefits of a single-arity approach (there are few cons), I can't find the best one I've read about it but I've just quickly googled it and looks like there are lots of similar articles that go into it in a little more depth.

Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Recently Browsing   0 members

    No registered users viewing this page.