javascript function inside function code example

Example 1: closure in js

A closure gives you access to an outer function’s scope from an inner function
//example
function init() {
  var name = 'Mozilla'; // name is a local variable created by init
  function displayName() { // displayName() is the inner function, a closure
    alert(name); // use variable declared in the parent function
  }
  displayName();
}
init();

Example 2: function inside function javascript

function getFullName() {
	return getName() + ' ' + getLastName();
  	function getName() {
    	return 'William';
    }
  	function getLastName() {
    	return 'Wallace';
    }
}

console.log(getFullName());
//William Wallace
console.log(typeof getFullName);
//function
console.log(typeof getName);
//undefined
console.log(typeof getLastName);
//undefined

Example 3: closures in javascript

function OuterFunction() {

    var outerVariable = 100;

    function InnerFunction() {
        alert(outerVariable);
    }

    return InnerFunction;
}
var innerFunc = OuterFunction();

innerFunc(); // 100