JS Code
var foo = "Hello World!"; // <------- global scope
document.write("<p>Before our anonymous function foo means '" + foo + '".</p>');
(function() {
// The following code will be enclosed within an anonymous function
var foo = "Goodbye World!"; // <------- local scope
document.write("<p>Inside our anonymous function foo means '" + foo + '".</p>');
})(); // We call our anonymous function immediately
document.write("<p>After our anonymous function foo means '" + foo + '".</p>');
HTML Output
Before our anomymous function foo means 'Hello World!".
Inside our anomymous function foo means 'Goodbye World!".
After our anomymous function foo means 'Hello World!".
My problem is
- When we replace the value of
foo
variable inside the function why does not get it replaced ? How does it still contains the"Hello World!"
? - If I'm to access the global variable inside the function How can I do it ?