Functions - Reusable Blocks of Code
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:
1function sayHello() {
2 console.log("Hello, Function!");
3}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:
1sayHello();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:
1function addNumbers(a, b) {
2 return a + b;
3}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:
1let sum = addNumbers(3, 4);
2console.log(sum); // prints 7Exercises
Learn to hack — start here
Hundreds of interactive courses, virtual labs and CTF challenges in your browser. Start a free trial — no card required.