Chapter 1. JavaScript Objects
Creating Objects
In JavaScript, objects are king: Almost everything is an object or acts like an object. Understand objects and you will understand JavaScript. So let’s examine the creation of objects in JavaScript.
An object is just a container for a collection of named values (a.k.a. properties). Before we look at any JavaScript code, let’s first reason this out. Take myself, for example. Using plain language, we can express in a table, a “cody”:
cody | |
property: | property value: |
living | true |
age | 33 |
gender | male |
The word “cody” in the table above is just a label for the group of property names and corresponding values that make up exactly what a cody is. As you can see from the table, I am living, 33, and a male.
JavaScript, however, does not speak in tables. It speaks in objects, which are not unlike the parts contained in the “cody” table. Translating the above table into an actual JavaScript object would look like this:
<!DOCTYPE html><html lang="en"><body><script> // create the cody object... var cody = new Object(); // then fill the cody object with properties (using dot notation) cody.living = true; cody.age = 33; cody.gender = 'male'; console.log(cody); // logs Object {living = true, age = 33, gender = 'male'} </script></body></html>
Keep this at the forefront of your mind: objects are really just containers for properties, each of which has a name and a value. This notion of a container of properties with named values (i.e., an object) is used by JavaScript ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access