Question about Arrays

I’m reading the Eloquent Javascript online book. I’m on Chapter 8, and there’s a piece of code that spits out all the properties of an array. = function() {
  var result = [];
  for (var property in this) {
    if (this.hasOwnProperty(property))
  return result;

var test = {"Fat Igor": true, "Fireball": true};

Why is the colon and true necessary? If I take them out and just have

var test = {"Fat Igor", "Fireball"};

I get a SyntaxError: missing : after property id.

Hi John,

Curly braces are actually for declaring objects in JS . The reason for the colon and true is because with an object you’re assigning values to properties, and the syntax for declaring object properties is propertyName: value. Every property needs to have a value assigned (even if that value is null or false).

If you want an array then you need to use squared brackets:

var myArray = ['Fat Igor', 'Fireball'];

There are two kinds of arrays in PHP. Simple arrays, starting with [ and ending in ], and hashes, starting with { and ending with }.
The difference is that arrays can only contain values, whereas hashes can contain key-value pairs.

Both have their uses. If I wanted to list prime numbers I could do something like this:

var primes = [1, 3, 5, 7, 13]; // and so on and so forth....

A flat list suffices here, because I’m not interested in any information about the numbers, but just the numbers themselves.
If on the other hand I did want to record information about something with properties, like a person, I could do:

var john = {
    name: 'John',
    age: 30,
    city: 'London'

Note that I’m using {} here instead of . You can’t mix these.
If you want, you can combine them though (or ‘nest’ them):

var john = {
    name: {
        first: 'John',
        last: 'Doe'
    age: 30,
    city: 'London',
    favourite_primes: [5, 23]

You may not that I’m not quoting my keys (name, age, city, etc). Quoting them is optional, and I like not quoting them, but that’s personal preference. If a key contains spaces however (like the “Fat Igor” in your example), it must be quoted.

Hope that helps. If you have any more questions feel free to ask :slight_smile:


@fretburner; beat me to it :eye: