In this tutorial, we will learn about function creation. While HTML is not a programming language and doesn't support functions, we'll actually be using JavaScript, a complementary language that works within HTML, to write our functions.
Functions are reusable pieces of code that perform a specific task. By the end of this tutorial, you will understand how to create functions, pass arguments to them, and use their output.
To follow this tutorial, you should already have a basic understanding of HTML and JavaScript syntax.
A function in JavaScript is defined with the function
keyword, followed by a name, followed by parentheses ()
. The code to be executed by the function is placed inside curly brackets {}
.
Here is an example of a function:
function myFunction() {
// function body
// this is where the code goes
}
But just writing a function is not enough. We need to call or invoke the function to run the code it contains. We do this by using the function name followed by parenthesis ()
:
myFunction(); // this will run the code inside myFunction
Let's dive into some examples.
Here, we will create a simple function that greets a user.
function greetUser() {
alert("Hello, User!");
}
greetUser(); // This will show an alert box with the message "Hello, User!"
This function accepts parameters or arguments.
function greet(name) {
alert("Hello, " + name + "!");
}
greet("Alice"); // This will show an alert box with the message "Hello, Alice!"
In this example, name
is a parameter. When we call the greet
function, we pass an argument, in this case, "Alice", which replaces name
inside the function.
In this tutorial, we've covered the basics of creating functions in JavaScript that can be used within an HTML document. We've learned how to define a function, how to call it and how to pass arguments to it.
To continue learning, you might want to look into more complex functionality such as returning values from functions, using anonymous functions, and understanding scope.
Here are some exercises to help you practice:
Solutions:
function addNumbers(num1, num2) {
alert(num1 + num2);
}
addNumbers(5, 7); // This will alert 12
function favoriteColor(name, color) {
alert(name + "'s favorite color is " + color);
}
favoriteColor("Bob", "blue"); // This will alert "Bob's favorite color is blue"
Remember, the key to learning is consistent practice and experimentation. Happy coding!