If you're seeing this message, it means we're having trouble loading external resources on our website.

If you're behind a web filter, please make sure that the domains *.kastatic.org and *.kasandbox.org are unblocked.

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?

  • hopper cool style avatar for user Sbayley13
    Why do you use println(); instead of text();?
    (288 votes)
    Default Khan Academy avatar avatar for user
  • primosaur tree style avatar for user -Drakon-
    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?
    (145 votes)
    Default Khan Academy avatar avatar for user
    • old spice man green style avatar for user Bob Lyon
      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.
      (197 votes)
  • blobby green style avatar for user Andrew Ashley
    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)
    Default Khan Academy avatar avatar for user
    • old spice man green style avatar for user Bob Lyon
      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:
          var booksPerShelf = 3;
      var row = floor(i / booksPerShelf);
      var col = i % booksPerShelf;
      Given a book's row and column, computing its X and Y coordinates on the canvas should be trivial.
      (22 votes)
  • hopper jumping style avatar for user dmkim2001
    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)
    Default Khan Academy avatar avatar for user
  • aqualine sapling style avatar for user Rainfalling
    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)
    Default Khan Academy avatar avatar for user
  • piceratops ultimate style avatar for user Ryan Highfill
    how do you make an object inside an object
    (12 votes)
    Default Khan Academy avatar avatar for user
  • winston default style avatar for user Hiteshew, Caden
    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)
    Default Khan Academy avatar avatar for user
  • mr pink red style avatar for user Den Karen
    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)
    Default Khan Academy avatar avatar for user
    • old spice man green style avatar for user Bob Lyon
      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, then
      var 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)
  • leafers ultimate style avatar for user Anthony T Lyristis
    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)
    Default Khan Academy avatar avatar for user
    • old spice man green style avatar for user Bob Lyon
      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)
  • duskpin tree style avatar for user mebble
    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)
    Default Khan Academy avatar avatar for user
    • blobby green style avatar for user A920213
      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 window
      var myVar = 0;
      can be deleted
      delete 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)