What Is a Function?
A function is a block of instructions in your code that you can use over and over again. You give the function a name, and when you call that name, the code inside the function will execute. Functions can take inputs (we call these parameters) and can give back an output (called a return value).
Declaring a Function
To create a function, you can use the function keyword. For example, this function prints a greeting:
function sayHello() {
console.log("Hello, Function!");
}
Here, we have:
- Declaration: The keyword function tells JavaScript we are creating a function.
- Name: The function is named sayHello.
- Body: The code inside the curly braces {} is what the function does. In this case, it prints a message.
Calling a Function
Once a function is declared, you can run it (or “call” it) by writing its name followed by parentheses:
sayHello();
This tells JavaScript, “Please run the instructions inside the function called sayHello.”
Functions with Parameters and Return Values
Functions can also accept inputs. For example, here’s a function that adds two numbers:
function addNumbers(a, b) {
return a + b;
}
In this case:
- Parameters: The function takes two inputs, a and b.
- Return Value: The function returns the result of adding a and b.
You can call this function and store its result in a variable:
let sum = addNumbers(3, 4);
console.log(sum); // prints 7
Exercises
Simple Function
- Create a function called sayHello that prints "Hello, Function!" to the console.
- After declaring the function, call it so that the message is printed.
Function with Parameters
- Create a function named addNumbers that takes two parameters.
- The function should return the sum of the two parameters
- .Call the function with the numbers 3 and 5, store the result in a variable called result, and print result using console.log.
Calculating the Area of a Rectangle
- Create a function named calculateArea using the function keyword.
- It should take two parameters: width and height.
- The function should return the product of width and height.
- After declaring the function, call it with the numbers 7 and 3, and print the result using console.log


Ready to become an ethical hacker?
Start today.
As a member of Hakatemia you get unlimited access to Hakatemia modules, exercises and tools, and you get access to the Hakatemia Discord channel where you can ask for help from both instructors and other Hakatemia members.