Accessing properties
Learning Goals
By the end of the lesson, students will be able to:
- Access object keys by variable
Overview
Debugging Review
Debugging review with examples.
Discuss order:
- Syntax error
- Logic mistakes
Explore
Create a human version of an object and if/else chain.
- Go through an example with if/else chain similar to the one students create in the previous lesson. Announce your steps out loud.
- Check the input
- Go to the if/else chain and check the noun
- If it is not the noun proceed to the next until you find the proper noun
- Once the proper one has been found walk over to the example object to find the description.
- Bring the description to the user.
- Ask students, "Can you think of a better way to find the description?"
- If students are having trouble, point out that the object already has a list of the available items.
- Go through the example again, this time only checking the object.
- Check the input
- Go to the object
- If the input is there bring back the description
Questions
- Why is the checking the object important?
- As your game gets bigger how many items do you think will be in the game?
- Is it easier to check the list or create an if/else chain to check each word?
Explain
- Review what students currently know about accessing properties of objects
- In the generic example show students the syntax for accessing a Javascript object using a variable in repl.it
items: { light: 'There is a dim light', chair: 'The chair is old and green.', closet: 'Inside the closet you see a shiny key.' } - Students practice accessing the properties on the right hand side of the repl
- First students access using a string
items['light'] - Then students create a variable and access that way
var input = 'light' items[input] - Then create a function to do the same
function getItem (input) { return items[input] } getItem('chair') - Students practice adding an item to an object using this notation
function addToInventory (input) { inventory[input] = items[inventory] }
- First students access using a string
Engage
- Students work on refactoring their code
- Students work on adding an inventory to their game
- Students work on implementing an original feature