What is this blog series about?
Through this blog series, I hope to explain variable declarations in JavaScript using var
, let
, and const
. I intend to cover various rules, properties, and scenarios to explain the 3 types of declarations and hopefully ease understanding of variables in JavaScript!
This blog would be probably end up becoming a 2 or 3 part series since there are a lot of concepts to cover!
Prerequisites
- Basic JavaScript syntax
- Concept of scope
Contents
Introduction
As humans, we see names everywhere - names we give to people, pets, and even inanimate objects. Even machines refer to names within their memory. The only difference is that their names are addresses.
Even in the world of programming, we have names. And these names are called variables
.
What are Variables?
Variables are placeholders we use to store values. These values could be any of the primitive types or objects.
To declare (define) variables in JavaScript, you write the following code-
"keyword" variable_name
The keyword
in JavaScript could be - var
, const
, or let
.
Before we move on, let us try to understand another term often used when talking about variables - scope
.
What is a Scope
- A scope is the context or region where a value is visible.
- When we talk about the scope of variables, it is the region in the program where it can be referenced and used.
- Let's understand scope with an analogy.
- John Doe is from India. He's planning on moving to Japan since he got an opportunity to work there (and being a lover of anime was an added advantage!).
- Now, once he moves to Japan, the Indian Rupee is no longer in scope in Japan (unless of course he exchanges the currency!).
- Also, the Japanese Yen he earns there is not in scope when he visits his home in India.
- Similarly, in JavaScript where you declare your variables reflects where and how you can use them. More to this in the post.
In this article, let us understand about variables declared using'var`.
var Keyword
- Variables declared with
var
have a global or function scope.
Syntax
var variableName [= value];
- Initialization while declaring is optional.
-
Variabled have a global or function scope - what this means is that, if a variable using
var
is-
Declared within a function then, it is accessible anywhere within that function (even enclosing blocks such as if statements).- Declared Withing the script (globally), then it is accessible in all enclosing functions and blocks of all the script files associated with the current page.
If you come from languages such as Java, you can visualize these variables as
publically defined variables
or public variables.
Scopes of var
- Let us look at some examples now-
- In the above example, the variable
x
has a global scope. Hence the variable is accessible both- outside and inside the function. But variable y has a function scope as it's declared within the function. You cannot access it outside the function.
- In the above example, the variable
-
Let us look at another example that highlights the behavior of variables declared using
var
in blocks.
- The output for the program above is -
- Even though a different variable
var y = 100
was declared within the if block, look how it changes the value of the variablevar y = 20
that was declared within the function. - This is because variables declared with
var
have function scope, and any variables declared within a block are scoped to the function or script that has the block. - So this means that both the variables have the same reference (memory address).
- Let me show you this through the console.
- Hence, any change made to the variable declared within the if block reflects in the variable defined within the function.
- This also means that redeclaration of the same variable is accepted for variables declared with
var
(concept covered later in this article).
var and its unhealthy attachments!
- Another interesting property of a variable declared globally using
var
is that it is bound to the global object. - This means that in any JavaScript environment, you can access the variable using the global object.
- e.g., in browsers, you can use the global
window
object to access the variable. - In the above example, where
x
is declared globally, you can usewindow.x
to get the value of x.
In some places you will see this as well -
globalThis.x
. This also works and it means the same thing.
Since there are many JavaScript environments and each of them has different global objects,globalThis
provides unified access to the object.
- But note that variables declared globally that are attached to the global object are bad.
- Why? It's simple. Since it's attached to the global object it is visible and accessible globally by any JavaScript code.
So if you have used global variables before... Now you know to avoid it.
var and its affair with undefined
- Let's look at the following code -
- Notice how the variable
count
is being accessed even before it's declaration. - Now, if you came to JavaScript from another language, you'd say- 'Of course, this is an error!`
- But in JavaScript, that is not the case.
- The JavaScript performs something called
hoisting
. - Hoisting is the process in which all variable, function, and class declararions are moved to the top their scope.
- The declarations are allocated memory much prior to the execution of code.
This means that you can access them before the actual declaration appears in the script.
That's fine, but the next question would be, what would
console.log(count)
print?The assignment to the
count
variable happens only after this line.This is where
undefined
comes in. JavaScript auto initializes variables declared usingvar
withundefined
.The value
undefined
means that - "Hey, there is memory allocated for this variable. But it's not been initialized yet."
- The final output would be -
Implicit global variables
- Although not a good practice, it's worth mentioning that a variable that's never declared but initialized with a value is automatically considered as a 'global variable'.
- This would not generate errors and works fine in
non-strict mode
. This mode is when the JavaScript interpreter understands features previous to the ES5 version, i.e., the default mode. - But in the strict mode that uses features introduced in ES5+, this would generate errors.
Redeclarations using var
- If you have come to JavaScript after exploring a few other languages, you know that a variable cannot be declared with the same name twice.
- But JavaScript is special. JavaScript let's you declare a variable with the same name if you do so with the
var
keyword. - For e.g., the code below works perfectly fine and no error is thrown.
- If you think about it, this is bad news.
- Say you are working on a project as a team and on your day off, your fellow mate comes and redeclares a variable you've already done so, but, with a new value.
- The interpreter indicates no error, and your team mate is happy that the code does what was expected.
- The next day you come and see that your part of the logic no longer works! And all because somewhere in the code a variable was re-declared. All you'll end up doing is wonder why!
- That's all for this post! Hope you found this blog helpful and were able to understand
var
in a much better sense. - The key takeaway you should have from this post is that, never trust
var
, and avoid usingvar
in your programs. - The JavaScript community realized issues with
var
and that's why new alternatives -let
andconst
- were introduced in ES6. - The keywords,
let
andconst
will be covered in the next part of the blog!
Summary
-
scope
is the region of the code where any value is visible or accessing. -
var
declarations when defined within a function are accessible anywhere inside that function.var
declarations that are global can be accessed anywhere within the script. -
var
declarations are attached to the global object of all JavaScript environments and can be accessed using theglobalThis
object or thewindow
object in browsers. -
var
declarations are hoisted. This means that they are allocated memory even before the code is executed and are auto initialized withundefined
. - A variable that is not declared but directly initilized becomes an implicit global variable and is attched to the global object.
-
var
declarations can be redeclared. That is, 2 variables that have the same name and belong to the same scopes can be declared usingvar
.
Hope you found this blog post helpful. If yes, help me out by hitting that unicorn/ pin/ heart button, comment down your thoughts, and share it among the dev community.
Thank you for reading!
Top comments (2)
well articulate Bharti ,with example good use of gif
Thank you, Shubham!