Functions: Returning values from a function

A function can have a return value.

By default a function returns undefined.

If you want to return a value from it, you add a return keyword with a value:

function test() {
  // do something
  return "hi!"
}

In your program you can assign the return value of the function to a variable, when you invoke the function:

function test() {
  // do something
  return "hi!"
}

const result = test()

result now holds a string with the hi! value.

One thing to note is that you can “return early” from a function, and this is very useful for example when you need to meet a condition before going on with your program:

function test(condition) {
  if (condition === false) return

  // do something
  return "hi!"
}

const result = test(true)

You can only return one value from a function.

A “trick” to return multiple values from a function is to return an object, or an array, like this:

function test() {
  return ["Flavio", 37]
}

Then you can call the function and save your array to a variable, or use array destructuring like this:

const [name, age] = test()

Lessons in this unit:

0: Introduction
1: Function parameters
2: ▶︎ Returning values from a function
3: Arrow functions
4: Nesting functions
5: Immediately-invoked functions
6: Recursive functions