DEV Community

Jesse Ilc
Jesse Ilc

Posted on

Declaring variables in JavaScript (What happens when you don’t)

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

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 but these are just to name a few. Let’s see an example on how declaring variables work:

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

console.log(number1) 
// 25
console.log(number2) 
// 50
console.log(number3) 
// 75
Enter fullscreen mode Exit fullscreen mode

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:

number = 25

console.log(number)
// 25
Enter fullscreen mode Exit fullscreen mode

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

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 in JavaScript, it will declare it for you implicitly.

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:

number = 25
console.log(number)
// 25
number = 50
console.log(number)
// 50
Enter fullscreen mode Exit fullscreen mode

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.

Scope

“a concept that refers to where values and functions can be accessed”

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

let number = "global"

function test(){
    let number = "local"
    console.log(number)
}
test()
// local 
console.log(number)
// global
Enter fullscreen mode Exit fullscreen mode
let number = "global"

function test(){
    var number = "local"
    console.log(number)
}
test()
// local 
console.log(number)
// global
Enter fullscreen mode Exit fullscreen mode
let number = "global"

function test(){
    number = "local"
    console.log(number)
}
test()
// local 
console.log(number)
// local
Enter fullscreen mode Exit fullscreen mode

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 scoped variable equal to 10 and a function (local) 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. 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 below:
A-1
Diagram for Lexical Scope, Scope Chain, and Varaible Lookup

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

Lexical Scope

Lexical scope 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. 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. 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
Diagram of Lexical Scope in JavaScript

Scope Chain - reference
Scope Chain Diagram

Varaible Lookup - reference
Flatiron's diagram on variable lookup

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.

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

Top comments (1)

Collapse
 
fruntend profile image
fruntend

Сongratulations 🥳! Your article hit the top posts for the week - dev.to/fruntend/top-10-posts-for-f...
Keep it up 👍