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?

  • It's impossible. – tkausl Aug 19 '21 at 05:07
  • Why do you return `sellsBonus` in the function `finalSalary`? If you want to get `totalSalary`, return `totalSalary`. – Ricky Mo Aug 19 '21 at 05:08
  • Is there any way to get the variable? –  Aug 19 '21 at 05: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);` – Ricky Mo Aug 19 '21 at 05:10

0 Answers0