An object is a way to collect data and assign a unique label to each item. One example of a real-life object is a dictionary - every word has a corresponding definition. Here's how a dictionary would look as an App Lab object:
var dictionary = {
"tortilla": "a thin, flat pancake of cornmeal or flour, eaten hot or cold, typically with a savory filling as a part of Mexican cuisine.",
"naan": "a type of leavened bread, typically of teardrop shape and traditionally cooked in a clay oven as part of Indian cuisine.",
"injera": "a white leavened Ethiopian bread made from teff flour, similar to a crêpe."
}
In the example above, each word in the dictionary is the key - it's what you use to look up values in the dictionary. The definitions are the values - they are what are trying to look up in the dictionary.
You can add new elements to an object using addPair. You can think of this as a pair of objects because you're adding two things: the key, and the value. In the dictionary example, this is like adding both the word and the definition to the dictionary:
We could add this to our dictionary with the code:
addPair(dictionary, "crepe", "a thin pancake, used to make sweet or savory dishes. Crepes are common in Vietnamese cuisine")
Add a new number to a contact list
var phoneNumbers = {
"Brendan": "520-555-1827",
"Alicia": "510-555-9182",
"Omar": "720-555-2817",
"Emergency": "911"
};
var name = prompt("Enter the new name you want to add to your contact list);
var number = prompt("Enter the new phone number");
addPair(phoneNumbers, name, number);
console.log(name + ": " + number + " was successfully added to your phone numbers");
Teach a chatbot what new abbreviations mean
var abbreviations = {
"LOL": "Laugh out loud",
"TIL": "Today I Learned",
"LGTM": "Looks Good To Me",
"FWIW": "For What It's Worth",
"FYI": "For Your Information"
};
console.log("Hello! I am learning new abbreviations! Would you like to look up an abbreviation, or teach me a new one?);
var choice = prompt("(1) Look Up an Abbreviation (2) Teach a New Abbreviation);
if(choice == 1) {
var word = prompt("What abbreviation do you want to look up?");
var definition = getValue(abbreviations, word);
console.log(word + ": " + definition);
}
if(choice == 2) {
var word = prompt("What is the new abbreviation?");
var definition = prompt("What does it mean?");
addPair(abbreviations, word, definition);
console.log("Successfully Added!");
}
addPair(object, key, value)
| Name | Type | Required? | Description |
|---|---|---|---|
| object | Object | The object to add the key and value pair. | |
| key | String | The name of the key to look up the value for in the object. | |
| value | Any | The value to store in the object under the key provided. |
None
Found a bug in the documentation? Let us know at documentation@code.org