How do I loop a specified region of code to compile data in Javascript?

Viewed 53

Newbie here.

So I'm developing a script to calculate how much money an employee makes at their workplace. I've figured out how to prompt the user to find how much they earned on a certain day, but how do I loop this region of code so the script continues asking the questions again to compile the total income into a final monthly value?

Thanks in advance.

const hourlyRate = 10.00
let hoursWorked = parseFloat(prompt("How many hours did you work?"))

console.log("You worked a total of " + hoursWorked + " hours.")

if (hoursWorked == 12) {
  hoursWorked -= 1
} else if (hoursWorked < 12 && hoursWorked >= 6) {
  hoursWorked -= 0.5
}

console.log("You will be paid for " + hoursWorked + " hours of work due to unpaid breaks.")

let incentiveRate = parseFloat(prompt("What was the hourly rate multiplier?"))
let dayPay = hoursWorked * incentiveRate * hourlyRate
console.log("You have earned £" + dayPay + " for your troubles today.")

2 Answers

wrap you code in a function like this:

function loopFunction(){
    //your code
    return dayPay;
}

and than add this

var totalDaysInMonth = 30;
var totalEarned = 0;

for(var i=0;i<totalDaysInMont;i++){
   totalEarned += loopFunction();
}

this solution will ask you 30 times the question and after the loop you have the total amount earned.

show = true;

while(show){
const hourlyRate = 10.00
let hoursWorked = parseFloat(prompt("How many hours did you work?"))

console.log("You worked a total of " + hoursWorked + " hours.")

if (hoursWorked == 12) {
  hoursWorked -= 1
} else if (hoursWorked < 12 && hoursWorked >= 6) {
  hoursWorked -= 0.5
}

console.log("You will be paid for " + hoursWorked + " hours of work due to unpaid breaks.")

let incentiveRate = parseFloat(prompt("What was the hourly rate multiplier?"))
let dayPay = hoursWorked * incentiveRate * hourlyRate
console.log("You have earned £" + dayPay + " for your troubles today.")
let answer = parseFloat(prompt("Do you want do add the hours again? 0 for no, 1 for yes"))
this.show = (answer === 0)? false: true;
}

Related