What is a function in programming?
In short
A function is a named block of code that does one job. You write it once and run it whenever you need it, by calling its name.
Functions stop you repeating yourself. If your program works out a price with tax in five places, you write a function for it once and call it five times. When the tax rate changes, you fix it in one place.
A function can take inputs, called parameters, and give back a result with return. Good functions are short, do one thing and have a name that says what that thing is.
Python
A function with a parameter and a return value
def add_tax(price):
return price * 1.2
print(add_tax(10))
print(add_tax(50))Output
12.0
60.0JavaScript
The same idea in JavaScript
function addTax(price) {
return price * 1.2;
}
console.log(addTax(10));
console.log(addTax(50));Output
12
60Learn it properly
These free lessons teach it step by step, with questions and a program you write yourself.
- Defining Functions and ParametersLearn Python →
- Return Values and DefaultsLearn Python →
- Functions and ParametersLearn JavaScript →
- Defining FunctionsLearn C →
Try your first lesson free
Codiqo teaches coding in five-minute lessons with real code. Free on the web, iPhone and Android.