xxxxxxxxxx
/// OBJECTS IN JAVASCRIPT
const testScore = {
damon: 89,
shawn: 91,
keenan: 80,
kim: 89,
};
Object.keys(testScore); // gives all keys
Object.values(testScore); // gives all values
Object.entries(testScore); // gives nested arrays of key-value pairs
// YOU CAN USE ( FOR-IN ) LOOP FOR ITERATION OVER OBJECTS
for (let person in testScore) { }
// WE CAN'T DIRECTLY USE ( FOR-OF ) LOOP IN OBJECTS BUT WE CAN DO Like THIS:
for(let score of Object.values(testScore)){
console.log(score) // 89 91 80 89
}
xxxxxxxxxx
const student = {
id: 101,
major: "Mathamatics",
money: 5000,
name: "Abrar",
subjects: ["English", "Economics", "Math 101", "Calculus"],
bestFriend: {
name: "Kundu",
major: "Mathematics"
},
takeExam: function () {
console.log(this.name, "taking exam");
},
treatDey: function (expense, tip) {
this.money = this.money - expense - tip;
return this.money
}
}
student.takeExam();
//Output: Abrar taking exam
const remaining1 = student.treatDey(900, 100);
const remaining2 = student.treatDey(500, 50);
console.log(remaining1);
console.log(remaining2);
//Output: 4000,3450
xxxxxxxxxx
Object methods in javascript:
create()
keys()
values()
entries()
assign()
freeze()
seal()
getPrototypeOf()
xxxxxxxxxx
objectName.methodname = functionName;
var myObj = {
myMethod: function(params) {
// ...do something
}
// OR THIS WORKS TOO
myOtherMethod(params) {
// ...do something else
}
};
xxxxxxxxxx
const engine = {
// method shorthand, with one argument
start(adverb) {
console.log(`The engine starts up ${adverb}...`);
},
// anonymous arrow function expression with no arguments
sputter: () => {
console.log('The engine sputters...');
},
};
engine.start('noisily');
engine.sputter();
/* Console output:
The engine starts up noisily...
The engine sputters...
*/
xxxxxxxxxx
const person = {
name: 'Sam',
age: 30,
// using function as a value
greet: function() { console.log('hello') }
}
person.greet(); // hello