โšก

Functions

๐ŸŽ‰
๐Ÿ’จ
Functions are like recipes - write once, use many times!

What are Functions?

A function is a reusable block of code that performs a specific task. Instead of writing the same code over and over, you put it in a function and call it when needed.

Functions can take inputs (parameters) and give back outputs (return values).

๐Ÿ’ก
๐Ÿ’จ

Creating Functions

There are two main ways to create functions:

1// Function declaration
2function greet(name) {
3 return "Hello, " + name + "!";
4}
5
6// Arrow function (modern way)
7const greet = (name) => {
8 return "Hello, " + name + "!";
9};
10
11// Arrow function - short form
12const greet = (name) => "Hello, " + name + "!";
๐Ÿค”
๐Ÿ’จ

Parameters and Return

Functions can take parameters (inputs) and return values (outputs):

1// Function with parameters
2function add(a, b) {
3 return a + b; // Return the result
4}
5
6// Calling the function
7const result = add(5, 3);
8console.log(result); // 8
9
10// Multiple parameters
11function introduce(name, age) {
12 return name + " is " + age + " years old";
13}
14
15console.log(introduce("Alice", 25));
16// "Alice is 25 years old"
๐Ÿ’ก
๐Ÿ’จ

Default Parameters

You can set default values for parameters:

1function greet(name = "Guest") {
2 return "Welcome, " + name + "!";
3}
4
5greet("Alice"); // "Welcome, Alice!"
6greet(); // "Welcome, Guest!"
๐Ÿค”
๐Ÿ’จ

Functions with Arrays

Functions work great with array methods:

1const numbers = [1, 2, 3, 4, 5];
2
3// Using arrow functions with map
4const doubled = numbers.map(n => n * 2);
5console.log(doubled); // [2, 4, 6, 8, 10]
6
7// Using arrow functions with filter
8const evens = numbers.filter(n => n % 2 === 0);
9console.log(evens); // [2, 4]
10
11// Custom function with find
12const isGreaterThan3 = n => n > 3;
13const found = numbers.find(isGreaterThan3);
14console.log(found); // 4
๐ŸŽฎ

Try It Yourself!

Build and call functions! Watch how inputs become outputs.

function add(a, b)

+=8

function greet(name)

name:
Returns: "Hello, World!"

Console Output

// Call a function to see the output
1// Your functions
2const add = (a, b) => a + b;
3const greet = (name) => "Hello, " + name + "!";
4
5// Call them!
6add(5, 3); // 8
7greet("World"); // "Hello, World!"

๐Ÿงช Code Lab - Try It Yourself!

๐ŸงชFunctions Lab
Enter RunShift+Enter New line History
๐Ÿ“‹Output

Run some code to see the output here!

๐Ÿ’กTry These Examples