This code defines a function named sum. We can then call this function sum(1, 3) which returns 4. And call it even more with other values sum(2, 7) which returns 9.
return value
In JavaScript, we must return a value from within a function. If nothing is returned, the function returns undefined
In addition, the return keyword exits the function. This means any code written after a return won’t be executed.
function sum(x, y) { return x + y; // exits function with a value console.log("Hello World"); // code never executed}
Parameters vs Arguments
In the above function, (x, y) are parameters of the function. It means they are variables created within a function definition.
When we call this function, (x, y) can be assign those variables any data/values: we call those arguments.
function sum(x, y) { //(x, y) are parameters of the sum function return x + y;}sum(1, 2) // 1 and 2 are arguments, where x = 1, y = 2
If we call a function with parameters, without arguments, the function will return undefined.
function sum(x, y) { return x + y;}sum() // return undefined
TLDR: Parameters are the named inputs defined in the function. Arguments are the actual values passed when calling it.
// function declaration — hoisted, can be called before it's definedfunction makeColor(h, s, l) { return `hsl(${h}, ${s}%, ${l}%)`}// arrow function — shorter syntax, common in modern JSconst makeColor = (h, s, l) => `hsl(${h}, ${s}%, ${l}%)`const color = makeColor(247, 90, 65) // "hsl(247, 90%, 65%)"
Parameters in Depth & Error Handling
Default parameters kick in when an argument is omitted. Rest (...name) collects remaining arguments. try/catch handles errors without crashing.
Arrow functions always start with parameters, followed by => then with the function body {...}.
//basic functionfunction sum(a, b) { return a + b;}// can also be written asconst sum = function(a, b) { // definition of sum variable // sum is assigned a function with two parameters return a + b;}// arrow functionconst sum = (a, b) => { // function is removed // an arrow is added between parameters and curly brackets return a + b;}
Implicit return
When forgetting to write return in a function, it returns an implicite undefined. It means it is infered but not specifically expressed.
For example:
const sum = (a, b) => { a + b; // return is missing}sum(1, 3); // undefined
With arrow functions, we can implicitely return based on specific conditions:
The function body can only have one expression (no curly brackets)
return keyword must be removed
// This works (implicit return)const sum = (a, b) => a + b;sum(1, 3); // 4
Warning
Only use implicit return when the function body is short and sits on one line. Never sacrifice readability and code clarity to use certain functionalities.