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
foovariable 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 ?
By using
var fooinside your function, you are explicitly telling the variable only to change locally, within that function. If you want to change it globally, just usefoo = ...If you want to read up on it, I suggest this SO Question