mobile theme mode icon
theme mode light icon theme mode dark icon
Random Question Random
speech play
speech pause
speech stop

Calculate Total with Discount in JavaScript

In the code you provided, there are a few issues that could be considered "improper" or suboptimal:

1. Missing `return` statement: The function `calculate_total()` does not return anything, which means it will return `undefined` by default. You should add a `return` statement at the end of the function to specify what value it returns.
2. Unused variables: The variable `discount` is assigned a value but never used. You should remove the unused code to avoid confusion and make the code more readable.
3. Magic numbers: The code uses hardcoded values like `10` and `50` without any explanation or documentation. It would be better to use named constants or variables to make the code more readable and maintainable.
4. Complexity: The code has multiple nested `if` statements, which can make it difficult to understand and debug. You could simplify the code by consolidating some of the conditions into a single `if` statement or using a `switch` statement.
5. Lack of error handling: The code does not handle errors if the user enters an invalid value for the discount percentage. You should add error handling to ensure that the function handles unexpected input gracefully.

Here's an updated version of the code that addresses these issues:
```javascript
function calculate_total(price, discount) {
const DISCOUNT_PERCENTAGE = 0.1; // define a constant for the discount percentage

if (discount === undefined || discount < 0 || discount > 100) {
throw new Error('Invalid discount value');
}

const total = price * (1 - (DISCOUNT_PERCENTAGE * discount));

return total;
}
```

Knowway.org uses cookies to provide you with a better service. By using Knowway.org, you consent to our use of cookies. For detailed information, you can review our Cookie Policy. close-policy