Deep Dive into JavaScript Variables I
Tags: javascript, beginners, webdev, programming
Published: 2022-02-24 14:01:49

## 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
1. [Introduction](#introduction)
1. [What are Variables?](#what-are-variables)
   1. [What is a Scope](#what-is-a-scope)
1. [`var` Keyword](#var-keyword)
   1. [Syntax](#syntax)
   1. [Scopes of var](#scopes-of-var)
   1. [var and it's Unhealthy Attachments](#var-and-its-unhealthy-attachments)
   1. [var and its Affair with undefined](#var-and-its-affair-with-undefined)
   1. [Implicit Global Variables](#implicit-global-variables)
   1. [Redeclarations using var](#redeclarations-using-var)

---

## 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`. 

<br/>

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.
<br />

### Scopes of var
- Let us look at some examples now-
     ![var global and function scope](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gfen2arxm9ucdypwkwbp.png) 
  - 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.

<br />

- Let us look at another example that highlights the behavior of variables declared using `var` in blocks.
     ![Behavior of var in block](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/24h6l9csqhdsq8gixef3.png)
 
 
  - The output for the program above is - ![Behavior of var in block output](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/14pazoukpnexsvpoy1cr.png)
  - Even though a different variable `var y = 100` was declared within the if block, look how it changes the value of the variable `var 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. 
![var behaviour in block scope in console](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pyybkjzvrfz0qmrd3dag.gif) 

  - 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).  
<br />


### 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 use `window.x` to get the value of x.

![var with global scope can be accessed via global object](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r1h53dmnzg6iexnb67wt.png)

> _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. 

<br / >

So if you have used global variables before... ![michael scott when you do something wrong gif](https://c.tenor.com/yGhUqB860GgAAAAC/worriedface.gif) Now you know to avoid it.
<br />

         
### var and its affair with undefined
- Let's look at the following code - 
![var hoisting](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9rq7u9p0tgdev4shb6p3.png)
- 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.

![picking your hair and irritated gif](https://media.giphy.com/media/3o7TKEP6YngkCKFofC/giphy.gif)

- 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.

- So the above code after hoisting is as follows-
![var declaration after hoisting](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5v537n1pjuzgn7jfhtkd.png)

- 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 using `var` with `undefined`.
- The value `undefined` means that - "Hey, there is memory allocated for this variable. But it's not been initialized yet." 

<br />
- The final output would be -
![output of hoisted variable](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hryvseevwn6p620s84ym.png)
<br />

### 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.
![implicit global in non strict mode](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z61kg2keriid3u5vngv3.png)
- But in the strict mode that uses features introduced in ES5+, this would generate errors.
![implicit global generates error in strict mode](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n7vmx7m4bvzz76bxhnsv.png)
<br />

### 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.
![Redeclaring a variable with the same name](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3wkp3z3wysklatrk5xm9.png)
- 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!
![I don't need sleep, I need answers](https://c.tenor.com/_XOJRgZ2M8QAAAAC/sheldon-cooper.gif)

--- 

- 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 using `var` in your programs. 
- The JavaScript community realized issues with `var` and that's why new alternatives - `let` and `const` - were introduced in ES6.
- The keywords, `let` and `const` 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 the `globalThis` object or the `window` object in browsers.
- `var` declarations are hoisted. This means that they are allocated memory even before the code is executed and are auto initialized with `undefined`.
- 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 using `var`.

---
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.
<br />


Thank you for reading!