How do functions work in JavaScript, and what is different about them compared to a plain value?
The core requirement is a function that takes two parameters and returns the result. Everything else is style.
function add(a, b) {
return a + b;
}
console.log(add(2, 3)); // 5
console.log(add(2)); // NaN - the missing argument is not an error
console.log(add(2, 3, 4)); // 5 - extra arguments are ignored
Three behaviours are worth being able to state out loud. A missing argument is not an error in JavaScript. The parameter simply holds the empty value, so adding two of them produces not-a-number rather than throwing an error. Extra arguments are ignored completely. And the return statement ends the function immediately, so any code after it never runs.
For anything beyond a two-line function, add a default so that the missing case is handled explicitly, and think about whether the parameters should be an options object instead. An options object explains itself at the call site, and it lets you add parameters later without breaking the callers.
There is one more habit worth mentioning here. Return the value instead of logging it. A function that returns a result can be tested, reused, and combined with other code. A function that only writes to the console can do none of those things, and mixing the two habits makes code much harder to move later.