Declare an object
Declares an object and stores it in a variable.
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 use getValue()
to access the values of the dictionary, and you can use addPair()
to add new values to the dictionary.
Examples
Profile Object
Creates an object to store profile information
var myProfile = {
"name": "Michelle",
"age": "17",
"interests": "Computer science, playing music, basketball",
"favorite food": "seafood tacos"
}
Choose Your Own Adventure
Using objects to start a choose your own adventure game
var options = {
"left": "You see a giant squid! It looks dangerous at first, but then you start to pet it and it becomes friendly",
"straight": "You see a large table with food on it! All of your friends jump out and say 'Surprise! Happy Birthday!'",
"right": "You are now outside and it's snowing! You start making a snowman and humming your favorite song to yourself"
};
console.log("There are three doors in front of you - which path will you take? left, right, or straight?");
var answer = prompt("Enter your choice (left, right, or straight)");
var response = getValue(options, answer);
console.log("You chose " + answer + "! Here's what happens:");
console.log(response);
Syntax
var object = {"key": "value"};
Returns
Tips
- The
keys
in a dictionary must be unique.- For example:
var dictionary = {"orange": "a color", "orange": "a fruit"}
would return an error
- For example:
- Objects are similar to arrays in the following ways:
- Both allow you to store a collection of data
- You can add elements to both an object and an array
- You use a single variable to access the entire collection of variables
- Objects are different from arrays in the following ways:
- Arrays store ordered information, and you can access each element by its index in the array
- Objects tore unordered information, and you can access each element by it's key value
Found a bug in the documentation? Let us know at support@code.org.