JavaScript Functions
Functions are reusable blocks of code. Define once, call anywhere.
Declaring a function
A function declaration names a block you can run later.
function greet(name) {
console.log("Hello, " + name);
}
greet("Ada");
greet("Grace");
Parameters and arguments
Parameters are the inputs a function expects. Arguments are the values you pass in.
function add(a, b) {
return a + b;
}
const total = add(3, 4);
console.log(total);
Return values
return sends a value back to the caller. Without it, a function returns undefined.
function square(n) {
return n * n;
}
console.log(square(5));
Arrow functions
Arrow functions are a shorter syntax, common in modern JavaScript.
const double = (n) => n * 2;
console.log(double(21));