Why objects matter

Let's say we were building a color application where we had to store a lot of colors with their respective hex codes.

And there's a lot of colors that we had to manage. We'd have a shade of blue with it's hex code, so we logically make a variable called blue:

const blueColor = "#00f";

And along with blue, we have a good orange color, which we want to create and access around our app as well:

const orangeColor = "#f60";

As you can already see, creating and naming places to store and reference these value would be pretty tedious. Every time we make one, we have to keep writing the same things--const to declare the variable and to name the variables clearly, we have to add the word color onto them after their particular value name. Try to imagine about if we got orders to create hundreds of colors in our app. That would be exhausting.

And not to mention the fact that none of these values are tied together in any way. They are all free floating variables available in our global scope. There is no relationship shared between these values and nothing connecting them other that a hint to that in their suffix, 'color'. Is there any way to group multiple related values together?

Maybe one approach we could think of managing lots of values, particularly string values would be to create a long string composed of each of these hex codes:

const colors = `${blueColor} ${orangeColor}`;

But now we've lost all ability to easily access them. How are we going to use each individual value.

So this is a case where we need to lean on the language and we're going to look at a new data structure to help us manage multiple values. We'll be doing that by now moving on to the other side of JS data types, objects.

Objects give us powerful patterns for managing and organizing related data.

Variables are boxes; objects are file cabinets

If we know of variables as boxes that can store anything we like, objects on the other hand are file cabinets. How do we get anything from a file cabinet? We have a reference to what we want to find, say a file with a given name. You can imagine every value that is on an object as a separate file and it has a separate, unique identifier that we can use to access it, called a key or property. I'll call them keys or properties interchangeably.

Just like variables, we can name keys whatever we like, so we know that no matter what value is being stored in it, we can get it's value.

Object literal syntax

So now let's create our first object. The way objects is with two curly braces and between these braces will be all of our keys with their corresponding values:

{
}

And just so you know, the double curly syntax is technically called the object literal syntax.

And we can start putting data in objects right away when we create them.

So to return to our analogy, if the object is file cabinets, where we put our files, the keys are the names on each of the files, while the values are the files themselves. If you keep this in mind, it's easy to understand why objects consist of what are known as key value pairs.

We write our key, our reference to the data first in the pair:

{
  key;
}

And every key is just a simple JavaScript string. We'll return to this fact later. And then to link it with its corresponding value, we write a colon and then the value itself. So here, let's make the value the string 'value'.

{
  key: "value";
}

And what's powerful about key-value pairs on objects is that while keys can only be strings, their associated values can be any data type, they can be another primitive, such as a number or boolean:

{
  key: true;
}

Or they can even be other objects, that include their own key-value pairs. Say if the key property was itself and object with the property key set to 'value':

{
  key: {
    key: "value";
  }
}

Objects that have objects within them are called nested objects. They can be nested as many times as is necessary for the application data.

And notice the formatting convention I used here. When an object is not nested and just one or two properties, we can write it all on one line:

{
  key: "value";
}

But if we have a nested object or just an object with a lot of properties, we put the curly braces on separate lines and indent each level of data that we have. Either 2 or 4 spaces is the convention:

{
  key: {
    key: "value";
  }
}

Object methods

And since I said we can put any data type on our objects, we can also put functions on them. So we to make a very simple function, say hi that just console logs 'hi'. And note that we can use whatever function variant we like--either a function declaration or an arrow function:

{
  sayHi: function() {
    console.log('hi');
  }
}

