Early returns
Hey ,
I'm thrilled to help you learn JavaScript. Unfortunately, you've landed on a page where you cannot access with your current purchase.
Please upgrade (use this link) access this content.
I'm super eager to help you learn more!
Hey ,
I'm thrilled to help you learn JavaScript. Unfortunately, you've landed on a page where you cannot access with your current purchase.
Please upgrade (use this link) access this content.
I'm super eager to help you learn more!
In JavaScript, functions can contain a return statement—which consist of a return
keyword and a value.
const 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.
const 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.
You want to use early returns for two situations:
else if
statementsWhen 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
})
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.
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.
const 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 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.
const getGift = score => {
if (score === 100) return 'Xbox'
if (score > 75) return 'new phone'
if (score > 50) return 'meal'
return null
}