0

Possible Duplicate:
JavaScript arrays braces vs brackets

I have a simple question that I can't find an answer to with Google. What is the difference between

var foo = { };

and

var bar = [ ];

An example would help.

Community
  • 1
  • 1
Gregor Menih
  • 5,036
  • 14
  • 44
  • 66

1 Answers1

4

foo = {} is not an array, but an object (created using object literals, {}).

bar = [] is an array, which inherit various methods from the Array constructor. An array also has various properties, such as .length.

EDIT (regarding comment):
The a property of an object can be accessed through foo.a or foo["a"]. Looping through the properties of the object should be done using a for( .. in .. ) loop.

var foo = {"a":true, "b":false};
for(var prop_name in foo){
    alert(prop_name + " - " + foo[prop_name]);
}

This code will show two alert messages:

a - true
b - false
pimvdb
  • 151,816
  • 78
  • 307
  • 352
Rob W
  • 341,306
  • 83
  • 791
  • 678
  • but i've seen object being used like this: `foo = {"a":true, "b":false};`. Would it then be possible to see, if "a" is in "foo"? – Gregor Menih Oct 22 '11 at 18:05
  • @GregaMenih: Sure: `'a' in foo`. – Felix Kling Oct 22 '11 at 18:08
  • It's important to note that it's still an object, not an array. – JJJ Oct 22 '11 at 18:09
  • Great help, noted. One question only now: To see if 'a' is in foo, I would do `"a" in foo`, then what would I do to see if 'a' is NOT in foo? – Gregor Menih Oct 22 '11 at 18:16
  • @GregaMenih Use a `!` (logical NOT, negation): `!("a" in foo)`. See also: https://developer.mozilla.org/en/JavaScript/Reference#Operators_and_other_keywords – Rob W Oct 22 '11 at 18:51