Answers for "js object methods"

6

object object javascript

person = {
    'name':'john smith'
    'age':41
};

console.log(person);
//this will return [object Object]
//use
console.log(JSON.stringify(person));
//instead
Posted by: Guest on April-20-2020
5

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 
}
Posted by: Guest on November-01-2020
1

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
  }
};
Posted by: Guest on July-06-2021
0

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);
Posted by: Guest on September-06-2021

Code answers related to "Javascript"

Browse Popular Code Answers by Language