Functions can be defined inside other functions:
const dosomething = () => {
const dosomethingelse = () => {
//some code here
}
dosomethingelse()
return 'test'
}
The nested function is scoped to the outside function, and cannot be called from the outside.
This means that dosomethingelse()
is not reachable from outside dosomething()
:
const dosomething = () => {
const dosomethingelse = () => {
//some code here
}
dosomethingelse()
return 'test'
}
dosomethingelse() //ReferenceError: dosomethingelse is not defined
This is very useful because we can create encapsulated code that is limited in its scope by the outer function it’s defined in.
We could have 2 function define a function with the same name, inside them:
const bark = () => {
const dosomethingelse = () => {
//some code here
}
dosomethingelse()
return 'test'
}
const sleep = () => {
const dosomethingelse = () => {
//some code here
}
dosomethingelse()
return 'test'
}
and most importantly you don’t have to think about overwriting existing functions and variables defined inside other functions.