Understanding Global & Local Scope in Javascript – Even if we have a good project plan and a logical concept, we will spend the majority of our time correcting errors abaout javascript and . Furthermore, our application can run without obvious errors with JavaScript, we must use various ways to ensure that everything is operating properly. In general, there are two types of errors that you’ll encounter while doing something wrong in code: Syntax Errors and Logic Errors. To make bug fixing easier, every JavaScript error is captured with a full stack trace and the specific line of source code marked. To assist you in resolving the JavaScript error, look at the discuss below to fix problem about Understanding Global & Local Scope in Javascript.
Problem :
I’ve been learning Javascript using Object-Oriented JavaScript by Stoyan Stefanov
He offers an example comparing global and local scope:
var a = 123;
function f() {
alert(a);
var a = 1;
alert(a);
}
f();
Looking at this example, I expected the first alert to be ‘123’ and the second alert to be ‘1’. Lo and behold, Stoyan says:
You might expect that the first alert() will display 123 (the value of
the global variable a) and the second will display 1 (the local a).
This is not the case. The first alert will show “undefined”. This is
because inside the function the local scope is more important than the
global scope. So a local variable overwrites any global variable with
the same name. At the time of the first alert() a was not yet defined
(hence the value undefined) but it still existed in the local space.
The explanation was not clear to me, how can the local variable overwrite the global variable in the first alert? Any other/different explanations would be appreciated.
Solution :
It is not overriding the global variable. What is happening is called “variable hoisting”. That is, a var a;
gets inserted at the top of the function.
The script engine changes your script to be the following:
var a = 123;
function f() {
var a;
alert(a);
a = 1;
alert(a);
}
f();
Lesson to learn: Always declare your variables before you use them. Some will say declare all your variables at the top of the function.
In simple words, all the declarations, of both variables and functions are considered first. So local var a
in effect will override global variable only in local scope and will have no value i.e. undefined
. So first alert will show undefined
. Second alert will show 1 as it is after a = 1
. This just happens locally and global variable a will have value 123 – it won’t be changed.
another example using function to show how it works
function show(){
alert("I am global");
}
function f() {
show();
show = function(){
alert("I am second");
}
show();
function show(){
alert("I am first");
}
}
f();
show();