Whenever we declare a variable, it is immediately given a scope. The scope which belongs to a variable depends to where it was declared on the code.
If we run the example, it will throw ‘undeclared variable’ error. Therefore we can conclude that whenever we make a function, it will make its own scope isolated from outside the function.
If we run example above, it will print out ‘bar’. This shows us that even though we declare the variable outside a function, it is still recognized inside the function after we call out the function. Now look at the example below.
Variable ‘bar’ which is declared inside a function is not recognized outside the function so it will throw an
x can still be accessed by
multipleByX function despite
multipleBy has been invoked. This happens because
multipleByX still save a scope outside of it. This concept is known as a closure.
Closures are functions that refer to independent (free) variables (variables that are used locally, but defined in an enclosing scope). In other words, these functions ‘remember’ the environment in which they were created. - Mozilla Developer Network
Giraffe function return an object which contains two properties,
changeFood. Because of lexical scoping, these two properties save scope from
Giraffe which are
eat function. Therefore when
babyGiraffe.changeFood were called, they can still be accessed. The example above also shows that
eat can only be accessed via properties which were returned by
Giraffe function. This kind of model is often be used to avoid global scope pollution, and is popularly known as module pattern.