Skip to main content

Exercise 4: Calculating Age with JavaScript

This tutorial teaches you how to calculate a user's age from their birth year using JavaScript. Ideal for forms or interactive applications.

The main goal is to practice declaring numeric variables and performing basic operations in JavaScript.

Activity

  1. Declare a variable called currentYear and assign it the current year.

  2. Declare another variable called birthYear and assign it the year you were born.

  3. Calculate your age by subtracting currentYear from birthYear and store the result in a new variable called age.

  4. Display the age 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>Calculando la Edad</title>
</head>
<body>
<h1>Ejercicio 4: Calculando la Edad</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
// Declaración de variables
let añoActual = 2024;
let añoNacimiento = 2000;

// Cálculo de la edad
let edad = añoActual - añoNacimiento;

// Mostrar la edad en la consola
console.log("Tu edad es: " + edad + " años.");
info

🔎Check the sectionConcepts about variables in JavaScriptwhere you will find more information on this topic.