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 |
Are you intimidated by Git? Can’t figure out
merge vs rebase? Are you afraid of screwing up
something any time you have to do something in
Git? Do you rely on ChatGPT or random people’s
answer on StackOverflow to fix your problems?
Your coworkers are tired of explaining Git to
you all the time? Git is something we all need
to use, but few of us really master it. I
created this course to improve your Git (and
GitHub) knowledge at a radical level. Launching
May 21, 2024. Join the waiting list!