Introduction to JavaScript Variables and their Scope.
Get introduced to JavaScript variables, and the different types of scopes!
What is a variable?
A variable is a named piece of a memory location. By adhering to certain specific naming conventions which a variable should follow, we can access that memory location using that name anywhere in our program.
Now, the main question arises: Why should you learn about variables, and then use them? Well, the simplest answer is, it makes your life so much easier! Don't believe me? Let's see an example:
Let us imagine a scenario where you want to invite 7 (no specific reason why I chose this number) people to your birthday party, and you want to create invitation cards by specifying the name of the person and the location details, and the time of arrival. Let us simply mimic this real-life scenario with the help of console-log:
console.log(" Hey Joe! I'd like to invite you to my birthday party")
console.log(" 7:P.M. near XYZ mall. Hope to see you there!! ")
Great! You're done with one invitation! 6 more to go! But, instead of typing them, why don't we just copy-paste them 6 more times? That would make our job easier, right? Let me do it for you.
console.log("Hey John Wick!")
console.log("I'd like to invite you to my birthday party, at 7:P.M. near XYZ mall. And since you love your dog so unconditionally, you can bring it along too! Hope to see you there!! ")
console.log("Hey Katy Perry!")
console.log("You're a FIREWORK! And so, I'd like to invite you to my birthday party, at 7:P.M. near XYZ mall. Hope to see you there!! ")
console.log("Hey Captain Marvel!")
console.log("I know you're out there, thousands of light years away, saving galaxies from bad people. But I was hoping you could hop back to earth and save my birthday party instead? 7:P.M. near XYZ mall. Hope to see you there!! ")
console.log("Hey Dwane 'The Rock' Johnson!")
console.log("I'd like to invite you to my birthday party, at 7:P.M. near XYZ mall. I'm Hoping the Jabroni-beatin', pie-eatin', Hell-raisin', trailblazin', People's Champ would be there!! ")
console.log("Hey Simon Cowell!")
console.log("I know you don't have many friends, but don't worry! I'd like to invite you to my birthday party, at 7:P.M. near XYZ mall. Hope to see you there!! ")
console.log("Hey Emilia Clarke!")
console.log("(P.S. -> I have a massive crush on you!!!!!)I'd like to invite you to my birthday party, at 7:P.M. near XYZ mall. Hope to see you there!! ")
I've also changed the names from Joe to 6 other random people(or maybe, not so random)
P.S. ==> If you were able to understand the catchphrases and the inside jokes/memes I used in the above examples, let me know in the comments!
This is what it appears like in the console:
Awesome! Invitations created! You send the invitations, and then, suddenly, on the eve of your birthday, you realize that you won't be able to make it by 7:P.M and that you need to delay your party by an hour. So now, what do you do? In the above scenario, are you going to go to each individual invitation and then change the time from 7 P.M. to 8 P.M.? Sure, you can do that. It might take a while, but you'll get done with it. But let me throw you a mind grenade. What if, instead of 6 invitations, there were 100? Are you going to spend the eve of your birthday editing invitations? No, right?
So, is there a better way? Yes!!
You can take the help of variables. By storing a certain value in a variable(for example, time in the above example), you can simply access that value with the help of the variable name in various parts of the program and then modify it quite easily.
I want to add a quick side note: The examples I will use down below are for illustrative purposes only and some of them might throw you an error if you try to run them as it is, because JavaScript executes our code line by line, and if it encounters an error, it does not proceed to the remainder of the program.
In JavaScript, you can declare variables using three keywords ==> let, const, var.
Ever since the inception of JavaScript, up until the ES5 module, var was the traditional way of declaring variables. But var had certain shortcomings(which we'll talk about in the next blog) and, with the introduction of the ES6 module in 2015, those shortcomings were addressed and two new keywords were introduced for declaring variables: let and const. Before let and const were introduced, the JavaScript world had two types of scope - function scope and global scope(we'll look into what scope is next), but with their introduction, they brought with them a new type of scope, which is block scope.
Getting heavy? Don't worry. I'll explain.
So, first: what is the meaning of scope? Well, scope represents the accessibility of the variables. Yes. You guessed it right. Variables which you might have declared at a certain part of your code, might not be accessible for use in some other part of your code. Now, this could easily get very frustrating; for you might be wondering, "Hey, I have declared the variable, but why can't I access it and display it in my output?" Hence, it becomes very important for you to learn about scope and its types if you want to enhance your JavaScript knowledge.
Variable Scope
There are three types of scopes:
1) Block Scope
What is a block? A block is a section of code written inside { }. So, if we put two and two together, what do we mean by block scope of a variable? It refers to the accessibility of the variable with respect to the block. What it means is that if a variable is declared inside a block, then it can ONLY be accessed from within the block, and not from outside of it. But wait, hold up. We've just learned that there are three different ways of declaring a variable. So, if we declare a variable using let, var, and const respectively, would it have a block scope in all three cases? Let's find it out with an example:
{
var a = 34;
}
console.log(a); // OUTPUT ==> 34
{
let b = 34;
}
console.log(b); // OUTPUT ==> Uncaught ReferenceError: b is not defined
{
const c = 34;
}
console.log(c); // OUTPUT ==> Uncaught ReferenceError: c is not defined
Let us now try and understand these outputs.
In the first example, we declared a variable a with the help of the var keyword. The var keyword does NOT have a block scope, meaning, its accessibility is not limited to just within the block. It actually has a function scope, or global scope(which we'll talk about next). The variable can be accessed from outside the block as well.
And in the second and third examples, we have declared variables b and c using keywords let and const respectively. Both the let and const keywords have block scope, meaning, its accessibility is limited to just within the block. The variable cannot be accessed from outside the block. Hence, when we try to console log b and c, we get the error that b and c are not defined.
So, to summarize: a variable, if declared using the var keyword, would not have a block scope, so, it can be accessed not only from within the block but also from outside of it. And, if a variable is declared using the let and const keyword, then it would have a block scope, so it can be accessed from only within the block, and NOT from outside of it.
Variables declared within a block become LOCAL to the block, so they are also referred to as local variables. As soon as the block ends, these local variables are deleted. This allows us to use multiple variables with the same name in various parts of the program without having to worry about variable names clashing or having to come up with some fancy names for each variable.
2) Function Scope:
JavaScript has function scope. What does function scope mean? Again, if we put two and two together, it refers to the accessibility of the variable with respect to the function. Variables declared inside a function can ONLY be accessed from within a function, and NOT from outside of it.
Now, you might be wondering, what is the difference between function scope and block scope?
Let us take another example to further clarify our concepts:
function myFunction()
{
var a = 34;
let b = 34;
const c = 34;
if(true)
{
console.log(a, b ,c); // OUTPUT ==> 34, 34, 34
let d = 12;
console.log(d); // OUTPUT ==> 12
}
console.log(a,b,c); // OUTPUT ==> 34,34,34
console.log(d); //OUTPUT ==> Uncaught ReferenceError: d is not defined
}
myFunction(); // Function call
console.log(a)
console.log(b)
console.log(c)
console.log(d)
Let us break down this example: We have declared a function named myFunction (in JavaScript, one of the ways of declaring a function is using the 'function' keyword. After declaring a function, we also need to invoke it. For now, don't worry about the syntax. We'll look into what functions are and how can we use them in a later blog.) Inside of it, we have declared three variables a,b,c using var, let, and const respectively. Just to brush up on your memory, var has function scope, and let and const have block scope. So, the variable 'a' has a function scope, and the variables 'b' and 'c' have block scope.
This is what the output appears like in the console.
As the condition is true, we go inside the if block. In the console, we see all the three values of a, b, and c (indicated by the line script.js: 7, {which basically means it is the 7th line of my code}). Now, this might give rise to a question inside your head. If we see the values of b and c being printed in the console, then does that mean b and c have a function scope as well?
Not exactly.
If you see carefully, the function too begins with curly braces. So, although it might seem that the variables b and c have a function scope, their scope is block. If we take the example of d, which is declared using the keyword let, we can see that it can be accessed ONLY within the if-block and not outside of it (as indicated by the script.js: 12, where we can see an error message that d is not defined.) This indicates that variables declared using let and const have block scope, as discussed.
(If the scope of a variable seems a bit confusing to you, what you can do is that whenever you declare a variable using the let and const keywords, navigate upwards, and wherever you come across the first curly brace, the variable can be accessed anywhere inside that block.)
As soon as the function ends, the variables a, b, c, and d, of them cannot be accessed now. (Hence, we do not see any output on the console for the last four console.log's in our code.)
Variables declared within a function become LOCAL to the function, so they are also referred to as local variables. As soon as the function ends, these local variables are deleted. This allows us to use multiple variables with the same name in various parts of the program without having to worry about variable names clashing or having to come up with some fancy names for each variable.
3) Global Scope :
Variables declared outside a function have global scope. Variables declared globally can be accessed from any part of your code. A variable declared with the keyword var, let, and const globally are quite similar. What that means is that if you declare a variable globally, it doesn't really matter which keyword you've used(i.e. var, let, and const) to declare it.
Let us take an example:
var a = 34;
let b = 34;
const c = 34;
function myFunction()
{
//Some Code here
console.log(a) // OUTOUT ==> 34
console.log(b) // OUTOUT ==> 34
console.log(c) // OUTOUT ==> 34
}
myFunction();
if(true)
{
console.log(a) // OUTOUT ==> 34
console.log(b) // OUTOUT ==> 34
console.log(c) // OUTOUT ==> 34
}
console.log(a) // OUTOUT ==> 34
console.log(b) // OUTOUT ==> 34
console.log(c) // OUTOUT ==> 34
The above example shows that variables declared globally, (be it with let, const, var) can be accessed anywhere in our program. Global variables are deleted when we close the current tab or the browser window.
What happens if we declare a variable without using the keywords let, const, and var?
If we declare a variable without using the keywords let, const, and var, then it automatically becomes a global variable(i.e.- it gets assigned a global scope)
You should avoid declaring variables globally. Why you ask?
1) Declaring variables globally doesn't allow us to assign the same variable name to some other variable. It causes variable name collisions, thereby forcing the user to come up with new names for each variable.
2) Global variables can be accessed/modified in any part of your program. Most of the time, you would want your variables to have a particular scope(function or block) so that they could only be accessed/modified within that particular section of your code. It is just as easy to inadvertently change a global variable as it is to change purposely. So, this might cause some unexpected errors, which in large programs, really becomes a pain.
So now, after reading this blog, you have a good understanding of JavaScript scope, what are the different types of scope, how using variables can make our lives easier, and the different keywords used to declare a JavaScript variable (let, var, and const.) In the next blog, we will be looking into the differences between these keywords.
Thank you so much for reading my blog. I really hope you found this helpful. A quick suggestion: After learning a concept, always try and experiment with different things by yourself. Head to your text editor, write some code, print it out into the console, and try to understand the output. Now, this applies to absolutely any programming language you're learning. If you bump into an error, rather than searching for a fix on the web, you should first spend a considerable amount of time trying to debug the issue yourself. Upon successfully doing it, it not only would give you immense satisfaction but also would further solidify your concepts.
See you on the next blog. May the force be with you!