1/// OBJECTS IN JAVASCRIPT
2const testScore = {
3 damon: 89,
4 shawn: 91,
5 keenan: 80,
6 kim: 89,
7};
8
9Object.keys(testScore); // gives all keys
10Object.values(testScore); // gives all values
11Object.entries(testScore); // gives nested arrays of key-value pairs
12
13// YOU CAN USE ( FOR-IN ) LOOP FOR ITERATION OVER OBJECTS
14for (let person in testScore) {...}
15
16// WE CAN'T DIRECTLY USE ( FOR-OF ) LOOP IN OBJECTS BUT WE CAN DO Like THIS:
17for(let score of Object.values(testScore)){
18 console.log(score) // 89 91 80 89
19}
20
21
1objectName.methodname = functionName;
2
3var myObj = {
4 myMethod: function(params) {
5 // ...do something
6 }
7
8 // OR THIS WORKS TOO
9
10 myOtherMethod(params) {
11 // ...do something else
12 }
13};
14
1// create 2 objects for Mark and John that calculate their BMI's
2// BMI = mass / height ** 2 || mass / (height * height);
3// mass: kg
4
5// john object
6const johnObj = {
7 firstName: "John",
8 lastName: "Smith",
9 mass: 92,
10 height: 1.95,
11 calcBMI: function () {
12 // learn more about 'this'
13 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this
14 this.bmi = Number((this.mass / this.height ** 2).toFixed(2));
15 return this.bmi;
16 },
17};
18
19// mark object
20const markObj = {
21 firstName: "Mark",
22 lastName: "Miller",
23 mass: 78,
24 height: 1.69,
25 calcBMI: function () {
26 this.bmi = Number((this.mass / this.height ** 2).toFixed(2));
27 return this.bmi;
28 },
29};
30
31// store the ternary results in a variable
32const results =
33 johnObj.calcBMI() > markObj.calcBMI()
34 ? `${johnObj.firstName} has a higher BMI of ${johnObj.calcBMI()} than ${
35 markObj.firstName
36 }'s BMI of ${markObj.calcBMI()}!`
37 : `${markObj.firstName} has a higher BMI of ${markObj.calcBMI()} than ${
38 johnObj.firstName
39 }'s BMI of ${johnObj.calcBMI()}!`;
40
41// display the results on the console
42console.log(results);