Objects Flashcards
Object
• data structure that stores data in key-value pairs.
var person = { name: "Nigel", age: 21, city: "La" };
- keys are always strings
- values can be any type or variable
- objects are similar to arrays, but objects use strings, it’s “key”, to access the different elements.
key-value pair
• A pair made up of a string(called a key) that is matched with a particular value (which can be any type of Value). Key-value pairs go inside JavaScript objects, and they are used to define an objects properties and methods
What is a Property?
- A name for a key value pair in an object
* properties usually tell you something about an object.
Methods
- A method is a function associated with an object.
- Methods perform actions on the object
add: function(x, y) {
return x + y;
}
obj.add(10,5) //15
How do you retrieve Data out of an object?
- bracket notation, similar to arrays:
- objects are similar to arrays, but objects use strings, it’s “key”, to access the different elements.
console.log(person[“name”]);
• dot notation:
console.log(person.name);
• dot notation only works if the key doesn’t have any special characters like spaces, etc
What’s the difference between bracket vs doted notations?
1) you can not use dot notation if the property starts with a number.
someObject.1blah //invalid
someObject[“1blah”] //valid
2) can’t use dot notation for property names with spaces
someObject.fav color //invalid
someObject[“fav color”]; //valid
Updating Data
//to update age person["age"] += 1; //to update city person.city = "London";
How do you create an object?
1) make an empty object then add to it. var person = {} person.name = "Nigel" person.age = 21; person.city = "LA"; 2) All at once var person = { name = "Nigel", age = 21, city = "La" }; 3) use "new object();" keyword var person = new object(); person.name = "Nigel"; person.age = 21; person.city = "La";
What is a library?
• A collection of JavaScript code that someone else wrote that we can use in our own programs.
Object.keys(anyObject);
• returns an array containing all the keys of anyObject.