Exerpad
🔥 1
10 XP
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!

Where you'll use this
console.log, prompt, Math.floor — every command you've used, someone defined. Functions are how you invent your own.

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!

Did you know?
Right now, this very page is running dozens of JavaScript functions to show you this text — the browser you're using is one of the biggest JavaScript programs ever written.

Check yourself

Pause & predict — what will this print?
function shout() {
  console.log("YO!");
}