object object javascript
person = {
'name':'john smith'
'age':41
};
console.log(person);
//this will return [object Object]
//use
console.log(JSON.stringify(person));
//instead
object object javascript
person = {
'name':'john smith'
'age':41
};
console.log(person);
//this will return [object Object]
//use
console.log(JSON.stringify(person));
//instead
object methods in javascript
/// 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
}
define methods of objects in javascript
objectName.methodname = functionName;
var myObj = {
myMethod: function(params) {
// ...do something
}
// OR THIS WORKS TOO
myOtherMethod(params) {
// ...do something else
}
};
js object methods
// create 2 objects for Mark and John that calculate their BMI's
// BMI = mass / height ** 2 || mass / (height * height);
// mass: kg
// john object
const johnObj = {
firstName: "John",
lastName: "Smith",
mass: 92,
height: 1.95,
calcBMI: function () {
// learn more about 'this'
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this
this.bmi = Number((this.mass / this.height ** 2).toFixed(2));
return this.bmi;
},
};
// mark object
const markObj = {
firstName: "Mark",
lastName: "Miller",
mass: 78,
height: 1.69,
calcBMI: function () {
this.bmi = Number((this.mass / this.height ** 2).toFixed(2));
return this.bmi;
},
};
// store the ternary results in a variable
const results =
johnObj.calcBMI() > markObj.calcBMI()
? `${johnObj.firstName} has a higher BMI of ${johnObj.calcBMI()} than ${
markObj.firstName
}'s BMI of ${markObj.calcBMI()}!`
: `${markObj.firstName} has a higher BMI of ${markObj.calcBMI()} than ${
johnObj.firstName
}'s BMI of ${johnObj.calcBMI()}!`;
// display the results on the console
console.log(results);
Copyright © 2021 Codeinu
Forgot your account's password or having trouble logging into your Account? Don't worry, we'll help you to get back your account. Enter your email address and we'll send you a recovery link to reset your password. If you are experiencing problems resetting your password contact us