Welcome to this new series of JavaScript tutorials. It is designed for developers who are experienced with other programming languages (C++ or even worst : Java) and who think that JavaScript is a light version of Java: its name starts with Java and it even has a similar syntax which is definitely wrong. I was one day one of these guys. I always had the following issue when writing in JavaScript: I start coding quickly. It’s exactly the same thing to what I use to. What’s the worst that can happen? And then when I run the code, I discover a countless number of bugs for reasons that I don’t understand. Sometimes, even worst: the whole architecture of my code is wrong because I didn't understand how JavaScript works and I need to start from scratch. (I still have yet some of these issues ☺).
Through this series we are going to discuss the dark parts of JavaScript: the parts where I got most of the troubles.
The Scope
Global Variables
A global variable can be accessed and modified outside and inside the function where it was defined.
A variable which is declared outside a function with “var” is a global variable.
var a;
a = 1;
alert(a); // a = 1
function test() {
alert(a); // a = 1
a = 5;
}
test();
alert(a); // a = 5
Warning!!
A variable which is declared inside or even outside a function without using a “var” is also a global variable.
function test() {
a = 5;
}
test();
alert(a); // a = 5
Local Variables
A local variable can be accessed and modified only inside the function where it was defined.
A variable which is declared inside a function with a “var” is a local variable.
function test() {
var a = 5;
}
test();
alert(a); // ReferenceError: a is not defined.
Function arguments are also local variables.
function test(a) {
alert(a); // a = 5
}
test(5);
alert(a); // ReferenceError: a is not defined.
Local vs Global
When there are two variables: one is local and the other one is global and both have the same name, the local variable hides the global variable.
var a;
a = 1;
alert(a); // a = 1
function test() {
var a = 5;
alert(a); // a = 5
a = 4;
}
test();
alert(a); // a = 1
Block Scope
“var” keyword doesn't support block scope.
var a;
a = 1;
alert(a); // a = 1
function test() {
if (true) {
var a = 5;
}
alert(a); // a = 5
a = 4;
}
test();
alert(a); // a = 1
Let Keyword
There is another keyword that allows us to declare a block scope local variable. Unfortunately, it’s not supported by all the browsers.
var a;
a = 1;
alert(a); // a = 1
if (true) {
let a = 5;
alert(a); // a = 5
}
alert(a); // a = 1
Conclusion
The main conclusion of this article is that the JavaScript scope is different to other programming languages like Java/C++ that we are used to.
So please be careful about that and try to understand all these rules to avoid later a lot of bugs.