Learning Outcome: You will understand how to create and call a function in JavaScript.
A function is a block of code designed to perform a specific task. For example, think of a function as a recipe. Just like a recipe tells you how to make a dish, a function tells the computer what to do. Therefore, understanding how to invoke a function is essential for all beginners.
The following example demonstrates how to define a function and call it:
File: greet.php
function greet() {
console.log('Hello, welcome to JavaScript!');
}
greet(); // Call the function
Hello, welcome to JavaScript!
This code showcases a simple function named greet. The important lines are:
function greet() { ... }: This line defines the function. The code inside the curly braces runs when the function is called.greet();: This line calls the function, which executes the code inside it.Now, try creating your own function! Name it sayGoodbye. When called, it should print “Goodbye! See you again!”. This task will help reinforce what you have learned about creating and calling a function.
function sayGoodbye() {
console.log('Goodbye! See you again!');
}
sayGoodbye(); // Call the function
function keyword.To learn more about the foundations of JavaScript, check out the lesson on What Is JavaScript?. Understanding JavaScript is crucial because it is the language that allows dynamic interaction on websites.
In addition, mastering functions is a step towards working with more complex programming tasks. If you are interested in applying what you have learned, consider the hands-on project from our Practical task: Build Your Student Profile Page.