DEV Community

Rodrigo Rojas
Rodrigo Rojas

Posted on

Object of My Affection

Alt Text
There are only seven fundamental data types in JavaScript, and six of those are the primitive data types: string, number, boolean, null, undefined, and symbol. With the seventh type, objects, we open our code to more complex possibilities. We can use JavaScript objects to model real-world things, like me, or we can use objects to build the data structures that make the web possible. But that's boring, let's use me as an example.

At their core, JavaScript objects are containers storing related data and functionality, but that deceptively simple task is extremely powerful in practice. We’ve been using the power of objects all along, but now it’s time to understand the mechanics of objects and start making our own!

Creating Object Literals

Objects can be assigned to variables just like any JavaScript type. We use curly girls, {}, to designate an object literal:

const rod = {}; // rod is an empty object :(
Enter fullscreen mode Exit fullscreen mode

We fill an object with unordered data. This data is organized into key-value pairs. A key is like a variable name that points to a location in memory that holds a value.

We make a key-value pair by writing the key’s name, or identifier, followed by a colon and then the value. We separate each key-value pair in an object literal with a ,.

// An object literal with two key-value pairs
const rod = {
  hairColor: 'black',
  age: 'nunya'
}; 
Enter fullscreen mode Exit fullscreen mode

Dot Notation for Accessing Object Properties

Properties of a JavaScript object can be accessed using the dot notation in this manner: object.propertyName. Nested properties of an object can be accessed by chaining key names in the correct order.

const rod = { 
  age: 'nunya',
  powers: {
    p1: 'sleeping',
    p2: 'programming'
  }
};
console.log(rod.age); // 'nunya'
console.log(rod.powers.p1); // 'sleeping'
Enter fullscreen mode Exit fullscreen mode

Bracket Notation

The second way to access a key’s value is by using bracket notation, [ ].

We must use bracket notation when accessing keys that have numbers, spaces, or special characters in them. Without bracket notation in these situations, our code would throw an error.

const rod = {
  'Favorite Cheese': 'Camembert',
  'Wants Nap': true,
  hometown: 'Oakland',
  hungerLvl: 5
};
rod['Wants Nap'];   // Returns true
rod['Favorite Cheese'];   // Returns  'Camembert'
rod['hungerLvl'];   // Returns 5
rod['happinessLvl'];   // Returns undefined
Enter fullscreen mode Exit fullscreen mode

With bracket notation you can also use a variable inside the brackets to select the keys of an object. This can be especially helpful when working with functions:

let returnAnyProp = (objectName, propName) => objectName[propName];

returnAnyProp(rod, 'Favorite Cheese'); // Returns 'Camembert'
Enter fullscreen mode Exit fullscreen mode

If we tried to write our returnAnyProp() function with dot notation objectName.propName the computer would look for a key of 'propName' on our object and not the value of the propName parameter(trust me, I've made this mistake before).

Property Assignment

Once we define an object, we’re not stuck with all the properties we wrote. Objects are mutable meaning we can update them after we create them.

We can use either dot notation, ., or bracket notation, [], and the assignment operator, = to add new key-value pairs to an object or change an existing property.

One of two things can happen with property assignment:

  • If the property already exists on the object, whatever value it held before will be replaced with the newly assigned value.
  • If there was no property with that name, a new property will be added to the object.

It’s important to note that although we can’t reassign an object declared with const, we can still mutate it, meaning we can add new properties and change the properties that are there.

const rod = {age: 'nunya'};
rod = {age: 40}; // TypeError: Assignment to constant variable.
rod.age = 18; // Changes the value of the age property
rod.speed = 'Mach 5'; // Creates a new key of 'speed' with a value of 'Mach 5'
Enter fullscreen mode Exit fullscreen mode

You can delete a property from an object with the delete operator.

const rod = {
  'Favorite Cheese': 'Camembert',
  'Wants Nap': true,
  motto: "I'm sleepy" 
};

delete rod.motto;  // Removes the motto property
Enter fullscreen mode Exit fullscreen mode

Nested Objects

In application code, objects are sometimes nested— an object might have another object as a property which in turn could have a property that’s a collection of even more objects.

const rod = { 
  age: 'nunya',
  powers: {
  'Main Powers': {
    p1: 'sleeping',
    p2: 'programming'
 },
  'Secondary Powers': {
   p3: 'eating',
   p4: 'shopping'
}
  }
};
Enter fullscreen mode Exit fullscreen mode

We can chain operators to access nested properties. We’ll have to pay attention to which operator makes sense to use in each layer. It can be helpful to pretend you are the computer and evaluate each expression from left to right so that each operation starts to feel a little more manageable.

rod.powers['Secondary Powers'].p4; // Returns 'shopping'
Enter fullscreen mode Exit fullscreen mode

In the preceding code:

First the computer evaluates rod.powers, which results in an object containing the 'Main Powers' and 'Secondary Powers' objects.
We accessed the 'Secondary Powers' object by appending ['Secondary Powers'].
The 'Secondary Powers' object has a p4 property, accessed with .p4 which returned the value stored there: 'shopping' (I don't have a shopping problem I swear).

Summary

Woohoo! You made it to the end of my self-deprecating tutorial on JS objects. We’re well on our way to understanding the mechanics of objects in JavaScript. By building our own objects, we have a better understanding of how JavaScript built-in objects work as well(psstconsole). We can also start imagining organizing our code into objects and modeling real world things in code.

Extra Credit: Classes

One last thing before we go...
JavaScript is an object-oriented programming (OOP) language we can use to model real-world items. Classes are a tool that we'll use to quickly produce similar objects.

For example, imagine we have a daycare for doggos and want to create a catalog of all the dogs who belong to the daycare. Instead of creating an instance for every dog that joins the daycare, we can create a Dog class that serves as a template for creating new Dog objects. For each new dog, we can provide a value for their name.

class Dog {
  constructor(dogName) {
    this._name = dogName;
    this._behavior = 0;
  }

  get name() {
    return this._name;
  }
  get behavior() {
    return this._behavior;
  }   

  incrementBehavior() {
    this._behavior ++;
  }
}
const pooper = new Dog('Pooper');
console.log(pooper.name); // Pooper
console.log(pooper.behavior); // 0
pooper.incrementBehavior(); // Add one to behavior
console.log(pooper.behavior); // 1
Enter fullscreen mode Exit fullscreen mode
Sources:

MDN Objects
Getter
Constructor
This
Console in Javascript

Top comments (0)