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 not available in the global scope. Great! So now we know that variables declared with var are scoped within the function (with the global namespace essentially being one big function) they were declared in.

Variables declared with the var keyword are function-scoped. When they are declared in the global namespace, they are scoped globally.

Okee-dokee. Just so we’re clear on this whole “scoping thing”, let’s just make sure that something declared in the global namespace is actually scoped globally.

var name = ‘Todd’;function someFunction() {
console.log(name); // Output: Todd
}
someFunction();
// Output: Todd

Awesome! Just what we wanted. By declaring the variable name in the global namespace and using the var keyword to do so (try saying that ten times fast with marbles in your mouth) when we logged the value of name to the console…

--

--

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.