Node.js ABC’s - O is for Object
Objects are one of the core components of the JavaScript language and something that you will interact with every time you look at a pice of JavaScript code. The easiest way to explain what a JavaScript Object is would be to compare it to an "object" in real life. In JavaScript, an Object is a single entity with properties and a type. Compare that to a car. A car is a standalone object with properties too. A car has weight, design, color, materials, passenger capacity, etc. In the same way, a JavaScript object can have it's own set of properties which define it's characteristics.
Constructing and Object
There are several ways to create an object from scratch. You can use the Object constructor with the new operator or you can use the alternate object literal syntax by using curly-braces. These are called "Object Initializers".
Object Initializers
// create object from Object's constructor
var car = new Object(); // create object with object literal syntax
var car = {};
Object literal syntax is almost always preferred as it allows you to easily pre-populate the Object with properties. The following example creates a new "car" object that represents a blue 2015 Honda Accord.
var car = { make: "Honda", model: "Accord", year: 2015, color: "blue" };
Object Literal Notation looks a lot like JSON (JavaScript Object Notation) but differs in that wrapping property names in single or double quotes is optional, while with JSON it's mandatory. Certain JSON libraries allow for single quotes, but for broadest compatibility, I'd suggest using double quotes whenever possible.
This alternate declaration from above is both valid Object Literal Notation as well as JSON.
var car = { "make": "Honda", "model": "Accord", "year": 2015, "color": "blue" };
Constructor Functions
To use this method, you create a function named the type of Object you want, and in the function body, assign property values to the "this" property. The following example creates a "Car" constructor function and creates a new Car object of make "Honda".
// create a "Car" constructor function function Car(make) { this.make = make }; var car = new Car("Honda");
The Object.create Method
Objects can also be created using the "Object.create()" method. This method behaves similarly to the constructor function, but allows you to choose a prototype object for the object without defining a constructor function.
var Car = { "make": "Unknown", "getMake": function() { return this.make; } }; var honda = Object.create(Car); honda.make = "Honda";
Object Properties
As you have seen above, a JavaScript object can have properties associated with it. Think of a property of an object as a variable attached to it. Object properties are just like variables except that they are scoped within the context of that object. In the above example, I created a "car" object with "make", "model", "year", and "color" properties.
Properties are not limited to strings and integers. They can be any JavaScript type object including Functions and Objects themselves.
var interior = { "upholstery": "leather", "color": "tan", "mud-guards": "all-weather" }; var car = { "make": "Honda", // String "model", "Accord", // String "year", 2015, // Integer "color": "blue", // String "interior": interior, // Object "mileage": function() { // Function return 12345; } }
Adding Properties To An Existing Object
If you have an existing object and would like to add a property to it, it's as simple as assigning it a value with the "dot" or "bracket" notation
car.transmission = "manual"; car["sunroof"] = true;
An Object property name can be a string, or anything that can be dynamically converted to a string. But, if the property name starts with, or contains special characters, you must use the "bracket" notation.
var prop_name = "1CoolProperty"; car[prop_name] = "some value";
Enumerating Properties Of An Object
There are three native ways to enumerate object properties:
- "for..in" loops which traverse all enumerable properties of an object (and it's prototype chain)
- The "Object.keys(o)" method which returns an array with the enumerable properties of the object (not the prototype chain)
- The "Object.getOwnPropertyNames(o)" method which returns an array with the property names of an object.
Below is an example of iterating through all the properties of an object (including it’s inheritance chain) and filtering out only those properties that belong directly to that object.
for (var prop_name in car) { if (car.hasOwnProperty(prop_name)) { console.log(prop_name + " = " + car[prop_name] + "\n"); } }
Inheritance and Prototypes
Above I mentioned the word "prototype". All Objects in JavaScript inherit from at least one other object. This inherited object is known as the prototype and all inherited prototypes can be accessed with the "prototype" object of the constructor. Discussing prototypes and inheritance is more than a single article in itself, so I'll point you to the Mozilla documentation on Inheritance and the Prototype Chain for further reading on that topic.
Deleting Properties
You can remove a property from an object by using the "delete" operator. Keep in mind that you can only delete properties that are in scope with the current object (not inherited). The following code shows you how to remove a property:
var car = { "make": "Honda", "model": "Accord", "year": 2015, "color": "blue" }; delete car.color; // Deletes the color property for the car object.