JavaScriptbeginner 8 min
Wrap code in a named, reusable function with parameters and a return value.
How to define a function, call it, pass values in with parameters and get a result out with return.
Functions let you name a piece of work and reuse it. They are the main way programs stay organised instead of becoming a long wall of code.
A function is a named recipe. You define it once, then call it whenever you need it.
name is a parameter: a placeholder for a value the caller will provide."Asha", is an argument.return sends a result back and ends the function.A function that does not return gives back undefined.
The short arrow function form is common in modern code:
add is defined with two parameters. Nothing runs yet.add(2, 3) calls it: a is 2, b is 3, and return a + b sends back 5. That value is stored in total.double(add(2, 3)) runs the inner call first (5) and then doubles it to 10.describe(20) takes the first return, so it prints adult. The function ends right there.describe(12) skips the if and reaches return "minor".Write a function square(n) that returns n * n, then print square(7).
return. The function runs but gives back undefined.add is the function itself, add(2, 3) runs it.return. It never runs.function name(params) { return value; } defines reusable code.return sends a result out.You finished the JavaScript beginner section. Next: arrays, objects and the DOM.
function greet(name) {
return "Hello, " + name + "!";
}const double = (n) => n * 2;function add(a, b) {
return a + b;
}
const total = add(2, 3);
console.log(total); // 5
const double = (n) => n * 2;
console.log(double(add(2, 3))); // 10
function describe(age) {
if (age >= 18) {
return "adult";
}
return "minor";
}
console.log(describe(20)); // adult
console.log(describe(12)); // minor