And since methods are effectively function assignments, where we're connecting a function with a given identifer, we don't need to give it a name (if we're using the function keyword)

But with ES6, as we've seen, we have lots of ways of making things shorter and dropping boilerplate like the function keyword. So with it came a shorthand to write the same function declaration with less code. We can write a method without the function keyword and also without the semicolon:

{
  sayHi() {
    console.log('hi');
  }
}

So if you see the syntax, know that, behind the scenes this is still just a normal function.

Where else method exist

And since we now know that methods are just functions on objects, pause right now and try to name a couple of examples of methods that we've worked with already.

Well can you name an object that we've worked with in the past? One that I can name is the global object. And we've used functions from it a great deal already (for example, just now), such as alert, prompt as well as console.log:

alert();
prompt();
console.log();

Remember that we don't often have to write the name of the object, window, but that is effectively what we're doing:

window.alert();
window.prompt();
window.console.log();

So based off of what we've already observed, if a method is a direct property of an object, we can call it by using the following syntax:

objectName.methodName();

So let's try calling sayHi on our object. We'll do that first by storing our object in a variable call obj (note that we'll come up with more descriptive names when we have actual data). And then just say obj.sayHi();

const obj = {
  sayHi() {
    console.log("hi");
  },
};

obj.sayHi();

[Run code] And we see that it works. We'll dive more into this dot syntax that we're using here in later lessons.

So now let's return to our original example of organizing color data for our app. Take a minute and create a new object that we'll use to organize our colors and add one new color key value pair to it, that is, a new color...

So I'll give my color object what I think is a logical and obvious name 'colors'. If they were being used for a specific purpose, I would work that intent into the name. We'll create our object with the curly brace that is the object literal syntax. That is how objects are always created. And then I'll add a new color yellow. So to easily reference in the future, I'll give it a key name of yellow. Note that it doesn't have any quotes around it, even though it's a string. This is how keys are written, but for the value they have to be written properly according to their data type. So we'll have a hex code string here like the other values, namely ff0. It has to be a valid string with quotes around it. We'll go deeper into these observations and what's happening in later lessons in this section:

const colors = {
  yellow: "#ff0",
};

And note that I didn't have to call this key, yellowColor, like I would have if we were using a variable. Because it's place in this object named colors, it's clear that its a piece of color data.

And since we're creating an object here, we can bring in the other values that we originally had as variables, blueColor and orangeColor. In a similar fashion to this yellow key, we can drop the color suffix and just put these values on two keys, blue and orange, respectively. So blue will be set to blueColor and orange will be set to orangeColor:

const colors = {
  yellow: "#ff0",
  blue: blueColor,
  orange: orangeColor,
};

And now if we console.log(colors), we see our created object with all their key value pairs:

const colors = {
  yellow: "#ff0",
  blue: blueColor,
  orange: orangeColor,
};
console.log(colors);

So this is totally valid if we needed to get our color data from variables. But we can make this even better. In a similar fashion to the method shorthand that we saw with objects to write less code, there is an object property shorthand, and it makes good intuitive sense.

So to demonstrate, since we have a colors object, we no longer really need to have our variable end with color, so we can edit them to just be blue and orange:

const blue = "#ff0";
const orange = "#f60";

And we then need to update our properties that we are initializing in the colors object:

const colors = {
  yellow: "#ff0",
  blue: blue,
  orange: orange,
};
console.log(colors);

So what's cool here is that since it's not required for keys to use quotes around them, which gives them the same appearance as a JS variable, we can take advantage of that if the property we are creating has the same name as the value we are putting on it. So in other words, since the value variable name is the same as the key name, we can just shorten it to:

const colors = {
  yellow: "#ff0",
  blue,
  orange,
};
console.log(colors);

Pretty neat huh? Another nice shorthand that we can use with objects to cut down our code. You can console.log again and see that we get the same result.

Get Property Data with Dot Syntax

And to come full circle now, to access each of these values, we can use the exact same dot syntax like our method used? Since methods are properties just like any other key, we can simply use the syntax of:

objectName.key;

So for example, to get the color yellow, we can say colors.yellow:

console.log(colors.yellow);

So when any one else working on this app needs the color yellow, they jsut grab it directly: colors.yellow. It’s that simple. And we could use the same syntax for anything else we want to get, say the color blue:

console.log(colors.blue);

So as you can see, this is why objects are perfect for grouping and using static information.

What objects are good for

So before we move on, know that objects are great when you want to share unchanging structured key-value data, but are not appropriate for dynamic information that is updated frequently, as you will see in later lessons.

For example, if you wanted to share your collection of colors, objects are a great choice. The data doesn’t change. In this example, we wouldn’t dynamically change the hex value for blue or orange because it doesn't change.

For all of these reasons, objects play a huge role in JavaScript and we'll be using them extensively for the rest of the course.