User-Defined Objects
Everything in JavaScript is either one of the five primitive values (strings, numbers, Booleans, undefined, and null) or an object.
Objects are JavaScript’s sixth and final type.
In addition to built-in objects (arrays, strings, document, Math, Date, RegExp, …), new objects can be quickly and easily defined by the user.
Definitions
An object in JavaScript is a collection of named properties.
A property name is a JavaScript identifier or a string literal.
Quotes around a property name are optional if the name would be a legal JavaScript name. So quotes are required around “first-name”, but are optional around first_name.
Property values can be any JavaScript value: strings, numbers, Booleans, arrays, functions, objects and so on.
If a property’s value is a function, it is known as a method.
Objects as Associative Arrays
In computing, an associative array is a data structure that maps keys to values.
Therefore, an associative array (a.k.a. hash table, hash map, symbol table,dictionary, or db record) is a data structure composed of a collection of {key: value} pairs.
Object Literals
The easiest way to create an object is with an object literal.
An object literal is a comma-separated list of colon-separated name:value pairs, enclosed within curly braces {}.
Object literals are a distinguishing feature of the JavaScript language, as they allow objects to be created quickly without the need to define a class (as one has to do in Python, Java, C++, C#, etc.).
Examples
From our textbook (p. 112)
var superman = { name: "Superman", "real name": "Clark Kent", height: 75, weight: 235, hero: true, villain: false, allies: ["Batman","Supergirl","Superboy"], fly: function(){ 112 JavaScript: Novice to Ninja return "Up, up and away!"; } } Exercise: Add a getRealName method that returns Superman's real name.
Another Example
var lotteryNumbers = [4, 8, 15, 16, 23, 42]; var profile = { firstName: "Hugo", lastName: "Reyes", flight: "Oceanic 815", car: "Camaro" }; console.log(profile.lastName[0]); //"R"
Note how the lotteryNumbers array lends itself well to storing the sequence of lottery numbers, while the profile object is perfect for storing the key/value pairs of a person’s (Hugo’s) profile.
A Third Example (Github)
Optional
- Data Structures: Objects and Arrays (Eloquent JavaScript)
- Object Methods (Eloquent JavaScript)
- What it really means when people say “Everything in JavaScript is an object”. 7-min video (OReilly).