Exercise 14: Function that calculates the total price with tax
Apply functions to calculate the final price of products with tax. A key step in simulating online purchase transactions.
The fundamental purpose is to learn how to work with functions that take an object as a parameter and return calculated values.
Activity
- Create an object called
productothat has the following properties:
-nombrewith the value of any product.
-preciowith the numerical value of the product price.
-
Create an arrow function called
calcularPrecioConImpuestothat takes the objectproductoas a parameter and a second parameter calledimpuesto(representing the tax percentage). -
Within the function, calculate the total price including tax using the formula
precio + (precio * impuesto / 100)4. The function should return the total price including tax. -
Call the function with
productoand a tax of, for example,15and stores the result in a variable calledprecioFinal6. SampleprecioFinalon the console.
Solution
Step 1: Create the index.html file
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Función que calcula el precio total con Impuesto</title>
</head>
<body>
<h1>Ejercicio 14: Función que calcula el precio total con Impuesto</h1>
<p>Los cambios se muestran en consola.</p>
<script src="script.js"></script>
</body>
</html>
Step 2: Write the code in script.js
// Crear el objeto producto
const producto = {
nombre: "Televisor",
precio: 300,
};
// Definir la función flecha para calcular el precio con impuesto
const calcularPrecioConImpuesto = (producto, impuesto) =>
producto.precio + (producto.precio * impuesto) / 100;
// Llamar a la función y guardar el resultado en una variable
let precioFinal = calcularPrecioConImpuesto(producto, 15);
// Mostrar el precio final
console.log("El precio final con impuesto es: $" + precioFinal);
🔎Review the following sections where you will find more information on this topic: