JavaScript: Understanding the difference between var, let and const

Todd Davis
7 min readFeb 28, 2019
Photo by Markus Spiske on Unsplash

If you’ve been coding in JavaScript for any length of time, you’ve probably typed the word var into your IDE so many times by now that you probably don’t even think about it anymore. It works, it’s easy, and unlike most strongly-typed languages, you don’t have to fret too much over considering what type of variable to declare. And that’s one of the beautiful things about JavaScript, it’s pretty smart.

JavaScript is notorious for its dangers however, and the var declaration is one of the key offenders in that battle. In order to better understand why var is such a creepy little bugger let’s take a look at how it works. Consider the following code:

var name = 'Todd';function someFunction() {
var greeting = 'Hi there!';
console.log(name); // Output: Todd
console.log(greeting); // Error: greeting is not defined

Simple enough, right? Our name variable prints out the value we assigned to it, while the greeting variable throws an error. Why the error for greeting? Because var’s scope is contained by the function it was declared in. In the case above, name is declared in the global scope, so when we get to the log() statement, it’s available for us. The greeting variable however was declared inside of a function, so its value is…



Todd Davis

This is my life. These are my words. If I choose to own my life story, then I can decide how the story ends.