2

Suppose consider the following example:

1st:

projectController.getProjectById = function(req,res){

            return (res.status(200).send("Hey"));

}

2nd:

projectController.getProjectById = function(req,res){

                res.status(200).send("Hey");

    }

Look closely in both of my snippet, in 1st snippet I have written return (res.status(200).send("Hey")); and in 2nd snippet I have written res.status(200).send("Hey");.

My question is that if we don't write the return(...) in res.send() then also it will send the data to client side . Then what is meaning of wrapping res.send() inside return(...) .

I have searched in internet but remains unsatisfied with answer, can anyone provide the explanation of my question.

halfer
  • 19,824
  • 17
  • 99
  • 186
Pushprajsinh Chudasama
  • 7,772
  • 4
  • 20
  • 43
  • Adding the `return` statement allows for that instance of what the `send` method returns (In this case, the `Response` object) to be passed to the caller of the function such that it can be reused again later on. You don't have to return it if you're not using the return value. – Edric Sep 19 '19 at 10:41
  • Once the headers are send , it cannot be reused anywhere . @Edric . If i misunderstood you , please give a some more lines of explanation . – Pushprajsinh Chudasama Sep 19 '19 at 10:44
  • What I meant is that in JavaScript, you can add the return keyword to a function, which returns the value that you've specified. You can then optionally pass on this value somewhere or not use it. (What I meant by the `send` method is that it's a method that does something and returns the same instance: https://expressjs.com/en/api.html#res) – Edric Sep 19 '19 at 10:45

2 Answers2

4

The return keyword returns from your function, thus ending its execution. This means that any lines of code after it will not be executed.

Also once you used return keyword code executer/compiler doesn't need to care about next line of codes

For more info refer to this SO post

jitender
  • 10,238
  • 1
  • 18
  • 44
1

To add onto jitender's answer, because return terminates execution, return res.send() can be used to clean up your code when the response is conditional.

For example, let's say you're logging in a user...

if (!user) {
  res.status(400).send('User not found')
} else if (user.disabled) {
  res.status(400).send('User is disabled')
} else {
  // ...check password...

  if (passwordMatch) {
    res.send('Here is your token...')
  } else {
    res.status(400).send('Password did not match')
  }
}

Can be cleaned up like so...

if (!user) {
  return res.status(400).send('User not found')
}

if (user.disabled) {
  return res.status(400).send('User is disabled')
}

// ...check password...

if (passwordMatch) {
  return res.send('Here is your token')
}

res.status(400).send('Password did not match')

In the end, it's a stylistic choice whether you want to use return or if-else blocks.

akritskiy
  • 71
  • 1
  • 4