Exerpad
Lesson · Chapter: Functions+10 XP for reading

Building Your Own Commands

Functions let you create your own reusable blocks of code, like building your own commands!

Defining a Function

Use the function keyword to create a function:

javascript
function greet() {
console.log("Hello there!");
}

greet();
Output
Press Run to see the output.

Output:

Hello there!

The code inside the braces runs every time you call the function with greet().

Functions with Parameters

Parameters let you pass information to a function:

javascript
function greet(name) {
console.log(`Hello, ${name}!`);
}

greet("Alex");
greet("Sam");
Output
Press Run to see the output.

Output:

Hello, Alex!
Hello, Sam!

Returning Values

Use return to send a value back:

javascript
function double(n) {
return n * 2;
}

let result = double(5);
console.log(result);
Output
Press Run to see the output.

Output:

10

Multiple Parameters

Functions can take more than one parameter:

javascript
function add(a, b) {
return a + b;
}

console.log(add(3, 4));
Output
Press Run to see the output.

Output:

7

Why Use Functions?

Without functions, you'd repeat the same code over and over:

javascript
// Without functions — lots of repeated code
console.log("Hello, Alex!");
console.log("Hello, Sam!");
console.log("Hello, Jordan!");

// With functions — much cleaner!
function greet(name) {
console.log(`Hello, ${name}!`);
}

greet("Alex");
greet("Sam");
greet("Jordan");
Output
Press Run to see the output.

Functions make your code shorter, cleaner, and easier to fix!