What is a Function?
Function: A function is a self-contained block of code designed to perform a specific task. It can accept inputs (called parameters) and produce an output (called a return value).
Functions are one of the most fundamental building blocks in programming. Instead of writing the same code repeatedly, you write it once inside a function and call that function whenever you need it.
A function typically has three key components:
- Function Name , a descriptive identifier that reflects its purpose (e.g.,
calculateArea,getAverage) - Parameters , the inputs the function receives when it is called (there may be zero or more)
- Return Value , the output the function sends back to the caller (some functions return nothing)
Exam Tip
Follow the single responsibility principle: each function should do one thing and do it well. This makes functions easier to read, test, and reuse across your programs.