56

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

var port = chrome.extension.connect({name: "testing"});
port.postMessage({found: (count != undefined)});
Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
milan
  • 2,179
  • 9
  • 24
  • 34

4 Answers4

210

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"
Lord Zed
  • 750
  • 7
  • 28
Matthias Winkelmann
  • 15,870
  • 7
  • 64
  • 76
  • 31
    Thank you so much. This is exactly the answer I was looking for. [More here.](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) – FuzzY Dec 11 '15 at 07:30
  • 5
    This is actually the correct answer, as the question states "for functions". – George Y. Oct 25 '19 at 02:40
40

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"
user113716
  • 318,772
  • 63
  • 451
  • 440
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.

camomilk
  • 763
  • 1
  • 7
  • 15
0
var x = {title: 'the title'};

defines an object literal that has properties on it. you can do

x.title 

which will evaluate to 'the title;

this is a common technique for passing configurations to methods, which is what is going on here.

hvgotcodes
  • 118,147
  • 33
  • 203
  • 236