5

Very simple question but I'm quite new to JS and this is not easy to search.

If I see a line like this:

var colours = {}, r, g, b;

I get that it's just a declaration for 3 vars, but what does the {} bit mean? I can't see anywhere that gives me an idea as to what this is declaring?

Thanks!

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
FBryant87
  • 4,273
  • 2
  • 44
  • 72
  • 1
    possible duplicate of [What do curly braces in javascript mean?](http://stackoverflow.com/questions/9699064/what-do-curly-braces-in-javascript-mean) – Felix Kling May 11 '12 at 12:54

7 Answers7

6

It declares new object and equivalent to new Object();

antyrat
  • 27,479
  • 9
  • 75
  • 76
4
 var colours = {}, r, g, b;

This declares 4 variables which is the same as

   var colors = {}; // this is an empty object like, var colors = new Object();
   var r; // undefined
   var g; // undefined
   var b; // undefined
kamui
  • 3,339
  • 3
  • 26
  • 44
2

It means that colours is going to be an object.

ShaneBlake
  • 11,056
  • 2
  • 26
  • 43
2

{} declares an object, with no members. Like an empty data container. [] would declare an empty array.

Arrays have number indexes (and a few handy methods) and objects can have string indexes (but lack the methods of an array)

K..
  • 4,044
  • 6
  • 40
  • 85
  • 2
    Fun fact: Even arrays are objects in JavaScript. – Chris Sobolewski May 11 '12 at 12:55
  • 3
    They don't have "string indexes" but "properties". The `[]` syntax is just another way to access their properties (and the only proper way to access a property with a non-fixed name, e.g. `foo['bar' + x]`) – ThiefMaster May 11 '12 at 12:55
2

It's a declaration of four variables, not three. One is called colours and is initialized to {}. The others are called r, g, and b, and their initial values are undefined. {} is an empty object literal.

Gareth McCaughan
  • 19,888
  • 1
  • 41
  • 62
1

It's declaring an empty object literal.

Rob
  • 12,659
  • 4
  • 39
  • 56
1

It initializes colors with a new, empty object.

While objects in JavaScript can have methods, too, they are often used as associative arrays, which is pretty likely in this case (assumption based on the name and the fact that it's initialized without any properties).

ThiefMaster
  • 310,957
  • 84
  • 592
  • 636