JavaScript · Lesson 6 of 20 · 3 min
Functions: Basics
Your ability to write a clean, reusable function is the first filter in any coding interview.
After this, you'll know how to structure a function that is robust, readable, and easy to test. Interviewers use basic function questions to see if you can isolate logic and handle inputs defensively. Get this right, and you signal that you write maintainable code.
Structure your function with a clear API
A function does one job. It takes defined inputs (parameters), performs a specific task, and provides a single output (a return value). This separation of concerns is the foundation of testable and scalable code.
Think of every function as a small public API. Its signature—the name and parameters—is the contract. The body is the private implementation.
A solid function handles both the happy path and edge cases. Use guard clauses at the top to validate inputs and exit early. This keeps the main logic clean and un-nested.
/**
* Calculates the area of a rectangle.
* @param {number} width - The width of the rectangle. Must be positive.
* @param {number} height - The height of the rectangle. Must be positive.
* @returns {number} The area, or 0 if inputs are invalid.
*/
function calculateRectangleArea(width, height) {
// Guard clause for invalid inputs
if (typeof width !== 'number' || typeof height !== 'number' || width <= 0 || height <= 0) {
// In a real app, you might throw an error. For this example, we return 0.
return 0;
}
// The "happy path" logic
const area = width * height;
return area;
}
const validArea = calculateRectangleArea(10, 5); // 50
const invalidArea = calculateRectangleArea(-10, 5); // 0
This function is predictable. It clearly states what it needs and what it returns. It doesn't fail silently or produce NaN. This is what an interviewer wants to see.
Choose between declarations and expressions deliberately
You can define a function in two primary ways: as a declaration or as an expression.
A function declaration is hoisted. The JavaScript engine moves it to the top of its scope before execution. This means you can call the function before it appears in the code.
// This works because declarations are hoisted
const area = getArea(10, 20);
function getArea(w, h) {
return w * h;
}
A function expression is not hoisted. It's part of an assignment statement, and like any variable, it's only available after the line where it is defined.
// This throws a ReferenceError because getArea is not defined yet
const area = getArea(10, 20);
const getArea = function(w, h) {
return w * h;
};
The trade-off: Hoisting can be convenient, but it can also lead to code that's hard to read, with functions being called far from their definition. Function expressions enforce a more logical, top-down flow where dependencies are defined before they are used.
For utility functions used across a file, declarations are fine. For logic specific to a component or a single block of code, expressions can help keep your code organized and easier to follow. The most important thing is to be consistent within a codebase.
Understand the function's contract
A function's signature is its contract with the rest of your program. The parameters define the inputs it accepts, and the return statement defines the output it produces.
- Parameters are the named variables in the function definition.
- Arguments are the actual values you pass into the function when you call it.
The flow is simple: arguments are passed from the caller, assigned to the function's parameters, used in the function body, and a single value is sent back via return.
The trap: Forgetting to
return. A function that does not have an explicitreturnstatement, or just hasreturn;, will implicitly returnundefined. This is a common source of bugs that can be tricky to track down. If a function is supposed to produce a value, it must end withreturn someValue;.
Always ask yourself: what should this function produce? If the answer is "nothing," it's a procedure (e.g., an event logger). If it's supposed to compute a value, make sure you return it.
Try it
Write a utility function truncate(text, maxLength) that takes a string and a number. If the string's length is less than or equal to maxLength, it should return the original string. Otherwise, it should truncate the string to maxLength and append an ellipsis (...). Ensure your function handles cases where maxLength is 0.
Next: We'll organize our data with Arrays and Objects.
Lock it in — apply this lesson under interview conditions.