0

I am a beginner and I am learning JavaScript. I am tying to get a private variable of a function which is within a object. How can I call the private variable totalSalary outside the object and get the value of the variable?

Here is my JavaScript code:

const info = {
    firstName: "Richard",
    lastName: "Benson",
    mainSalary: 250000,
    monthlySell: 1000000,

    finalSalary: function(bonusParcent) {
        const sellsBonus = this.monthlySell * bonusParcent;
        const totalSalary = this.mainSalary + sellsBonus; // This variable
        return sellsBonus;
    }
}

console.log("Full name: " + info.firstName + " " + info.lastName);
console.log("Main salary: $", info.mainSalary);
console.log("Sells bonus: $", info.finalSalary(0.05));
console.log("Total salary: $", info.finalSalary().totalSalary); // Want to call form here

How can I call the totalSalary the variable?

4
  • It's impossible. Commented Aug 19, 2021 at 5:07
  • Why do you return sellsBonus in the function finalSalary? If you want to get totalSalary, return totalSalary. Commented Aug 19, 2021 at 5:08
  • Is there any way to get the variable? Commented Aug 19, 2021 at 5:09
  • 1
    You have to return the variable. If you want to return two variables, you can return an object. e.g. return {sellsBonus,totalSalary}; You can then get both variables back by let {sellsBonus,totalSalaru} = info.finalSalary(0.05); Commented Aug 19, 2021 at 5:10

0