1 of 22

Unit 2

Objects

2 of 22

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

3 of 22

Turn and Talk:

Consider Instagram. What data might Instagram use objects for?

4 of 22

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']

}

5 of 22

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…'

]

}

6 of 22

Keys Are Strings!

Keys are strings, but we can leave out the quotations when writing an object.

We must include the quotations if:

  • The key begins with non-alphanumeric characters
  • The key is a string with spaces�

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']

7 of 22

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?

8 of 22

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?

9 of 22

Bracket vs. Dot Notation

We can always use bracket notation but we must use it if:

  • the key is a number
  • the key is a string beginning with a non-alphanumeric character.

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

10 of 22

Turn and Talk:

How are arrays and objects similar

How are they different?

11 of 22

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

12 of 22

How would you reference:

  • Motun, and William?

const user = {

friendList: ["Carmen", "Motun"],

bio: {� name: "Ben Spector",

age: 0,

"my siblings": ["Daniel", "Michael", "William"]

}

}

13 of 22

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

14 of 22

Turn and Talk:

Objects are passed (copied) by reference. Come up with a code example that demonstrates this.

15 of 22

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?

16 of 22

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?

17 of 22

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?

18 of 22

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]]);

}

19 of 22

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?

20 of 22

An Object Example: Snake

https://benspector3.github.io/snake/

  • Inspect
  • Find the first line in the update() function
  • Be prepared to add a breakpoint at the first line
  • Play and grab a few pieces
  • Add a breakpoint. Then, look at the snake

21 of 22

Object Documentation

You need to understand how to use the following operators and methods:

22 of 22

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.