In this lesson, we’ll explore one of the most important concepts in JavaScript programming: functions. Functions allow you to create reusable blocks of code that can be executed on demand. Understanding how to create and use functions is vital for writing efficient and maintainable JavaScript code.
Table of Contents
Declaring Functions
A function is a block of code designed to perform a specific task. Functions in JavaScript can be declared using the function
keyword, followed by the function name, a list of parameters enclosed in parentheses, and a set of curly braces containing the function’s code.
Here’s the basic syntax for declaring a function:
function functionName(parameters) {
// code to be executed
}
For example, let’s create a simple function that adds two numbers together:
function add(a, b) {
return a + b;
}
In this example, add
is the function name, a
and b
are the parameters, and the return
statement specifies the value to be returned by the function.
Invoking Functions
To call or invoke a function, you simply use the function name followed by the arguments enclosed in parentheses. The arguments are the actual values you pass to the function when calling it. The number of arguments should match the number of parameters defined in the function.
Here’s an example of how to call the add
function we declared earlier:
let sum = add(3, 4);
console.log(sum); // Output: 7
In this example, we call the add
function with the arguments 3
and 4
. The function returns the sum, which is then assigned to the variable sum
. Finally, we log the result to the console.
Actionable Work:
To practice declaring and invoking functions, create a new HTML file and add a <script>
element inside the <body>
section. Write JavaScript code inside the <script>
element to declare and call several functions.
- Create a function called
greet
that takes a name as a parameter and returns a greeting string, such as “Hello, [name]!”. - Invoke the
greet
function with your name as an argument and log the result to the console. - Create a function called
multiply
that takes two numbers as parameters and returns their product. - Invoke the
multiply
function with two numbers of your choice as arguments and log the result to the console.
In the next part of Lesson 3, we’ll learn about parameters, arguments, and variable scope in JavaScript, which are essential for controlling the behavior of functions and managing data in your code.