return Keyword

Examples

Interrupt a function

A function immediately stops at the point where return is called.

function counter() {
  for (let count = 1; ; count++) {  // infinite loop
    console.log(`${count}A`); // until 5
    if (count === 5) {
      return;
    }
    console.log(`${count}B`);  // until 4
  }
  console.log(`${count}C`);  // never appears
}

counter();

// Output:
// 1A
// 1B
// 2A
// 2B
// 3A
// 3B
// 4A
// 4B
// 5A


Returning a function

See also the article about Closures.

function magic() {
  return function calc(x) { return x * 42; };
}

const answer = magic();
answer(1337); // 56154