MakeW3web

JavaScript Return values and undefined

In JavaScript, functions can return values using the `return` statement. When a function is called, the value returned by the function can be used in other parts of your code, allowing you to pass data between functions and create more modular programs.

  1. Return values:

To return a value from a function, you use the `return` keyword followed by an expression or a value. Once the `return` statement is executed, the function immediately terminates, and the control is passed back to the caller.

Example:

function add(a, b) {
  return a + b;
}

const sum = add(3, 4);
console.log(sum); // Output: 7

In this example, the `add` function takes two parameters, `a` and `b`, and returns their sum using the `return` statement. When the function is called with the arguments `3` and `4`, it returns the value `7`, which is then assigned to the `sum` variable.

  1. Undefined return values:

If a function does not have a `return` statement or the `return` statement does not specify a value, the function returns `undefined` by default.

Example:

function logMessage(message) {
  console.log(message);
}

const result = logMessage("Hello, World!");
console.log(result); // Output: undefined

In this example, the `logMessage` function takes a single parameter, `message`, and logs it to the console. The function does not have a `return` statement, so it returns `undefined` by default. When the function is called with the argument `"Hello, World!"`, it logs the message to the console, but the `result` variable is assigned the value `undefined`.

Understanding how return values work in JavaScript is crucial for writing functions that communicate effectively with other parts of your code. By using return values and properly handling `undefined`, you can create more robust and modular programs that are easier to maintain and debug.

Was this page helpful?