How do you use return in a Javascript function and what is its purpose?

Asked by: SarahM
Viewed: 56
Answers: 1
  • 0


I don’t really understand the use of the return statement. Can anyone tell me what and how is it used for?


Answer by: jenniryan

Answered on: 21 Jul 2023

  • 0

In a JavaScript function, the return statement is used to specify the value that is returned to the function caller when the function is finished executing.

For example:

function add(x, y) {
return x + y;

let result = add(2, 3);
console.log(result); // Output: 5

In the above example, the add function takes in two parameters, x and y, and returns their sum when it is called. When we call the add function with the arguments 2 and 3, it returns the value 5, which we assign to the result variable and then log to the console.

The return statement is used to exit the function and specify the value that should be returned to the caller. It can be used in any function, regardless of whether the function is intended to return a value or not.

For example, the following function returns undefined:

function doNothing() {
// This function does nothing

let result = doNothing();
console.log(result); // Output: undefined

In this case, the doNothing function does not have a return statement, so it returns the default value of undefined when it is called.





Please log in to post an answer!