A function is reusable code that performs one clear task. Once steps are placed in a function, calling its name runs them again without copying the whole block.
Defining and calling a function
After function comes the function name. Parameters go inside parentheses and the function body goes inside braces. The actual values supplied by a call are arguments.
function larger(num1, num2) {
if (num1 > num2) {
return num1;
}
return num2;
}
const result = larger(7, 12);
console.log(result); // 12return sends a result back to the calling position and immediately ends that call.
KNOWLEDGE QUIZ
Functions without an explicit result
Some functions only perform an action. They can omit return; reaching the end of the body returns undefined.
function printGreeting(name) {
console.log(`Hello, ${name}!`);
}
printGreeting("Mina");Caller → method → return
Unlock the complete interactive lab, deeper explanations, and curated reference answers.
Calling another function
One function can call another. Execution enters the called function, receives its return value, and then continues at the original calling position.
function square(value) {
return value * value;
}
function distance(x1, y1, x2, y2) {
const dx = x2 - x1;
const dy = y2 - y1;
return Math.sqrt(square(dx) + square(dy));
}
console.log(distance(0, 0, 3, 4)); // 5Nested calls: distance() asks square() twice
Unlock the complete interactive lab, deeper explanations, and curated reference answers.
KNOWLEDGE QUIZ
A JavaScript file executes from the top. You can declare functions and call them where needed; the language does not automatically look for a function named main.
Write a method that returns an absolute difference
Write absoluteDifference(num1, num2) and return the absolute difference.
- Define the method.
- Use if/else to return the non-negative difference.
- Print at least two calls.
Write a prime-checking method
Wrap prime checking in reusable isPrime(n).
- Return false for n <= 1.
- Check factors through sqrt(n).
- Read and report from top-level code.
Calculate the day number within a year
Split the work into isLeap, daysInMonth, and dayOfYear.
- Implement leap-year logic.
- Return each month length.
- Call helpers from dayOfYear and main.