I don't understand the return statement for js

Lesson “Return a Value From a Function With Return,” says “You can use a return statement to send a value back out of a function.” Yet I can’t figure out what that is supposed to mean. Could someone explain it in more detail for me?

1 Like

While some functions only perform some task without returning a value back to the calling function, many times you want to pass data to a function and maybe have it calculate a new value based on the data passed. For example, if I wanted to create a function named addTwo Numbers with two parameters (i.e. num1 and num2) and want the function to return the sum of any two numbers passed to the it, then I would need a return statement. See below for a working example.

function addTwo(num1, num2) {
  return num1 + num2; // this returns the sum of num1 and num2
var sum1 = addTwo(5,10); // sum1 gets assigned the returned sum of 5 + 10
console.log(sum1); // displays 15 to the browser's console

var sum2 = addTwo(100, 200); // sum2 gets assigned the returned sum of 100 + 200
console.log(sum2);  // displays 300 to the browser's console

Thanks for taking the time to explain this to me!

Also the return statement is used in some cases to stop the code executing further. For example in node js(server side javascript in case you don t know)
if for some reason you encounter an error you can return back a response to prevent the code going further and trying to send 2 responses for example which would crash your app. Also inside a function the code you write after return it won t be executed. You can also return another function that returns a value and you can grab that value.

1 Like

This is more explicit in some other languages. Take this C/C++ code, for instance:

void hello(){
  printf("Hello World");
bool test(){
  return true;
int main(){
  return 0;

Here, we have three functions. main() returns an integer, test() returns a boolean value, and hello() is void and just prints “Hello World” without returning anything.

1 Like

could you pleas give me an example When exactly we don’t use Return statement?