Exercise 9: Creating a Simple Function with JavaScript
Discover how to declare and use basic functions in JavaScript to improve code organization and reuse.
The main goal is to learn how to define and call a basic function in JavaScript.
Activity
-
Create a function called
saludarthat takes a parameter callednombre2. Within the function, display a message in the console that says "Hello, [name]!" (replace[nombre]with the parameter value). -
Call the function
saludarand pass your name as an argument.
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>Creando una Función Sencilla</title>
</head>
<body>
<h1>Ejercicio 9: Creando una Función Sencilla</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
function saludar(nombre) {
console.log("Hola, " + nombre + "!");
}
// Llamar a la función con un argumento
saludar("Carlos");
info
🔎Check the sectionFunctions in JavaScript: A Beginner's Guide with Exampleswhere you will find more information on this topic.