77

I have recently been messing around with jQuery on my website, and I have a fairly limited knowledge of Javascript. I am beginning to like the jQuery ability to pass variables to a jQuery function inside the curly braces, like so:

$(somediv).animate({thisisone: 1, thisistwo: 2}, thisisavar);

What I was wondering is how I can write a Javascript function that I can pass items to inside the curly braces? I know you can write functions like this:

function someName(var1, var2, var3...) {

}

but that doesn't support the braces? I also know that you can add no arguments and do this:

function accident() {
    for( var i = 0; i < arguments.length; i++ ) {
        alert("This accident was caused by " + arguments[i]);
    }
}
accident("me","a car","alcohol","a tree that had no right to be in the path of my driving");

but I also want to pass outside variables instead of just a whole line of strings, if that makes sense?

Basically, I want a function that I can pass variables to, like so:

function myFunction(neededcodehere){
    //Some code here...
}

myFunction (var1, {"Option 1", "Option 2", "Option 3"}, anothervar);
3
  • 1
    FWIW, {"Option 1", "Option 2", "Option 3"} and var 1 are not valid JavaScript. Commented Oct 14, 2011 at 7:46
  • Wraith, I would just like to point out that if your passing pre-declared variables, your function will already be able to access them without any special syntax (as long as they're not nested within some other function). Commented Oct 14, 2011 at 7:59
  • Hey Marlin, they aren't going to be pre-declared, I wrote it wrong, its going to look something like myFunction("Title", {"Option 1" : "option1name", "Option 2" : "option2name"}, true) Commented Oct 14, 2011 at 8:01

6 Answers 6

139

The "braces" are making an object literal, i.e. they create an object. It is one argument.

Example:

function someFunc(arg) {
    alert(arg.foo);
    alert(arg.bar);
}

someFunc({foo: "This", bar: "works!"});

the object can be created beforehand as well:

var someObject = {
    foo: "This", 
    bar: "works!"
};

someFunc(someObject);

I recommend to read the MDN JavaScript Guide - Working with Objects.

Sign up to request clarification or add additional context in comments.

5 Comments

Do you know how to set a default value if, say, the foo value wasn't passed? Such that someFunc({bar: "works!"}); still generates the alerts saying "This" and "works!"
@Normajean You create a defaults object with same properties and merge with the arguments object. See my answer below as the formatting in comments is poor
Here's an updated url to MDN JS Guide: developer.mozilla.org/en-US/docs/Web/JavaScript/Guide
Hi @Felix. what if that object has a function? it is called immediately. how can i prevent this?
@Arash: You should post an actual question. I'm missing a lot of context here but creating an object that contains a function as a property does not automatically call said function. If it does in your case then your code is (intentionally or unintentionally) set up to do that.
11
function myFunction(arg) {
    alert(arg.var1 + ' ' + arg.var2 + ' ' + arg.var3);
}

myFunction ({ var1: "Option 1", var2: "Option 2", var3: "Option 3" });

1 Comment

Right. ...I was tyring to JSON.parse() my object literal. ...it was already parsed! ...doh!
7

Answering normajeans' question about setting default value. Create a defaults object with same properties and merge with the arguments object

If using ES6:

    function yourFunction(args){
        let defaults = {opt1: true, opt2: 'something'};
        let params = {...defaults, ...args}; // right-most object overwrites 
        console.log(params.opt1);
    }

Older Browsers using Object.assign(target, source):

    function yourFunction(args){
        var defaults = {opt1: true, opt2: 'something'};
        var params = Object.assign(defaults, args) // args overwrites as it is source
        console.log(params.opt1);
    }

Comments

2

in this way:

  • no need to change your function signature and your function calls.
  • support defaults overrides.
  • use ES6 object destrrcturing.
function yourFunction(args) {
    let defaults = {opt1: true, opt2: 'something'};
    let params = {...defaults, ...args}; // right-most object overwrites 
    const {opt1, opt2, opt3} = params
    console.log(opt1);
}

Comments

0

when you pass an object within curly braces as an argument to a function with one parameter , you're assigning this object to a variable which is the parameter in this case

Comments

0

My cents.

function readable(args) {
    const {opt1, opt2, opt3} = args

 
    console.log(opt1 + opt2 + opt3)
    // => "My favorite things"
}


readable({
      opt1: "My f"
    , opt2: "avori"
    , opt3: "te things"
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.