๐
๐จ
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 declaration2function greet(name) {3 return "Hello, " + name + "!";4}56// Arrow function (modern way)7const greet = (name) => {8 return "Hello, " + name + "!";9};1011// Arrow function - short form12const greet = (name) => "Hello, " + name + "!";
๐ค
๐จ
Parameters and Return
Functions can take parameters (inputs) and return values (outputs):
1// Function with parameters2function add(a, b) {3 return a + b; // Return the result4}56// Calling the function7const result = add(5, 3);8console.log(result); // 8910// Multiple parameters11function introduce(name, age) {12 return name + " is " + age + " years old";13}1415console.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}45greet("Alice"); // "Welcome, Alice!"6greet(); // "Welcome, Guest!"
๐ค
๐จ
Functions with Arrays
Functions work great with array methods:
1const numbers = [1, 2, 3, 4, 5];23// Using arrow functions with map4const doubled = numbers.map(n => n * 2);5console.log(doubled); // [2, 4, 6, 8, 10]67// Using arrow functions with filter8const evens = numbers.filter(n => n % 2 === 0);9console.log(evens); // [2, 4]1011// Custom function with find12const 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 functions2const add = (a, b) => a + b;3const greet = (name) => "Hello, " + name + "!";45// Call them!6add(5, 3); // 87greet("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