Book Image

Object-Oriented JavaScript

Book Image

Object-Oriented JavaScript

Overview of this book

Table of Contents (18 chapters)
Object-Oriented JavaScript
Credits
About the Author
About the Reviewers
Preface
Built-in Functions
Regular Expressions
Index

From Arrays to Objects


As you already know from Chapter 2, an array is just a list of values. Each value has an index (a numeric key) starting from zero and incrementing by one for each value.

>>>> var myarr = ['red', 'blue', 'yellow', 'purple'];
>>> myarr;

["red", "blue", "yellow", "purple"]

>>> myarr[0]

"red"

>>> myarr[3]

"purple"

If you put the indexes in one column and the values in another, you'll end up with a table of key/value pairs like this:

Key

Value

0

red

1

blue

2

yellow

3

purple

An object is very similar to an array but with the difference that you define the keys yourself. You're not limited to using only numeric indexes but can use friendlier keys, such as first_name, age, and so on.

Let's take a look at a simple object and examine its parts:

var hero = {
  breed: 'Turtle', 
  occupation: 'Ninja'
};

You can see that:

  • The name of the variable that contains the object is hero

  • Instead of [ and ] which you use...