All About Objects

Today we're going to talk about objects. Note that this is just a very basic practical introduction to objects and doesn't go into Object Oriented Programming or the technical details of how Javascript objects work. See Further Information for that.

An object is another type of data structure in Javascript. Technically, every non-primitive in Javascript is an object. This includes arrays and functions.

However, for our purposes in this class, we're going to think about objects as being a special type of thing. Objects have keys and values.

// each entry in an object is a key-value pair
let myObject = {
    "cats": "cute",
    "dogs": "cool",
}

// we access values the same way as in an array
console.log(myObject["cats"])

// we assign new keys the same way we access them
myObject["birds"] = "smelly"

// you can loop through keys using for in loops
for (key in myObject) {
    console.log(`${key} are ${myObject[key]}`)
}

One of the main uses of objects is to make it easy to pass data between functions, especially when returning multiple values.

function totalPets(data) {
    let total = 0
    for (let pet in data) {
    total += data[pet]
}
    return total
}

function hasNumber(data, number) {
    let petsWith = {}
    for (let pet in data) {
        petsWith[pet] = (data[pet] === number)
    }
    return petsWith
}

let pets = {"birds": 1, "cats": 2, "dogs": 2} 
let total = totalPets(pets)
let hasNumberList = hasNumber(pets, 2)
console.log(`Total pets: ${total}; Has 2: ${hasNumberList}`)

Objects can store any data type, just like an array. You can do some cool tricks with objects by exploiting this property; for example they can be used to simplify complex and dull if-else statements.

// incomplete example of using objects to set up calculator functions

// if statement version
if (operation == '+') add(a,b)
else if (operation == '-') subtract(a,b)
else if (operation == '/') divide(a,b)

// object version
let operations = {'+': add, '-': subtract, '/': divide}
console.log(operations[operation](a,b))

Assignment VII

Write a quiz game where the player has to select from 4 choices (e.g. a,b,c,d). Each question needs to store the question, the possible answers, and the correct answer as an object. Note that the easiest way to do this is to use the quick way to make arrays and objects:

let listOfQuestions = [
    {
        // question body
    }
]

At the end of the quiz, the player should be given their score and the option to play again. Please write 3 or more questions.

Hint: you probably want to write some functions for extracting information from your list of questions.

Further Information

  • For more details on how Javascript objects work, see Hashable Data Structures from cs-101.
  • For object-oriented programming on the web, see the first part of the Javascript Frameworks course (web-102).