55 Mins beginner
7. Functions
Functions
Functions
A function is a reusable block of code designed to perform a specific task. You define it once, and "call" it as many times as you need.
๐๏ธ Function Declarations
The standard way to create a function. It takes inputs (parameters) and sends data back out using the return keyword.
def calculateTax(amount) {
const tax = amount * 0.15;
return amount + tax;
}
const total = calculateTax(100);
console.log("Total with tax:", total);
OutputTotal with tax: 115
๐ฆ Function Expressions
In JavaScript, functions are "first-class citizens." This means you can assign a function directly to a variable.
const greet = function(name) {
return "Welcome, " + name;
};
console.log(greet("Alice"));
OutputWelcome, Alice
๐น Arrow Functions (ES6)
Introduced in ES6, arrow functions provide a shorter, cleaner syntax. If the function is a single line of math, you can even omit the return keyword and the curly braces!
// Standard arrow function
const multiply = (a, b) => {
return a * b;
};
// Implicit return (ultra-clean syntax)
const square = x => x * x;
console.log(multiply(5, 4));
console.log(square(6));
Output20
36
36
Knowledge Check
Ready to test your understanding of 7. Functions?