Function can return values
In CodeCraft, functions are mostly used to perform actions such as building blocks. But functions can also be used to get numeric results for math calculations. Functions can return values. It's a very basic aspect of function definition.
A function can accept input values, as well as returning a value to the code that calls this function. Here is an example:
function square(x) {
return x**2;
}
The directive return can be in any place of the function. When the execution reaches it, the function stops, and the value is returned to the calling code, which can use the value such as feed it to console.log()
:
console.log( square(3) ); // 9
Or assign to a new variable result
:
let result = square(5);
console.log( result); // 25
Or to
Use square(x)
to write another function:
function sum_of_square(a,b) {
sum = square(a) + square(b);
return sum;
}
Now it's easy to calculate (3*3 + 4*4)
console.log( sum_of_square(3, 4) ); // 25
console result)
Note about return statement
When the execution reaches return
, the function stops. Any value provided to the return
statement is passed back to your calling code;
Never add a newline between return and the value;
If a function does not have a return
statement, or it's just an empty return
without any value, then it returns the value undefined
.