Declaring variables in JavaScript (What happens when you don’t)
Tags: javascript, programming, beginners
Published: 2023-03-20 16:37:01

## TLDR people read the last sentence.

As you may know when coding in JavaScript, variables are used extremely often. For those who don’t know, a variable is basically a container used for storing data. When working with variables in JavaScript, they are typically declared using one of the following: `const`, `let` or `var`(usually typed in lowercase). `const` and `let` were recently introduced in [2015](https://www.w3schools.com/js/js_es6.asp). Prior to this there was only one way to declare variables, which was `var`. In essence, `const` and `let` made it easier to catch certain errors that were caused by [`var`](https://javascript.plainenglish.io/4-reasons-why-var-is-considered-obsolete-in-modern-javascript-a30296b5f08f).
####Function Scope 
>"When a variable is declared inside a function, it is only accessible within that function and cannot be used outside that function"

####Block Scope
>"A variable when declared inside the if or switch conditions or inside for or while loops, are accessible within that particular condition or loop"

`const` declares variables and makes it so that it *cannot* be reassigned. `let`, on the other hand, declares variables that *can* be reassigned. `var` is similar to `let` where variables declared with it *can* be reassigned. There are more [differences](https://medium.com/javascript-scene/javascript-es6-var-let-or-const-ba58b8dcde75) but these are just to name a few. Let’s see an example on how declaring variables work:

```javascript
const number1 = 25
let number2 = 50
var number3 = 75

console.log(number1) 
// 25
console.log(number2) 
// 50
console.log(number3) 
// 75
```
*Seems simple enough*. So, what happens if you **don’t declare** a variable? What if you just **assign** the variable a **value**? Is it possible to **reference** these variables later? Well, let's try it:

```javascript
number = 25

console.log(number)
// 25
```
It works just as if it had been declared by `const`, `let` or `var`. *Why* is this happening? Is declaring variables **optional**? 
![Well yes, but actually no meme](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d0ifidzh7s5qymym8df6.jpg)

Even though *technically* you can assign variables without declaring them… **~PLEASE DON'T DO THIS~** You should **always** declare variables using `const`, `let`, or `var`. So what’s going on here? *Why* is this working? Basically, when you **don’t declare** the variable [**explicitly**](https://www.oreilly.com/library/view/javascript-the-definitive/0596101996/ch04.html#:~:text=If%20you%20don%C3%A2%E2%82%AC%E2%84%A2t%20declare%20a%20variable%20explicitly,declare%20it%20implicitly%20for%20you.) in JavaScript, it will declare it for you [**implicitly**](https://www.oreilly.com/library/view/javascript-the-definitive/0596101996/ch04.html#:~:text=If%20you%20don%C3%A2%E2%82%AC%E2%84%A2t%20declare%20a%20variable%20explicitly,declare%20it%20implicitly%20for%20you.). 
####Explicit
>"Stated clearly and in detail, leaving no room for confusion or doubt"

####Implicit
>"Implied though not plainly expressed"

Even though it’s best practice to **declare** your variables, let’s explore how the code will function if you **don’t**. 

So *how* is JavaScript treating an undeclared variable? Is it treating it like `const`? Let’s test and see if you can reassign the variable to a new value if it’s not declared:

```javascript
number = 25
console.log(number)
// 25
number = 50
console.log(number)
// 50
```

As seen above, if the variable is not declared it can be freely reassigned without throwing an error. So we know that this works similarly to `let` and `var`. Let’s take another step by testing its [scope](https://www.codecademy.com/learn/introduction-to-javascript/modules/learn-javascript-scope/cheatsheet). 
####Scope 
>“a concept that refers to where values and functions can be accessed”

Let’s write ourselves a function to test some things: 

```javascript
let number = "global"

function test(){
    let number = "local"
    console.log(number)
}
test()
// local 
console.log(number)
// global
```
```javascript
let number = "global"

function test(){
    var number = "local"
    console.log(number)
}
test()
// local 
console.log(number)
// global
```
```javascript
let number = "global"

function test(){
    number = "local"
    console.log(number)
}
test()
// local 
console.log(number)
// local
```
####Global Scope
>"A variable declared outside a function, becomes GLOBAL"

####Local Scope
>"Variables declared within a JavaScript function, become LOCAL to the function"

In the cases above we set a [*global*](https://www.w3schools.com/js/js_scope.asp) scoped variable equal to 10 and a function ([*local*](https://www.w3schools.com/js/js_scope.asp)) scoped variable equal to 20. Scope in JavaScript works like a reverse *waterfall*. If a variable is declared globally everything **down** the scope chain has access to it. But it **doesn’t** work in **reserve**. So the globally scoped variable should not have access to the variable that is function(local) scoped. When `let` or `var` is used the global variable remains the same, but when it’s **not declared** the **global** variable is now **changed**. You can see how this can potentially be [*dangerous*](https://stackoverflow.com/questions/2485423/is-using-var-to-declare-variables-optional). Whenever you **don’t declare** a variable you run the **risk of changing** that variable’s **value** when it’s **not intended**. 

Let’s revisit the topic of scoping and discuss how it works. Take a look at the [diagram](https://www.oreilly.com/library/view/javascript-the-definitive/0596101996/ch04.html#:~:text=If%20you%20don%C3%A2%E2%82%AC%E2%84%A2t%20declare%20a%20variable%20explicitly,declare%20it%20implicitly%20for%20you.) below:
**A-1**
![Diagram for Lexical Scope, Scope Chain, and Varaible Lookup](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/p7o7bjvsc1i3m3gx0pm4.png)

These words may look intimidating but *trust me*, these definitions for the most part are easy to understand. 

####Lexical Scope

[*Lexical scope*](https://www.freecodecamp.org/news/javascript-lexical-scope-tutorial/) means that the variable is scoped in the place where the code was created. In diagram **A-1** above, you can see that each of the variables is colored in a different shade of gray. This signifies that each variable is scoped in the block/function it was created.

####Scope Chain

The next topic diagram **A-1** is referring to is the [*scope chain*](https://www.geeksforgeeks.org/explain-scope-and-scope-chain-in-javascript/). This comes back to the reverse waterfall I mentioned earlier. `function g()` has access to all the variables up the scope chain: `function f()` and global object `var x=1`. But the reverse isn’t true. The global object `var x=1` cannot access `function f()` or `function g()`.

The next topic diagram **A-1** is referring to is [*variable lookup*](https://www.toptal.com/javascript/javascript-prototypes-scopes-and-performance-what-you-need-to-know). It displays how the computer is working in reference to the scope chain. It will search for the declared variable (or object in this case) up the scope chain until it finds a match. Once a match is found the computer will get the value that was assigned to the variable in that particular scope.

[Lexical Scope - reference](https://www.educative.io/answers/lexical-scope-in-javascript)
![Diagram of Lexical Scope in JavaScript](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7qq53lc1kpgc9bxxx24q.png)

[Scope Chain - reference](https://www.toptal.com/javascript/javascript-prototypes-scopes-and-performance-what-you-need-to-know)
![Scope Chain Diagram](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kpfqgcy8r9tpwqier1z7.png)

[Varaible Lookup - reference](https://github.com/learn-co-curriculum/phase-0-pac-1-the-variable-lookup-expression)
![Flatiron's diagram on variable lookup](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qj80lzhmr9zy0dzu2t2d.png)

In conclusion, you should **always** declare your variables using `const`, `let` or `var` in JavaScript. Even though the language will **implicitly** declare them for you, this can lead to **unpredictable behavior** and create **errors** that are extremely **difficult to detect**. JavaScript will treat undeclared variables as global variables which can unintentionally be changed in the future. On topics discussing scoping, **lexical scope** refers to the place in which your variable/object was created. Additionally, lexical scope works in conjunction with the scope chain. We know that the **scope chain** is like a reverse waterfall, where the **bottom** of the chain **has access** to the **entire scope chain** but the **top does not**. We learned how the computer will search for the declared variable up the scope chain until a match is found through **variable lookup**. 

For more information on variable declaration check out [w3schools](https://www.w3schools.com/js/js_variables.asp).
 
Oh and for my TLDR people:
###ALWAYS DECLARE YOUR VARIABLES!

---

##References:
1. https://www.w3schools.com/js/js_variables.asp
2. https://www.w3schools.com/js/js_es6.asp
3. https://medium.com/javascript-scene/javascript-es6-var-let-or-const-ba58b8dcde75
4. https://www.oreilly.com/library/view/javascript-the-definitive/0596101996/ch04.html#:~:text=If%20you%20don%C3%A2%E2%82%AC%E2%84%A2t%20declare%20a%20variable%20explicitly,declare%20it%20implicitly%20for%20you.
5. https://www.codecademy.com/learn/introduction-to-javascript/modules/learn-javascript-scope/cheatsheet
6. https://www.freecodecamp.org/news/deep-dive-into-scope-chains-and-closures-21ee18b71dd9/
7. https://www.toptal.com/javascript/javascript-prototypes-scopes-and-performance-what-you-need-to-know
8. https://www.educative.io/answers/lexical-scope-in-javascript
9. https://www.toptal.com/javascript/javascript-prototypes-scopes-and-performance-what-you-need-to-know
10. https://github.com/learn-co-curriculum/phase-0-pac-1-the-variable-lookup-expression
11. https://javascript.plainenglish.io/4-reasons-why-var-is-considered-obsolete-in-modern-javascript-a30296b5f08f