In JavaScript, the return statement is used to stop a function from executing and return a value from inside the function.
Let’s say you have a function addName
that accepts name inputs.
let addName = function(name) {}
Now you want to pass a name to the addName()
function:
let myNameIs = addName("David")
Now the addName
function contains a variable name
with a string value of "David"
but right now you can’t do anything with the name
variable and its string value David
, because it’s stuck inside the addName()
function.
If you try to access it like this:
console.log(myNameIs)
// Undefined
You get undefined
.
This is where return
comes into the picture.
Add return name
inside your function and then try to log it out again:
let addName = function(name) {
return name
}
let myNameIs = addName("David")
console.log(myNameIs)
// "David"
Now it works!