Skip to main content

Implicit return


This is when you don't define a return from the function. This will return undefined:

function getNameLength(name) {
name.length
}
//this is the same as something like this:
function getNameLength(name) {
name.length
return undefined // implicit return added by JavaScript
}

You will NOT see that return undefined, but think as if it gets added after you run the code while being processed by the computer. That makes it....implied or implicit.

TLDR: If you forget to return from a function, the function will return undefined.

Branching with implicit return


This returns true if it is older than 18, but undefined if it is not. If we do a canVote(5), what do you think it will return? Undefined :)

function canVote(age) {
if (age >= 18) {
return true
}
}

Recap


  • If you forget to return from a function, the function will return undefined – this is called implicit return.
  • The purpose of most functions is to return something. So don't forget to return from them the result that you've calculated.
  • The concept of implicit return also applies in functions with branching (with if conditions).
  • If one of the branches does not have a return, it will return undefined. We will learn how to fix that in upcoming chapters.