Week 7: Objects, Object Literals & JSON

To Do This Week:

Work on Hangman (Due Feb 26 28) and Generative Literture Projects (Due March 12).

Try to finish Codecademy. Especially "Objects."


Notes


Audio/Video Element & JavaScript:

Important notes: Examples:

Code samples

Jump to a specific time.

videoElement.currentTime = 10; // jump to 10 seconds

Sync audio to the current video time (works for multiple media elements too).

audioElement.currentTime = videoElement.currentTime;

Slow down or speed up playback.

videoElement.playbackRate = 2.0; // double speed
videoElement.playbackRate = 0.5; // half speed

Trigger code when the video passes certain timestamps.

videoElement.addEventListener("timeupdate", function () {
  if (videoElement.currentTime > 5 && videoElement.currentTime < 6) {
    console.log("Triggered at ~5 seconds");
  }
});

Loop only a specific section (from 5s to 10s).

videoElement.addEventListener("timeupdate", function () {
  if (videoElement.currentTime > 10) {
    videoElement.currentTime = 5; // loop back
  }
});

Play and pause the video.

videoElement.play();
videoElement.pause();

Restart from the beginning and play.

videoElement.currentTime = 0;
videoElement.play();

Toggle play/pause with one button.

if (videoElement.paused) {
  videoElement.play();
} else {
  videoElement.pause();
}

Mute and unmute.

videoElement.muted = true;  // mute
videoElement.muted = false; // unmute

Play the video in a loop.

videoElement.loop = true;

Store timestamps and labels as objects (e.g., for lyrics or captions).

const lyrics = [
  { time: 0,  text: "First line of the song" },
  { time: 5,  text: "Second line of the song" }
];

Objects, Object Literals and Classes

built-in JavaScript Objects

Objects are variables that store properties and methods.

JSON (JavaScript Object Notation) is a format for storing and exchanging data. It looks similar to a JavaScript object and behaves in a comparable way.

Simple Object Literal


// JavaScript Object Literal Example
const person = {
    firstName: "Margie",
    lastName: "Pepper",
    age: 50,
    eyeColor: "brown",
};

console.log(`Hi, ${person.firstName}`);

Object Literal



// JavaScript Object Literal Example
const person = {
    firstName: "Henry",
    lastName: "Smith",
    age: 24,
    eyeColor: "green",
    fullName() {
        return `${this.firstName} ${this.lastName}`;
    }
};

console.log(`Hi, ${person.fullName()}`);

Simple JSON

JSON is just a text format for data. It is commonly used in APIs to pass data between a server and your JavaScript code.


// Start with a normal JavaScript object
const personObj = {
    firstName: "Nina",
    lastName: "Lopez",
    age: 29,
    eyeColor: "brown"
};

// Convert JS object -> JSON string
const personJSON = JSON.stringify(personObj);
console.log(personJSON);
// {"firstName":"Nina","lastName":"Lopez","age":29,"eyeColor":"brown"}

// Convert JSON string -> JS object
const backToObject = JSON.parse(personJSON);
console.log(backToObject.firstName); // "Nina"

// IMPORTANT NOTE:
// JSON cannot store functions (methods). It only stores data (strings, numbers, booleans, arrays, objects).

Person Object Constructor


// JavaScript Object Constructor Example
function Person(firstName, lastName, age, eyeColor) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.age = age;
    this.eyeColor = eyeColor;
    this.fullName = function() {
        return `${this.firstName} ${this.lastName}`;
    };
}

// Create new Person objects
const person1 = new Person("Alice", "Brown", 32, "blue");
const person2 = new Person("Carlos", "Diaz", 28, "hazel");

console.log(person1.fullName()); // "Alice Brown"
console.log(person2.fullName()); // "Carlos Diaz"


Simple Classes

A class is a modern way to create many objects that share the same structure and behavior. It is similar to the constructor function above, but cleaner to read.


// JavaScript Class Example (simple)
class Person {
    constructor(firstName, lastName, age, eyeColor) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.age = age;
        this.eyeColor = eyeColor;
    }

    fullName() {
        return `${this.firstName} ${this.lastName}`;
    }
}

const person1 = new Person("Alice", "Brown", 32, "blue");
const person2 = new Person("Carlos", "Diaz", 28, "hazel");

console.log(person1.fullName()); // "Alice Brown"
console.log(person2.fullName()); // "Carlos Diaz"

Complex Classes

This example adds:


// JavaScript Class Example (more features)
class Person {
    constructor(firstName, lastName, age, eyeColor) {
        this.firstName = firstName;
        this.lastName = lastName;

        // Default value if age is missing or undefined
        if (age === undefined) {
            age = 0;
        }
        this.age = age;

        this.eyeColor = eyeColor;
    }

    fullName() {
        return `${this.firstName} ${this.lastName}`;
    }

    // A getter is like a "computed property"
    get isAdult() {
        return this.age >= 18;
    }

    // A method that changes the object's data
    birthday() {
        this.age = this.age + 1;
    }


}

const p = new Person("Tariq", "Nguyen", 17, "brown");
console.log(p.fullName()); // "Tariq Nguyen"
console.log(p.isAdult);    // false

p.birthday();
console.log(p.age);        // 18
console.log(p.isAdult);    // true

console.log(mina.fullName()); // "Mina Park"

https://api.openweathermap.org/data/2.5/weather?q=${city},${state},us&appid=5d403b6b84ed210aa64a032618aa4156&units=imperial

In-Class Exercise

In this exercise you'll start with a working two-player dice game and extend it by adding properties and methods to the Player class. Each challenge follows the same pattern: add something to the class, then make the changes needed so that something visible shows on screen. The goal is to sense how a class holds a state, how methods update that state, and how the DOM can reflect it.

The Opacity Challenge

Each challenge below builds on the last. Before writing any code, read the question and with your partner, think through the logic steps. What does the class need to store? What method changes it? Where in the compare function do you call that method?

  1. Opacity as health. Add an opacity property to the Player class. Add a win() and a lose() method that increase or decrease it. Both players start at 0.5. After each round, apply the updated value to the button.
  2. Declare a winner. Once you have opacity changing each round, add a conditional that checks whether a player has reached full opacity. If they have, announce them as the winner and stop the game. Where in the code does that check belong?
  3. Track a streak. Add a streak property to the class. Write a method that increments it on a win and resets it to zero on a loss. Add a conditional that messages the user when a player is on a streak of two or more. How would you show that message — and where would it appear on the page?
  4. Add a bonus. When a player wins the opacity game, reset both players' opacity back to 0.5 and award the winner a bonus point. Add a bonus property to the class to track this. How would you carry the bonus forward into the next game? How would you show the player their current bonus on screen?

Learn more about JSON and objects: