javascript · level 2 · unit 5 · lesson 2
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
Change or add a key with a dot, or look one up with brackets.
Put a new value in with a dot and =: pet.age = 4; overwrites the age. Use a key the object has never had, and it is added: pet.vet = "Dr Khan";. A const object can still change inside, because const only stops the variable holding a different object.
Sometimes the key's name is in a variable, like field holding "name". Then use : pet[field] looks up the key held inside field. pet.field would look for a key really called field.
Ask for a key that is not there and you get undefined.
const pet = { name: "Rex", age: 3 };
pet.age = 4;
pet.vet = "Dr Khan";
const field = "name";
console.log(pet[field], pet.field);
console.log(pet); Brackets take any string, so pet["age"] and pet.age mean the same thing.
guess first
Restocking the fruit stall. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
const stock = { apples: 4, pears: 0 };
stock.apples = stock.apples - 1;
stock.plums = 6;
const fruit = "pears";
console.log(stock[fruit], stock.apples);
console.log(stock);
your turn
Your turn. Build a tiny translator.
Pick one of the four English words and type it between the quotes. In the second blank, look it up with the variable that holds it. Press run.
fix it
The cafe price says undefined. Fix it!
- The price shows as
undefined, so the lookup found no such key. prices.drinklooks for a key called drink. You want the key held inside the variabledrink.- Change prices.drink to prices[drink] on line 3, then press run.
nailed it
you can change and look up any key. :D
- A dot and
=change a key, or add a new one. obj[variable]looks up the key held in the variable.- A missing key gives
undefined.
new words in your collection
- bracket notation
This lesson isn’t saved. A free account remembers every lesson you finish.