Objects review

What you need to know about objects for Monday’s assessment.

Object syntax

{ name: 'Mr. Seibel', job: 'Teacher' }

Creates an object with two properties, name and job.

Creating objects with computed values

let randomPoint = {
  x: Math.random() * 100,
  y: Math.random() * 100
};

Property access

person.name

or

person['name']

You should use the former when you can.

(You have to use the second syntax if the property name doesn’t follow the rules for a Javascript variable name, e.g. it contains a space or punctuation.)

Assigning to properties

point.x = 200

or

point['x'] = 200

Again, use the former unless you can’t.

Functions that take objects as arguments

const distance = (p1, p2) => {
  return Math.sqrt((p1.x - p2.x) ** 2 + (p1.y - p2.y) ** 2);
}

This function takes two objects representing points and returns a number.

Functions that create objects

const point = (x, y) => {
  return { x: x, y: y };
}

This function takes two numbers and returns an object.

Functions that both take and return objects

const midpoint = (p1, p2) => {
  return {
    x: (p1.x + p2.x) / 2,
    y: (p1.y + p2.y) / 2
  }
};

This function takes two objects and returns a new object.