xxxxxxxxxx
// nested function example
// outer function
function greet(name) {
// inner function
function displayName() {
console.log('Hi' + ' ' + name);
}
// calling inner function
displayName();
}
// calling outer function
greet('John'); // Hi John
xxxxxxxxxx
/*
* A nested function is a function within another function.
* A nested function is local, meaning it can only be accessed
* by code within that same function scope.
*/
function globalFunction() {
function localFunction() {
return "Hello world!";
}
return localFunction();
}
console.log(globalFunction()); // -> "Hello world!"
console.log(localFunction()); // -> Uncaught ReferenceError: localFunction is not defined
xxxxxxxxxx
/*
Function Syntax:
function functionName(parameter1, parameter2, ...) {
return something;
}
*/
function globalFunction(a, b, c) {
// `localFunction` cannot be called outside of `globalFunction`, once `globalFunction` finishes, `localFunction` ceases to exist
function localFunction(d, e, f) {
return [ f, e, d ];
}
return localFunction(a, b, c);
}
xxxxxxxxxx
// nested function
let a = 10;
const main = () => {
let b = 20;
const inner = () => {
let c = 30;
console.log(a, b, c);
};
return inner();
};
main(); // 10 20 30