-1

let aboutMark = {
  firstName: "Mark",
  lastName: "Miller",
  height: 1.69,
  weight: 78,
  bmiCalculator: function(){
    this.markBMI = (this.weight / (this.height * this.height)) 
    return  this.markBMI
  }
};
aboutMark.bmiCalculator()
console.log(aboutMark);

What i want to do here is inside aboutMark object i want to add an property and i want the values to be equal to firstName + lastName. How do we do it.

2
  • btw, why a property which reflects the first name? why not take an independent propery, like bmi? Commented Oct 16, 2022 at 11:27
  • You can use a getter Commented Oct 16, 2022 at 11:31

1 Answer 1

0

You could create a value after the object was made.

aboutMark['fullName'] = aboutMark.firstName + " " + aboutMark.lastName;

Or make a dynamic function and call it using console.log(aboutMark.fullName())

let aboutMark = {
    firstName: "Mark",
    lastName: "Miller",
    height: 1.69,
    weight: 78,
    bmiCalculator: function(){
        this.markBMI = (this.weight / (this.height * this.height))
        return  this.markBMI
    },
    fullName: function(){
        return this.firstName + " " + this.lastName
    }
};

You can also use a getter, Thanks @Nick Parsons

let aboutMark = {
    firstName: "Mark",
    lastName: "Miller",
    height: 1.69,
    weight: 78,
    bmiCalculator: function(){
        this.markBMI = (this.weight / (this.height * this.height))
        return  this.markBMI
    },
    get fullName(){
        return this.firstName + " " + this.lastName
    }
};
Sign up to request clarification or add additional context in comments.

4 Comments

The second option won't work because this inside of the IIFE will be the global object (window in nonstrict browser code). You're better off using a getter.
Tested it in Node.js seems to be returning the correct output @NickParsons
@SamHoque I tested in stackoverflow code snippet,and it won't work
Also tested it in nodejs, the second option doesn't work there either, unless you populate the global scope with firstName and lastName variables.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.