What is Scope?
This example demonstrates how the value of the variable
test changes depending on its scope. During the function call, its value is “local”, but afterwards, execution returns to the global scope.
As shown by the console output in this example, inside the
inner() function, the value of
test is 2, not 1, because that is the first definition the code encounters when searching outwards.
What is Hoisting?
Without an assigned value, the the value of
veggie is undefined.
cheese, however, is an undeclared variable, so the program crashes. Knowing that using an undeclared variable will crash the program, take a look at the next example.
fruit is not declared until the line after the first
console.log, the function does not crash. This is because the declaration is hoisted to the top of the scope.
undefined is logged because only the declaration is moved, not the definition. It is not until the second and third
console.log statements that the value of
fruit is defined.