What is an Object in JavaScript?
You may have heard that JavaScript is an object-oriented language, but what is an object?
Imagine we create a universe. How can we describe it to someone else? We might use words and numbers. (In JavaScript, these are primitive values.) We also need context and experience to understand those words. Well, an object gives you the power to create context. Let’s see how...
A simple declaration using curly braces creates an empty object:
const obj = {};
Imagine that words and numbers are like the electrons and protons of our universe, and objects are like the atoms. Objects are the fundamental build blocks of JavaScript. Every value that is not null or undefined is described by an object. For example, you might ask, “What is a number?” JavaScript provides a Number object to describe the number data type. Similarly, a Boolean object describes the boolean data type, and so on.
How does JavaScript use objects to “describe” a thing?
JavaScript objects can have properties and methods. Think of properties as descriptive of state. For example, an apple object might have properties of color, size, and weight. Let’s assign values to each one:
const myApple = {
color: "red",
size: "large",
weight: "8 oz"
}
To see the contents of any JavaScript object, you can use a JSON object method to create a string:
console.log(JSON.stringify(myApple));
// logs: "{'color':'red','size':'large','weight':'8 oz'}"
Properties and methods are named, and these names are called “keys.” You'll often hear object properties described as key/value pairs because each key is the name of a value. The key of the first property in our Apple object is color, which is paired with a value of red.
A method can also be labeled by a key, but it contains a function instead of a value. Methods in objects are like DNA – genetic instructions that describe an object’s capability.
An apple can rot, so let’s create a method called rot that describes the decay after is picked or falls from the tree. We’ll assume it takes seven days to rot and use an interval of 3 seconds for each day.
A method can be added when creating the object like this:
const myApple = {
color: "red",
size: "large",
weight: "8 oz",
rot: function() {
let countdown = 7;
let intervalID = window.setInterval(function () {
console.log(countdown + " days remaining");
countdown--;
if (countdown === 0) {
console.log("completely rotted!");
window.clearInterval(intervalID);
}
}, 3000);
}
};
We can also add a method to an existing object. If we start with a Apple that contains three properties...
const myApple = {
color: "red",
size: "large",
weight: "8 oz"
}
... we can add a method to that existing object using dot notation:
myApple.drop = function() {
let countdown = 7;
let intervalID = window.setInterval(function () {
console.log(countdown + " days remaining");
countdown--;
if (countdown === 0) {
console.log("completely rotted!");
window.clearInterval(intervalID);
}
}, 3000);
}
Now we have described an apple in JavaScript, and the properties and method of our myApple object are accessible to us. For instance, we can answer questions.
What color is the apple? Use dot notation to get the answer:
console.log(myApple.color); // logs: red
or bracket notation around a string:
console.log(myApple.["color"]); // logs: red
or bracket notation around an expression as long as it evaluates to the appropriate string:
console.log(myApple.["co" + "lor"]); // logs: red
Want to watch the apple rot? Call the rot() method:
myApple.rot();
You can explore this example at codepen.
Object keys can be a string, number, or symbol. Symbols are one of the seven primitive types in JavaScript. Because they are not enumerable, they are excluded if you iterate through the object using a for ... in loop. Also, they are not supported by Internet Explorer, if that matters to you.
When I explored the question of What is an array in JavaScript, I mentioned that an array is a type of object. An array is more limited because the key is not a string, but a number starting with 0. So you can have a myApple object with red as the first value, but the key won’t be color. It will be 0. You probably don’t want to use an array to describe an apple because keys can only be numerical indexes.
Related posts:
Helpful references:
Have feedback on this topic?