Curly braces inside JavaScript arguments for functions

24,701

Solution 1

The curly braces denote an object literal. It is a way of sending key/value pairs of data.

So this:

var obj = {name: "testing"};

Is used like this to access the data.

obj.name; // gives you "testing"

You can give the object several comma separated key/value pairs, as long as the keys are unique.

var obj = {name: "testing",
           another: "some other value",
           "a-key": "needed quotes because of the hyphen"
          };

You can also use square brackets to access the properties of the object.

This would be required in the case of the "a-key".

obj["a-key"] // gives you "needed quotes because of the hyphen"

Using the square brackets, you can access a value using a property name stored in a variable.

var some_variable = "name";

obj[ some_variable ] // gives you "testing"

Solution 2

A second possible answer has arisen since this question was asked. Javascript ES6 introduced Destructuring Assignment.

var x = function({ foo }) {
   console.log(foo)
}

var y = {
  bar: "hello",
  foo: "Good bye"
}

x(y)


Result: "Good bye"

Solution 3

Curly braces in javascript are used as shorthand to create objects. For example:

// Create an object with a key "name" initialized to the value "testing"
var test = { name : "testing" };
alert(test.name); // alerts "testing"

Check out Douglas Crockford's JavaScript Survey for more detail.

Share:
24,701
milan
Author by

milan

Updated on July 09, 2022

Comments

  • milan
    milan almost 2 years

    What do the curly braces surrounding JavaScript arguments for functions do?

    var port = chrome.extension.connect({name: "testing"});
    port.postMessage({found: (count != undefined)});
    
  • FuzzY
    FuzzY over 8 years
    Thank you so much. This is exactly the answer I was looking for. More here.
  • George Y.
    George Y. over 4 years
    This is actually the correct answer, as the question states "for functions".
  • rpivovar
    rpivovar over 4 years
    This is the answer
  • vishal dharankar
    vishal dharankar over 4 years
    what a concise answer , kudos ! Had been reading lot of answers but all were stating technical jargons with complex possible answer . Great work . thanks