X



Home>Tutorial>

What is JavaScript return Statement

Nuelson Penuel Wednesday, August 2, 2023 Javascript

In JavaScript, the return statement is used to specify the value that a function should return. It is used within a function to exit the function execution and provide a value that can be used by the calling code. Here is an example that demonstrates the usage of the return statement:
function addNumbers(a, b) {
  return a + b;
}
const result = addNumbers(5, 3);
console.log(result);
In the above example, we have a function called addNumbers that takes two arguments, a and b. Inside the function, the return statement is used to specify the sum of a and b. When this return statement is encountered, it immediately exits the function execution and returns the specified value. In the next line, we call the addNumbers function with arguments 5 and 3, and store the returned value in the variable result. Finally, we log the value of result to the console, which will output 8. The return statement is crucial for functions as it allows them to provide a result or output that can be used by the rest of the program. It is especially useful when you need to perform some calculations or operations within a function and return the result to the calling code. It's important to note that when a return statement is executed, it not only returns the value but also terminates the execution of the current function. This means that any code following the return statement within the same function will not be executed. Additionally, if a return statement is not explicitly specified in a function, the function will return undefined by default. Here's an example illustrating this:
function greet(name) {
  if (!name) {
    return "Hello, what's your name?";
  } else {
    return "Hello, " + name + "!";
  }
}

const greeting1 = greet();
console.log(greeting1);  // Output: "Hello, what's your name?"

const greeting2 = greet("John");
console.log(greeting2);  // Output: "Hello, John!"
In the above example, the greet function takes a name parameter. When the function is called without providing a name argument (like in greeting1), it returns a string asking for the name. However, when the function is called with a name argument (like in greeting2), it returns a personalized greeting message.

| | Views(174)

See Demo | Download File


Add your comment. Indicate code using code tag


Words: 0 | Chars: 0 | Reading Duration: 0



Images Attachment




Emmason Integratded Services(2017-2024)
All Rights Reserved
Designed and Maintained By Emmason Integrated Services