In JavaScript, functions can contain a return statement—which consist of a return keyword and a value.
function multiply(num1, num2) { return num1 * num2}When JavaScript sees a return keyword, it returns the value associated with the return keyword to the code that called the function. Code after the return statement is not read.
function multiply(num1, num2) { return num1 * num2 console.log('This statement will never be read!')}You can use this return statement in a control flow to return a value early. This is called an early return.
When to use early returns
You want to use early returns for two situations:
- To reduce nested code
- To remove the need for
else ifstatements
Reducing nested code
When we use the event delegation pattern, we usually need to search for an element; when the element is present, we execute some code.
container.addEventListener('click', e => { const el = e.target.closest('.some-element') if (el) { // Rest of the code here }})You don’t need to nest the rest of the code if you used an early return.
container.addEventListener('click', e => { const el = e.target.closest('.some-element') if (!el) { return }
// Rest of the code here})Removing else if statements
An else if statement is used when you need a control flow that can execute three or more code blocks.
Let’s say you want to get a gift for your kid.
- If they scored 100 marks, you’ll buy them an Xbox.
- If they scored between 76 to 100 marks, you’ll get them a new phone.
- If they scored between 51 to 75, you’ll bring them for a meal.
- If they got below 50, they’ll get nothing.
let gift
if (score === 100) { gift = 'Xbox'} else if (score > 75) { gift = 'new phone'} else if (score > 50) { gift = 'A meal'} else { gift = null}As mentioned previously, if/else branches take up brainpower. else if branches take up even more brainpower.
To simplify the code above, you can create a function that determines the gift, and use early returns within the function.
function getGift(score) { if (score === 100) { return 'Xbox' } if (score > 75) { return 'new phone' } if (score > 50) { return 'meal' } return null}
const gift = getGift(70)console.log(gift) // 'meal'Curly brackets and if statements
Curly brackets for an if (or else, or else if) statement indicate the code to run when the condition is met.
if (condition) { console.log('Say cheese!')}If you only need one expression, you can omit the curly brackets.
function getGift(score) { if (score === 100) return 'Xbox' if (score > 75) return 'new phone' if (score > 50) return 'meal' return null}Welcome! Unfortunately, you don’t have access to this lesson. To get access, please purchase the course or enroll in Magical Dev School.
Unlock this lesson