Skip to the content

Comparing objects

JavaScript · Unit 14: Modern classes

Two objects with the same data are not the same object. Between objects, === doesn't look at what's inside: it asks whether both variables point at the same object.

class Point {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }
}
const a = new Point(1, 2);
const b = new Point(1, 2);
console.log(a === b);

Prints

false

The rest of the explanation is in the lesson, which is part of the full plan.

Exercises in this lesson

You do them in the app, which checks them on the spot and explains why.

  1. 1. Predict the output

    c wasn't created with new. What does it print?

  2. 2. Predict the output

    The note is changed through b. What does it print?

  3. 3. Multiple choice

    Between two objects, what is a === b actually asking?

  4. 4. Predict the output

    Three different questions about two red mugs. What does it print?

  5. 5. Complete the code

    Two points are equal when both coordinates match. Fill in the method.

  6. 6. Predict the output

    c is the first color in the palette. What does it print?

  7. 7. Find the bug

    Both payments are 200, so this should print "paid". Which line has the error?

  8. 8. Put the lines in order

    Put in order the Coin class and the two lines that compare two 5-coins, first by identity and then by value.

  9. 9. Find the case that fails

    compare(x1, y1, x2, y2) builds two points and says whether they're equal: equal means both coordinates match. Which call does it fail on?

  10. 10. Predict the output

    Set keeps values without repeats. What does it print?

Do this lesson

It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.

See all lessons →