Main content
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?
- 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?(135 votes)
- Don't give up! I felt this way when I began learning as well. What I did was before I went on to the next lesson I sat down and tried to understand why and how the code works. And I don't move on until I get it. :)(13 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?(30 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;(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)
- 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)
- 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)
- Movie Reviews was so hard I took three years to do it(2 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)
- In the bookshelf project, how do you get the stars to show up on each book? I get how to repeat the title, but how do you display 2 stars on one book and 3 on another?(5 votes)
- You need to use both counter variables to calculate the
x
argument for the stars.
The distance is the space between the books. The space is the space between the stars.offset + outer counter * distance + inner counter * space
You need to use the counter from the outer loop to get the group of stars on the right book, the way you get thetitle
on the book, and then the inner loop accounts for the separate stars.(7 votes)
- Hello,
I'm having trouble to get the stars to loop for each of the books in the same row.. I yet only managed to do it "manually" for each book. I think the problem is that I cant seem to figure how to set the next books stars to start at x += 96...
One way I thought it could be done if there is a way to query the index number of the loop (if it is 1. movie, 2. movie and so forth) so I could use that as a multiplier for the starting position somehow..
Now my code for the stars looks like this:
var x = 14;
var y = 89;
// var jump = 96;
for (var i = 0; i < books[i].stars; i++) {
image(getImage("cute/Star"), x + i * 20, y, 20, 30);}
for (var i = 0; i < books[1].stars; i++) {
image(getImage("cute/Star"), 96 + x + i * 20, y, 20, 30);}
for (var i = 0; i < books[2].stars; i++) {
image(getImage("cute/Star"), 96 + 96 + x + i * 20, y, 20, 30);}
for (var i = 0; i < books[3].stars; i++) {
image(getImage("cute/Star"), 96 + 96 + 96 +x + i * 20, y, 20, 30);}
Maybe some one has figured this out? The next problem for stars would be to nest the loop to lay it to next row too. Probably if and boolean, will fix this?
Second question.
How can you control the loop so that it stops when it reaches the fourth book (as i have four books in the upper most level) and then continues at the next row until there is no entries left in objects. Maybe if and booleans, but where would those be and maybe someone could give an example?
Thank you very much. I'm very newbie, but a keen learner..(7 votes)