What you'll learn
Functions name a piece of behavior so you can understand it, test it, and reuse it. Good functions are the main building blocks of maintainable JavaScript.
Declarations and expressions
function greet(name) {
return `Hello, ${name}!`;
}
const shout = function (message) {
return message.toUpperCase();
};
console.log(greet("Rami"));
console.log(shout("keep going"));A function declaration has a name and is available throughout its scope. A function expression creates a function value and assigns it to a binding. Functions are values: they can be stored, passed, and returned.
Parameters, arguments, and defaults
A parameter is the name in the definition; an argument is the value supplied at a call site.
function priceWithTax(price, rate = 0.11) {
return price + price * rate;
}
console.log(priceWithTax(100));
console.log(priceWithTax(100, 0.2));Note
undefined. A default parameter runs when the argument is missing or explicitly undefined, but not when it is null.Return values and early returns
return sends a value to the caller and ends that function call. Without a return statement, a function returns undefined.
function percentage(part, whole) {
if (whole === 0) return null;
return (part / whole) * 100;
}
console.log(percentage(3, 4));
console.log(percentage(1, 0));Arrow functions
const square = number => number ** 2;
const describeScore = (name, score) => {
const status = score >= 70 ? "passed" : "keep practicing";
return `${name}: ${status}`;
};
console.log(square(6));
console.log(describeScore("Dana", 82));| Form | Best fit |
|---|---|
| Function declaration | Named reusable behavior and clear stack traces |
| Arrow function | Short callbacks and lexical this |
| Function expression | A function selected or configured at runtime |
Arrows are not shorter syntax for every function
this or arguments and cannot be constructors. Those distinctions matter in Phase 2.Rest parameters
A rest parameter gathers any remaining arguments into a real array. It must be the final parameter.
function average(...numbers) {
if (numbers.length === 0) return 0;
let total = 0;
for (const number of numbers) total += number;
return total / numbers.length;
}
console.log(average(10, 20, 30));Designing useful functions
- Give functions verb-based names such as
calculateTotalorformatName. - Make each function responsible for one coherent job.
- Prefer returning a value to printing inside reusable logic.
- Avoid changing data outside the function unless mutation is its explicit purpose.
- Validate at boundaries and keep the successful path easy to follow.
Pure functions are easy to trust
Mini-project: calculator
function calculate(left, operator, right) {
if (!Number.isFinite(left) || !Number.isFinite(right)) return "Invalid number";
switch (operator) {
case "+": return left + right;
case "-": return left - right;
case "*": return left * right;
case "/": return right === 0 ? "Cannot divide by zero" : left / right;
default: return "Unknown operator";
}
}
console.log(calculate(12, "*", 4));
console.log(calculate(10, "/", 0));Recap & quick check
Key takeaways
- Function declarations, expressions, and arrows all create callable values.
- Parameters receive arguments; defaults handle missing or undefined arguments.
- return ends the call and supplies its result.
- Rest parameters collect extra arguments into an array.
- Small, focused, value-returning functions are easier to combine and test.
Quick check
1. What does a function return when it has no return statement?
2. What does ...numbers create in a parameter list?
3. Which arrow has an implicit return?
4. What makes a function pure?