JavaScript Functions
A function is a block of code designed to perform a specific task. It is executed when it is called (invoked). Functions make code reusable and maintainable.
Defining a Function
Function Declaration
// Define the function
function greet(name) {
return "Hello, " + name + "!";
}
// Call (invoke) it
console.log(greet("Alice"));
console.log(greet("Bob"));Parameters and Arguments
Parameters are the names listed in the function definition. Arguments are the values passed when calling the function.
Parameters and Arguments
function multiply(a, b) { // a, b are parameters
return a * b;
}
console.log(multiply(3, 4)); // 3 and 4 are arguments → 12
console.log(multiply(10, 5)); // → 50Default Parameters
Default Parameter Values
function power(base, exponent = 2) {
return base ** exponent;
}
console.log(power(3)); // 9 (exponent defaults to 2)
console.log(power(3, 3)); // 27 (exponent is 3)The return Statement
The return statement exits the function and sends a value back to the caller. Execution stops at return.
Return Values
function isEven(n) {
return n % 2 === 0;
}
console.log(isEven(4)); // true
console.log(isEven(7)); // falseFunction Expressions
A function can be stored in a variable. Unlike declarations, function expressions are NOT hoisted.
Function Expression
const square = function(x) {
return x * x;
};
console.log(square(5)); // 25
console.log(square(9)); // 81Why Use Functions?
| Benefit | Description |
|---|---|
| Reusability | Write once, call many times |
| Readability | Named blocks clarify intent |
| Testability | Isolate logic for easier testing |
| Maintainability | Fix in one place, fixed everywhere |
DRY — Don't Repeat Yourself
function area(width, height) {
return width * height;
}
console.log(area(5, 8)); // 40
console.log(area(10, 3)); // 30
console.log(area(7, 6)); // 42📝 Note: Function declarations are hoisted — you can call them before they appear in the code. Function expressions are NOT hoisted.
Exercise:
Which keyword is used to define a function in JavaScript?