Tuesday, November 12, 2024

JavaScript Return Statement With or Without Argument

In JavaScript, the return statement is used to exit a function and optionally return a value to the caller. There are differences between using a return statement with or without an argument.

1. Return with an argument

When a return statement is used with an argument, it returns the specified value to the function caller.

Example:
function add(a, b) {
  return a + b; // returns the sum of a and b
}

let result = add(5, 3); 
console.log(result); // Output: 8
In this case, return a + b; sends the result of the expression (a + b) back to the caller.
The function add returns a specific value, and it can be assigned to a variable (result) or used directly.

2. Return without an argument

When the return statement is used without an argument, it returns undefined by default. This means that the function ends without explicitly returning any value.

Example:
function greet(name) {
  console.log('Hello, ' + name);
  return; // returns undefined by default
}

let greeting = greet('Alice');
console.log(greeting); // Output: undefined
In this case, the greet function performs an action (printing a message) but does not return any value.
The return; statement is implicit and returns undefined, which is the default return value when no value is provided.

3. Without return statement

When return statement is not used in function, then it implicitly returns undefined similar to case2.

Summary

  1. With an argument: The function returns the value provided as the argument to the return statement.
  2. Without an argument: The function exits and implicitly returns undefined.



No comments:

Post a Comment

Hot Topics