Coding for All
Lesson 24: Inputs and Return
Inputs and Return Give a function inputs and get an answer back.
1function add(a, b) {
2 return a + b;
3}
4
5console.log(add(2, 3));
6console.log(add(10, 20));
Terminal
$ node main.js
5
30
Every line, explained
function add(a, b) {
function defines a function: your own named block of code. Defining it does nothing on its own: it waits until somebody calls it by name. This one has two parameters, a and b, values the caller hands in.
return a + b;
return hands a value back to whoever called the function, and the function ends. Calling add(2, 3) is like asking a question and getting 5 as the answer.
}
This } closes the function.
console.log(add(2, 3));
add(2, 3) runs the function with a as 2 and b as 3, and becomes its returned value: 5. Then console.log prints it.
console.log(add(10, 20));
Same function, different inputs, different answer: 30.