JavaScript Fundamentals: Variables and Hoisting

Today I’m going to cover a few different kinds of variables in JavaScript. We have three types of variables to choose from when declaring: var, let, and const. In this article, I’ll be doing a quick comparison of the three and working in the term hoisting as well.

What is Hoisting?

Hoisting is JavaScript’s default behavior of moving all variable declarations to the top of the current scope or function. In order to truly grasp the concept, we need to understand the difference between variable declaration and variable initialization.

var x;
console.log(x);
x = "Hello";
//////////////////console.log(x);
var x = "Hello";
x = "Hello";
console.log(x);
var x;
var x = "Hello";
console.log(x);
let x;
console.log(x)
x = 'Hello";

Var vs. Let

Scope

Any variable declared using the old variable type var is defined in global scope or function scope. A simple example:

var x = 5;function scopeExample() {
var y = 6;
console.log(x, y);
}
console.log(x, y);
let y = 5;{
var x = 5;
let y = 6;
console.log(x, y);
}
console.log(x, y);

Reassignments & Redeclarations

When using var, you can reassign or redeclare that variable wherever in the program:

var x = 5;
{
var x = 6;
}
console.log(x);
let x = 5;
let x = 6;
// this code will break
let x = 5;
x = 6;
// this is perfectly fine
var x = 5;
let x = 6;
// this code will break
var i = 10;for (var i = 0; i < 12; i++) {
console.log(i);
}
console.log(i);
let i = 10;for (let i = 0; i < 12; i++) {
console.log(i);
}
console.log(i);

Let vs. Const

In the above section, for the most part, you can substitute const for let and it would remain true. Const is bound to block scope while var is not.

const x = 6;
// this is right
const x;
// this will break
const x = 5;
x = 6;
// this will break
const x = 5;
const x = 6;
// this will also break
const x = 5;
{
const x = 6;
}
// this will not break as its technically two different variables
const pets = ["cat", "dog", "bird"];
pets.push("fish");
// pets #=> ["cat", "dog", "bird", "fish"]
pets[0] = "hamster"
// pets #=> ["hamster", "dog", "bird", "fish"]
pets.pop();
// pets #=> ["hamster", "dog", "bird"]
const dev = {name: "Cody", experience: "Junior"}dev.experience = "Senior";
// properties can be reassigned
dev.fatigue = "low";
// properties can be added
// dev #=> {name: "Cody", experience: "Senior", fatigue: "low"}

Conclusion

I hope this was informative and helped you grasp the complexities between JavaScript’s different variables. Thank you for reading and happy coding!

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store