-2

I was researching some sample code and couldn't understand this line of code

var foo = {};

As far as i could see it is used as a kind of arry where the index is a string entered by the user instead of 0,1,2,... etc. Can explain/confirm this. Cheers!

XD face me
  • 578
  • 1
  • 3
  • 12

4 Answers4

2

That is an object literal. It can be used like an associate array in other languages, but javascript objects tend to do much more. It does use key/value pairs, but the values can be functions, other objects, arrays or anything.

m59
  • 43,214
  • 14
  • 119
  • 136
1

declaring a javascript variable as {} is basically creating an empty object.

See this answer: Create an empty object in JavaScript with {} or new Object()?

Community
  • 1
  • 1
Mark Redman
  • 24,079
  • 20
  • 92
  • 147
0

{} represents an empty object.

To initialize an object you can do something like this:

var foo = {
    bar: "test";
}

alert(foo.bar); // alerts "test"
Kenneth
  • 28,294
  • 6
  • 61
  • 84
0

This is the notation for creating an empty object and assigning it to foo.

The 'array' like behavior is that JavaScript objects act like associative arrays - mappings between strings and properties, which can be Numbers, String, etc. or other Objects.

I suggest you read "JavaScript The Good Parts"

iandotkelly
  • 9,024
  • 8
  • 48
  • 67