A function is a named, reusable block of code that performs a task. Instead of copying the same steps everywhere you need them, you write them once as a function and call it by name whenever you need it.
function greet(name) {
console.log("Hello, " + name + "!");
}
greet("Ada"); // "Hello, Ada!"
greet("Alan"); // "Hello, Alan!"<?php
function greet($name) {
echo "Hello, " . $name . "!\n";
}
greet("Ada"); // "Hello, Ada!"
greet("Alan"); // "Hello, Alan!"def greet(name):
print("Hello, " + name + "!")
greet("Ada") # "Hello, Ada!"
greet("Alan") # "Hello, Alan!"name here is called a parameter — a placeholder for the value the function will receive each time it's called.
A function can hand a value back to whatever called it, using return.
function add(a, b) {
return a + b;
}
let result = add(3, 4);
console.log(result); // 7<?php
function add($a, $b) {
return $a + $b;
}
$result = add(3, 4);
echo $result; // 7def add(a, b):
return a + b
result = add(3, 4)
print(result) # 7Functions make code reusable, easier to test in isolation, and easier to read — a well-named function like calculateTotalPrice() tells you what a block of code does without needing to read every line inside it.