Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

146
Views
Cannot access 'usagePrice' before initialization

I have a script that I'm using to calculate the price of a selected field

When i run the function 'calculateTotal()' i get this error "Cannot access 'usagePrice' before initialization".

Here is my code:

// Returns total for step 1
const usagePrice = () => {
    const field = document.querySelector('input[name="usage"]:checked');
    const subField = document.querySelector('input[name="varifocal-lenses"]:checked');

    let price = field.dataset.price;
       

    if (field.value == 'varifocal') {
        
        price = subField.dataset.price;
    }

    console.log('Usage price: ' + price);
    return price;
}

// Adds all totals together
const calculateTotal = () => {
    const usagePrice = usagePrice();
    const prescriptionPrice = prescriptionPrice();
    const lensPackagePrice = lensPackagePrice();
    const lensTypePrice = lensTypePrice();

    const total = usagePrice + prescriptionPrice + lensPackagePrice + lensTypePrice;

    return total;
}


console.log(calculateTotal());

Can anyone explain whats going wrong? Thank you in advance.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Solved now.

The issue was i was naming the variables in calculateTotal() the same as the functions declared before.

// Adds all totals together
const calculateTotal = () => {
    const usagePriceValue = usagePrice();
    const prescriptionPriceValue = prescriptionPrice();
    const lensPackagePriceValue = lensPackagePrice();
    const lensTypePriceValue = lensTypePrice();

    const total = usagePriceValue + prescriptionPriceValue + lensPackagePriceValue + lensTypePriceValue;

    return total;
}
about 4 years ago · Juan Pablo Isaza Report

0

Just like the name of the function calculateTotal starts with a verb ("calculate"), it is very common to name functions with a verb at the beginning. In your case, it makes sense to start function names with the "get" verb:

const usagePrice = getUsagePrice();
const prescriptionPrice = getPrescriptionPrice();
const lensPackagePrice = getLensPackagePrice();
const lensTypePrice = getLensTypePrice();

const total = usagePrice + prescriptionPrice + lensPackagePrice + lensTypePrice;

return total;
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!