Unit 2
Objects
What is an object and why are they useful?
An object is a data type that holds multiple pieces of data called properties.
Objects represent individual "things".
Arrays hold similar values
Objects hold related values.
const user1 = {
name: "Ben Spector",
email: "ben@mail.com",
age: 28,
}
console.log(user1.name);
const user2 = {}
user2.name = "C3PO"
user2.email = "c3po@mail.com"
user2.age = 250
Turn and Talk:
Consider Instagram. What data might Instagram use objects for?
Object Vocab: Properties, Keys, and Values
This object has 4 properties, each with a key and value.
Keys cannot have spaces and must start with an alphabetical character, _, or $
Values can be any data type
const post563 = {
src: "instagram/user235/post563.jpg",
caption: "Another day programming…",
likes: 563219,
comments: [
'You Got This!',
'Good looking code ;)',
'That for loop tho…'
]
}
const obj = {
aKey: "value",
anotherKey: 5,
aBool: false,
anArray: ['a', 'b', 'c']
}
Spot the Error
const post563 = {
src: "instaserver/user235/post563.jpg"
caption: "Just another day programming…"
likes: 563219
comments: [
'You Got This!'
'Good looking code ;)'
'That for loop tho…'
]
}
Keys Are Strings!
Keys are strings, but we can leave out the quotations when writing an object.
We must include the quotations if:
Note that keys in an object are not in a reliable order!
const myObj = {
a: 5,
0: 10,
"!!!": 20,
"A Key": 30,
}
const keysOfMyObj = Object.keys(myObj);
console.log(keysOfMyObj);
// prints ['0', 'a', '!!!', 'A Key']
Reading/Writing Object Data
Like arrays, we can reference the values in an object using bracket notation
const user = {
name: "ben",
age: 27,
}
if (user["age"] >= 18) {� user["canVote"] = true�}
else {� user["canVote"] = false�}
console.log(user);
obj["keyName"]
Turn and Talk:
What will be printed?
Reading/Writing Object Data
Or we can use dot notation
const user = {
name: "ben",
age: 7,
}
if (user.age >= 18) {
user.canVote = true
}
else {
user.canVote = false
}
console.log(user.canVote);
obj.keyName
Turn and Talk:
What will be printed?
Bracket vs. Dot Notation
We can always use bracket notation but we must use it if:
const myObj = {
a: 5,
0: 10,
"!!!": 20,
"A Key": 30,
}
console.log(myObj.a); // 5
console.log(myObj.0); // error
console.log(myObj.!!!); // error
console.log(myObj.A Key); // error
console.log(myObj["a"]); // 5
console.log(myObj["0"]); // 10
console.log(myObj[0]); // 10
console.log(myObj["!!!"]); // 20
console.log(myObj["A Key"]); // 30
Turn and Talk:
How are arrays and objects similar
How are they different?
Nested Objects / Arrays
const user = {
friendList: ["Carmen", "Motun"],
bio: {� name: "Ben Spector",
age: 0,
siblings: ["Daniel", "Michael", "William"]
}
}
user.bio.name; // Ben Spector
user.friendList[0]; // Carmen
user.bio.siblings.length; // 3
How would you reference:
const user = {
friendList: ["Carmen", "Motun"],
bio: {� name: "Ben Spector",
age: 0,
"my siblings": ["Daniel", "Michael", "William"]
}
}
More about accessing Object Properties
Attempting to access a property that doesn't exist returns undefined.
const myObj = {
a: 5,
0: 10,
"!!!": 20,
}
console.log(myObj.foo); // undefined
console.log(myObj.length); // undefined
console.log(myObj["bar"]); // undefined
Turn and Talk:
Objects are passed (copied) by reference. Come up with a code example that demonstrates this.
Dynamic Properties
When the key we want to access is stored in a variable, we must use bracket notation.
const myObj = {
a: 5,
0: 10,
"!!!": 20,
};
let keyToAccess;
keyToAccess = "a";
console.log( myObj[keyToAccess] ); // 5
keyToAccess = 0;
console.log( myObj[keyToAccess] ); // 10
console.log( myObj.keyToAccess ); // undefined
Turn and Talk:
Why does myObj.keyToAccess return undefined?
How do we Iterate through an object?
We can use a for…in loop to iterate through the keys of an object.
We then use bracket notation to access each value.
const myObj = {
a: 5,
0: 10,
"!!!": 20,
};
for (let key in myObj) {
console.log(key);
console.log(myObj[key]);
}
Turn and Talk:
What is printed to the console?
Turn and Talk:
const myObj = {
a: 5,
0: 10,
"!!!": 20,
};
for (let key in myObj) {
console.log(key);
console.log(myObj[key]);
}
let nums= [ 1, 2, 3, 4 ];
for (let i = 0; i < nums.length; i++) {
console.log(i);
console.log(nums[i]);
}
What is similar and what is different about iterating over an array vs. an object?
Other Iteration Approaches
const myObj = { a: 5, 0: 10, "!!!": 20 };
const values = Object.values(myObj);
for (let i = 0; i < values.length; i++) {
console.log(values[i]);
}
const keys = Object.keys(myObj);
for (let i = 0; i < keys.length; i++) {
console.log(myObj[keys[i]]);
}
Methods
A method is a property of an object whose value is a function. We can invoke them by referencing their key followed by parentheses.
const myMathObj = {
max: (a, b) => {
if (a > b) {
return a;
} else {
return b;
}
},
min: (a, b) => {
if (a < b) {
return a;
} else {
return b;
}
}
}
myMathObj.max(3, 5)
Turn and Talk:
What is console.log?
What is console?
An Object Example: Snake
https://benspector3.github.io/snake/
Object Documentation
You need to understand how to use the following operators and methods:
Object Destructuring
const { log } = console; // console.log
const {
max, // Math.max
min, // Math.min
random, // Math.random
floor, // Math.floor
PI // Math.PI
} = Math;
log(max(4,3)); // 4
log(min(4,PI)); // 3.14159…
log(floor(random() * 6) // 1-6
Destructuring is particularly useful to take particular known values out of objects.
const {keyA, keyB} = obj;
In this example, we log() from the console object and we extract a number of methods of the Math object.