Exercise 11: Function that Returns an Object
Implement a function that returns objects with multiple properties. Improve your understanding of functions and data structures in JavaScript.
The main objective is to learn how to create a function that returns an object and understand how to access the properties of the resulting object.
Activity
-
Create a function called
crearMascotto receive two parameters:nombreandedad. -
Inside the function, create an object called
mascotawith two properties:
-nombrethat takes the value of the parameternombre
-edadthat takes the value of the parameteredad.
- Make the function return the object
mascota4. Call the functioncrearMascotawith the values of your choice and save the result in a variable calledmiMascota5. Displays the object's propertiesmiMascotaon 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 Retorna un Objeto</title>
</head>
<body>
<h1>Ejercicio 11: Función que Retorna un Objeto</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 que crea un objeto mascota
function crearMascota(nombre, edad) {
let mascota = {
nombre: nombre,
edad: edad,
};
return mascota;
}
// Llamar a la función y guardar el resultado en una variable
let miMascota = crearMascota("Firulais", 3);
// Mostrar las propiedades de miMascota en la consola
console.log("Nombre de la mascota: " + miMascota.nombre);
console.log("Edad de la mascota: " + miMascota.edad);
info
🔎Review the following sections where you will find more information on this topic: