Exercise 12: Function to Calculate the Area of a Rectangle
Master arrow functions by applying them to area calculations. This tutorial combines basic geometry and modern JavaScript syntax.
The main goal is to learn how to create and use arrow functions and how to return values from a function.
Activity
- Create an arrow function called
calcularAreaRectangulothat takes two parameters:baseandaltura2. The function should return the area of the rectangle using the formulabase * altura3. Call the function with specific values for the base and height, and store the result in a variable calledarea4. Display the result in 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 Flecha para Calcular el Área de un Rectángulo</title>
</head>
<body>
<h1>Ejercicio 12: Función Flecha para Calcular el Área de un Rectángulo</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
// Definir la función flecha
const calcularAreaRectangulo = (base, altura) => base * altura;
// Llamar a la función y guardar el resultado en una variable
let area = calcularAreaRectangulo(5, 10);
// Mostrar el resultado
console.log("El área del rectángulo es: " + area);
info
🔎Check the sectionFunctions in JavaScript: A Beginner's Guide with Exampleswhere you will find more information on this topic.