Understand the idea
A function groups work that can be called with different inputs. Parameters name the inputs; arguments are the values supplied when calling it.
return sends a result back to the caller and stops the function. Logging a value displays it in the console but does not return it. Keep a function focused so that its purpose can be explained in one sentence.
Read the example
This is a JavaScript fragment. Run it in a browser console or an external script. Supply any HTML or data file named in the example first.
function describePhotos(count) {
return count === 1 ? "1 photograph" : `${count} photographs`;
}
const label = describePhotos(3);
console.log(label);A small mistake, explained
What goes wrong
A function without an executed return statement returns undefined. console.log inside the function does not change that.
How to fix it. Return the value needed by the caller, and keep any display or logging step separate.
Try it yourself
Test the function with 0, 1 and 3. Then write a simpler version using if and else instead of the conditional operator.
Further reading
ECMAScript — function definitions
Keep exploring
- JavaScript · Guide
Variables & valuesGive a value a name and understand when it can change.
- JavaScript · Guide
Conditions & comparisonsMake a decision without accidentally changing the value.