A function is a container for a few lines of code that perform a specific task.
Functions allow us to organize our code a lot better by breaking the code into smaller, more manageable chunks that are doing specific things.
Here's how a function definition looks like in JavaScript:
function functionName() {
// function body (where all the instructions are written)
}
There are two main components of a function:
1. The function header:
It consists of:
function
keyword which tells JavaScript that we are about to define a functionfunctionName
is the function's name, a unique identifier we use to refer to the function()
). We'll learn more about their use in next lessons2. The function body:
This is the code that JavaScript executes whenever the function is called.
It consists of one or more JavaScript statements placed inside curly brackets {}
(where we have our JavaScript comment).
Here's an example of a function:
function sayHello() {
console.log("Hello World");
}
Notice that we indented (added one tab before) our console.log("Hello World");
.
Indentation is not mandatory like in Python, but we use it to make our code easier to read.
Calling a function
If you copy paste the code we've written above in an editor and run it, you'll notice that nothing is being printed to the console.
That's because a function declaration alone does not ask the code inside the function body to run, it just declares the existence of the function.
The code inside a function body runs, or executes, only when the function is called.
You can call or invoke a function by typing its name followed by parentheses, like this:
// Function declaration:
function sayHello() {
console.log("Hello World");
}
// Function call:
sayHello(); // Output: Hello World
All of the code inside the function body will be executed every time the function is called.
In our example, each time the function is called it will print out the message Hello World
on the dev console.
We can call a function as many times as it is needed.
Assignment
Follow the Coding Tutorial and let's write some functions.
Hint
Look at the examples above if you get stuck.
Functions are fundamental building blocks in JavaScript. They allow us to encapsulate code into reusable blocks, making our programs more modular and easier to maintain. Functions are essential in any programming language, and mastering them is crucial for writing efficient and clean code.
Functions are particularly useful in scenarios where you need to perform the same task multiple times, such as validating user input, performing calculations, or manipulating data.
Before diving into more complex aspects of functions, it's important to understand their basic structure and usage. A function in JavaScript is defined using the function
keyword, followed by a name, parentheses, and a block of code enclosed in curly braces.
Here's a simple example:
function greet() {
console.log("Hello, World!");
}
In this example, greet
is the function name, and console.log("Hello, World!");
is the function body that gets executed when the function is called.
Let's break down the key concepts and techniques involved in using functions:
function
keyword, the function name, and the function body.Here's an example with parameters and arguments:
function greet(name) {
console.log("Hello, " + name + "!");
}
greet("Alice"); // Output: Hello, Alice!
greet("Bob"); // Output: Hello, Bob!
Let's explore some examples to see how functions can be used in different contexts:
// Example 1: Function to add two numbers
function add(a, b) {
return a + b;
}
console.log(add(3, 4)); // Output: 7
// Example 2: Function to check if a number is even
function isEven(number) {
return number % 2 === 0;
}
console.log(isEven(10)); // Output: true
console.log(isEven(7)); // Output: false
In these examples, we have functions that perform specific tasks: adding two numbers and checking if a number is even.
When working with functions, it's important to avoid common mistakes and follow best practices:
Once you're comfortable with basic functions, you can explore advanced techniques such as:
Here's an example of an arrow function:
const multiply = (a, b) => a * b;
console.log(multiply(2, 3)); // Output: 6
Let's implement a function that calculates the factorial of a number:
// Function to calculate factorial
function factorial(n) {
if (n === 0) {
return 1;
}
return n * factorial(n - 1);
}
console.log(factorial(5)); // Output: 120
In this example, the factorial
function uses recursion to calculate the factorial of a number.
When working with functions, it's important to test and debug your code:
console.log
: Print values to the console to check if your function is working as expected.Here's an example of a simple test case:
function testAdd() {
console.assert(add(2, 3) === 5, "Test Case 1 Failed");
console.assert(add(-1, 1) === 0, "Test Case 2 Failed");
}
testAdd();
When solving problems with functions, consider the following strategies:
Functions are a powerful tool in JavaScript that allow you to write modular, reusable, and maintainable code. By mastering functions, you'll be able to tackle more complex problems and write cleaner code. Keep practicing and exploring different ways to use functions in your projects.
For further reading and practice, check out the following resources: