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.
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;
}
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;