Main content
Computer programming - JavaScript and the web
Review: Objects
This is a review of what we covered in this tutorial on objects.
We have many types of values that we can store in JavaScript variables, and sometimes we want to store a bunch of related values together: that's where objects come in!
An object is a data type that lets us store a collection of properties in a single variable. To create an object, we declare a variable like we normally would, and then we use curly braces to surround key-value property pairs:
var objectName = {
propertyName: propertyValue,
propertyName: propertyValue,
...
};
Here's an object that describes Winston - this object has two properties,
hometown
and hair
, and each of the property values are strings:var aboutWinston = {
hometown: "Mountain View, CA",
hair: "no"
};
Here's a more complex object that describes a cat, with four properties-
age
, furColor
, likes
, and birthday
.var lizzieTheCat = {
age: 18,
furColor: "grey",
likes: ["catnip", "milk"],
birthday: {"month": 7, "day": 17, "year": 1994}
};
Notice how each property stores a different data type-
age
stores a number, furColor
stores a string, likes
stores an array, and birthday
stores another object. That's the cool thing about objects (well, one of the cool things) - they can store other objects inside them! So you can have deeply nested objects to describe complex data.You might also see objects declared using quotes around the property names, like:
var aboutWinston = {
"hometown": "Mountain View, CA",
"hair": "no"
};
That's equivalent to what we saw before with no quote marks, but it takes longer to type. The only time that you absolutely need quote marks is if your property name has a whitespace in it, like:
var aboutWinston = {
"his hair": "none"
};
We have to use quotes there, because otherwise the JavaScript interpreter would get confused. Here's my tip for you: just don't use whitespace in your property names to begin with! Then you never have to use quote marks around property names.
Accessing object properties
An object is not useful unless we can look inside it and grab the values of the different properties. We can do that two ways - first, using what we call "dot notation", where we write the name of the variable, followed by a ".", and then the property name:
var aboutWinston = {
hometown: "Mountain View, CA",
hair: "no"
};
text("Winston is from " + aboutWinston.hometown, 100, 100);
text("Winston has " + aboutWinston.hair + " hair", 100, 150);
We can also use "bracket notation", which looks similar to how we access array elements, where we write the variable name, then square brackets, with the property name inside in quotes:
var hisHometown = aboutWinston["hometown"];
var hisHair = aboutWinston["hair"];
If we try to access a property that doesn't exist, we'd see "undefined":
text("Winston's life goal is " + aboutWinston.lifeGoal, 100, 150);
Modifying object properties
Just like when we store other data types in variables, we can change the values of the object properties at any time during a program, using the dot or bracket notation:
aboutWinston.hair = "curly"; // Winston gets a wig!
We can also add entirely new properties!
aboutWinston.lifeGoal = "teach JavaScript";
If we're done with a property, we can delete it (but most of the time we'll probably just change its value):
delete aboutWinston.hair;
Arrays of objects
Now that you know both arrays and objects, you can combine them to make arrays of objects, which are actually really useful ways of storing data in programs. For example, an array of cats:
var myCats = [
{name: "Lizzie",
age: 18},
{name: "Daemon",
age: 1}
];
for (var i = 0; i < myCats.length; i++) {
var myCat = myCats[i];
println(myCat.name + ' is ' + myCat.age + ' years old.');
}
Notice that we iterate through an array of objects the same way that we iterate through an array of numbers or strings, using a for loop. Inside each iteration, we access the current array element with bracket notation, and then access the properties of that array element (an object) with dot notation.
Here's another practical example that you might use in your programs, an array of coordinate positions:
var positions = [
{x: 200, y: 100},
{x: 200, y: 200},
{x: 200, y: 300}
];
for (var i = 0; i < positions.length; i++) {
var position = positions[i];
ellipse(position.x, position.y, 100, 100);
}
Pretty neat, aye? Objects can be confusing at first, but keep using them, and eventually you'll be addicted and turn everything into an object!
Want to join the conversation?
- Why do you use println(); instead of text();?(288 votes)
- From the author:Right, I got bored of writing the text command, and the x/y can be distracting. I like using the println command for printing out information for debugging purposes, it's quite useful, try it!(584 votes)
- I feel like I'm at a dead end. I've gotten this far, but one glimpse at advanced code and I feel overwhelmed. I can't finish one line of code before going into the documentation and looking at everything again. Is there a better way to know how to combine things to get them to function properly, or is it just hours and hours of trial and error to get one thing to work? Am I just a really slow learner?(142 votes)
- It's not about being fast or slow. You are learning a new language here. (By looking at your projects, I see that you are actually learning at least two - HTML and Javascript.) Becoming proficient at a new language takes a lot of practice. Thirty programs for two languages is just not enough, particularly when some are simple spin-offs or abandoned challenges.
It's no big deal. I took two years of High School German, but never really became proficient. Similarly, two years of piano lessons did not have me playing Rachmaninoff.(194 votes)
- So this bookshelf project is one of the few I've struggled to complete entirely. I can get my first row showing fine with all information on three different books in the row with the stars working well....but! When I try to have my array carry over to the next row I'm not sure what the best approach is. Originally I created a row and column variable for each book to place them at top left, top middle etc. but the evaluation didn't pass for that approach. What's the best way to reset my values back to the left side at a certain point in the array?(31 votes)
- If
i
is your loop variable and the index into the book array, then a book's row and column are easily computed using integer division:
Given a book's row and column, computing its X and Y coordinates on the canvas should be trivial.var booksPerShelf = 3;
var row = floor(i / booksPerShelf);
var col = i % booksPerShelf;(22 votes)
- how to add a new property to each object to store a color, using the color command, and use that to fill each book differently?(16 votes)
- You have to type fill(book [i].color); under the for loop once you have added the category color as Lee suggested.(21 votes)
- I'm trying to do Project: Bookshelf, but the instant I tinker with the code I get Oh Noes saying "Did you mean to type status instead of stars?" That portion of code is there when you start the project and Oh Noes doesn't show up.(20 votes)
- So sorry you're having problems with that one. Hopefully it isn't blocking your progress and learning and creating.
Have you tried the "Start Over" button under the Project, and does it fix the issue? If not, are you able to report this to the Help Center and we'll try to take a closer look? You can click "Help Center" under report or click this direct link: https://khanacademy.zendesk.com/(6 votes)
- how do you make an object inside an object(12 votes)
{
x : 43,
y: {
a: 0,
b: 19
}
}(22 votes)
- in Challenge: Movie Reviews I tried to text the review, and there were no syntax errors or anything, but it did just not show up.(14 votes)
- Maybe you deleted the fill color. I did that by accident but I realized my mistake.(13 votes)
- Project: Bookshelf. I understand that the % operator calculates the reminder of a division. But I don't understand how to use it in a for loop, so that the books in the bookshelf will spread out on different shelves. Does anyone have examples of how to use the % operator in a for loop in this way?
And is it possible to only use the % operator to spread the books out, that is without any conditionals?(11 votes)- Yes. I highly recommend using math over logic in 98.73% of the cases where there is a choice. Assuming
books
is the array of book objects, thenvar booksPerShelf = 4; // constant
for (var i = 0; i < books.length; i++) {
var row = floor(i / booksPerShelf); // integer division
var col = i % booksPerShelf; // integer division's remainder
...
Given book i's row and column, it's easy to compute its associate X and Y coordinates on the canvas.(12 votes)
- Would anyone be willing to offer me a detailed description of what the role of "s" and "i" are in my FOR loop in the Bookshelf project?
for(var i=0; i<book.length; i++){
fill(214, 255, 219);
rect(10 + i* 100, 20, 90, 100);
fill(201, 28, 201);
text(book[i].title, 15+i*100, 29, 70, 100);
text(book[i].author,20+i*97,55,70,92);
for (var s=0; s < book[i].stars; s++) {
image(getImage("avatars/leaf-yellow"), 11 + s*13 + i*101, 90, 20, 30);}
On the very last line you see the equation 11+s*13+i*101 is the necessary X to space the stars(or leafs in my case) accordingly. This is a very ugly equation which makes me wonder how this makes it do what it does.(9 votes)i
is a variable whose value starts at zero. Each time the loop is about to repeat,i
is incremented by one.s
is a variable whose value starts at zero. Each time the loop is about to repeat,s
is incremented by one.
The ugly expression guarantees that the first star that is drawn lands on the appropriate book, and that subsequent stars land adjacent to (but not on top of) the previous star.(8 votes)
- It says here that we can delete an object's property by simply writing
delete aboutWinston.hair;
. Can this method be used to delete any variable or even an entire object? Is there any method to do so, if not this one? And can we also delete an array element from an array?(8 votes)- A variable (created with var) cannot be removed, but it will exist only in it's scope. So when the function is done, it is deleted.
In a browser the variable will be a property of windowvar myVar = 0;
can be deleteddelete window.myVar
For arrays there are several methods that can be used to delete elements.myArray.pop(); // removes last element
myArray.shift(); // removes first element shifting array down
myArray.slice(2, 4); // removes elements 2-3
delete myArray[5]; // myArray[5] is undefined
https://www.w3schools.com/js/js_array_methods.asp(5 votes)