JavaScript Intro: Variable Declarations

Zak Frisch
WDstack
Published in
7 min readDec 14, 2017

How to make variables with let, const, and var

“Hey Again! It’s your boi ZF come down from the high mountains geared up and ready to Sherpa. I’m here to drop some sick brain expanding knowledge. Get ready for an intellectual roller coaster to get that brain swole brutha.”

…is what I would say if my nickname was Beach Muscles and I only wore backwards flat-brimmed hats and wayfarers(for some reason), but hey, we’re going to learn about JavaScript Variable Declarations and their differences today so if you’re just starting out with JavaScript or need a refresher this article will aim to help you out!

Ready to Learn!

Variables

Variables in JavaScript have been traditionally declared using a single keyword. That keyword isvar :

var a; //create variable a
var b; //create variable b
var c; //create variable c

It used to be about as simple to create a variable in JavaScript as you could get it. No options meant no guesswork. You want a variable? ka-pow! You got it.

var whatever; 
var whoever;
var wherever;

The only thing that needed to concern you was the name of the variable and that was a very small hurdle(don’t use spaces/don’t begin with a number/decide on naming conventions probably/ etc.)

So why then, in the last few years, were the keywords let and const added to JavaScript as an alternative to var? What functionality do they provide that var doesn’t offer?

The very ambiguous sign raises a good question

let and var

If you look up “Variable Declarations in JavaScript” you’re likely to come across A Re-Introduction to JavaScript on the Mozilla Developer Network(MDN).

This article gives a lot of great information and I’ll link to it in the Resources section below as well. Even though it is worthwhile to read, the explanations of variable declaratives may seem too technical for the average person or someone just getting into JavaScript. Examples of this are the following:

let allows you to declare block-level variables. The declared variable is available from the block it is enclosed in.

and

var is the most common declarative keyword… This is because it was traditionally the only way to declare a variable in JavaScript. A variable declared with the var keyword is available from the function it is declared in.

Try as you might it is a bit much to wrap your head around. Now, I’m not trashing the author here (because as it would happen, I helped write this article) but there’s a lot of mentioning of blocks and block-level and things being available from the function they are declared in — what does all that mean to the uninitiated?

To break it down simply let and var are almost identical. In fact they are so closely aligned in function that you are encouraged more often than not to simply use let instead of var .

let a; //create variable a
let b; //create variable b
let c; //create variable c

But what is the difference?”

In Technical Terms: Their scopes are different.
In Layman’s Terms: If you use let that variable is only visible between the braces { } of the code it’s used in. If you use var that variable may be visible within and outside of the braces { } it’s used in.

I know, I know, saying “may be visible” is a bit confusing when you’re trying to solidify a concept in your head. It may be visible outside a block( code between braces { } ) if that block is not a function.

This will not allow a to be visible outside of the function call:

(function() {
var a = "a";
}()); //create anonymous function and invoke it immediately.
console.log(a);
// throws error a is not declared

This code will allow a to be visible outside of a for-loop block:

for(var i = 0; i < 1; i++) {
var a = "a";
}
console.log(a); // "a"

So again, using var means that a variable will be visible outside of a block of code if that block is not, itself, a function. Really this example is the gist of the difference. The fact is that 99% of the reason to use let lay within for-loops.

An example of a for-loop usinglet:

for (let i = 0; i < 5; i++) {
// i is only visible in here
console.log(i);
}
// 1...2...3...4
console.log(i);
// throws error "i is not declared"

An example of for-loop using var:

for (var i = 0; i < 5; i++) { 
// i is visible in here
console.log(i);
}
// 1...2...3...4
// i is visible out here
console.log(i);
// 5

The difference is the availability of the variable outside of the for-loop block. Aside from specifically the above situation let and var function the same, so much so that they are interchangeable in every instance but the one. It’s pretty well considered that in time let will phase out var entirely.

const

const allows you to declare variables whose values are never intended to change. Like let , the const variable is available from the block(code between braces { } ) it is declared in.

One thing to keep in mind, const stands for constant. This means that once a variable is set it will persist as that value and you can’t change it.

An example of constinability to change:

const Pi = 3.14; // variable Pi is set 
Pi = 1; // will throw an error because you cannot change a constant variable.

That being the case you can’t declare a constant variable and not define it’s initial value at the same time. You only get to define it the once and if you don’t that variable would have a permanent value of undefined — which would be pretty useless, right? Because of this the Browser will typically throw a Type Error if it detects this being done.

Example:

const a; // a is undefined forever. Throws Error.
const b; // b is undefined forever. Throws Error.
const c = "cat"; // c is defined as "cat" forever

As you can imagine you should only use const for values you are positive will not need to be changed in the future. This is particularly useful for instances where you might be working in tandem with other Developers and you know that certain values must never be altered, accidentally or otherwise.

But there are exceptions when it comes to Objects and Arrays.

const and Objects

In the above section about const you may have come to the conclusion that anything declared as a constant is immutable(immutable simply means that the data cannot, under any circumstances, be changed). I’m here to tell your assumption is incorrect. The caveat is declaring const objects and arrays.

const obj = {
property: "property",
property2: "property2"
}

The above declares an object using const underneath the variable obj.
This is all well and good. Certainly we can’t do the following and alter the variable obj:

const obj = {
property: "property",
property2: "property2"
}
obj = {
blah: "blah blah",
blah2: "blah blah blah"
} // throws error assignment to constant variable

However, though we can’t change obj through direct assignment, we can alter it through property/method assignment. This means we can assign to all of obj ‘s child properties and methods(and even delete them) by being more specific instead of trying to cram everything into obj at once:

const obj = {
property: "property",
property2: "property2"
}
delete obj.property; // remove property
delete obj.property2; // remove property2
obj.blah = "blah blah"; // add blah
obj.blah2 = "blah blah blah" // add blah2

This does mean that const doesn’t make a variable immutable/unchangeable, at least not always. If you’re interested(for whatever reason) in total immutability you can always look into using the freeze or seal object methods. I’ll also put links to some good helper articles and Stack Overflow questions in the Resources section.

const and Arrays

Arrays are also immutable as defined by their type. The Array stored within a variable is a reference to where data can be found, not the data itself.

This allow for the following Array to be changed after its declaration:

const arr = ["hi", "hola"];
arr[0] = "blue";
console.log(arr); // ["blue", "hola"]

I’ll also put links to some good helper articles and Stack Overflow questions in the Resources section.

--

--