Skip to main content

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

  1. Create an object calledproductothat has the following properties:

-nombrewith the value of any product.

-preciowith the numerical value of the product price.

  1. Create an arrow function calledcalcularPrecioConImpuestothat takes the objectproductoas a parameter and a second parameter calledimpuesto(representing the tax percentage).

  2. Within the function, calculate the total price including tax using the formulaprecio + (precio * impuesto / 100)4. The function should return the total price including tax.

  3. Call the function withproductoand a tax of, for example,15and stores the result in a variable calledprecioFinal6. SampleprecioFinalon the console.

Solution

Step 1: Create the index.html file

HTML
<!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

JavaScript
// 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);
info

🔎Review the following sections where you will find more information on this topic: