Variables in programming are named memory locations that store data. This said data can be retrieved for later user via the name. Some programming languages allow you to assign the same name to another variables and others strictly forbid this.
The programming languages that allow the reassignment of the same variable name to another data are called loosely typed languages others that forbid this are called strongly typed languages.
All screenshots are from Firefox 71.0 and its Developer Tools. One particular feature in Firefox 71.0 that's worthy of mention is the multi-line code editor in the console.
They literally do the same thing but with some huge differences.
Variables declared with the
Now, you might wonder why i said the
var keyword is a "traditional" way, that's because of its behavior. And prior to ES6 (ES2015) the
let keyword was introduced in ES6 to solve some of the issues that arise when using variables declared with
var. We'll talk about
The question you might ask is: What behavior are you talking about?
Let's talk about it briefly and we'll provide an additional learning resource if you decide to go deep and learn this further.
Hoisting means regardless of where a variable is declared, it is moved to the top of the scope in which it is defined.
That's the basic definition. Let's see some code.
Take a look at the image below. We called variable
a before declaring it but due to hoisting the variable still get the value
10 after the code is executed.
Mind you i have docked the Developer Tools into a separate window. If you've followed this series up to this point i believe you should be able to do this.
This is just a basic example and its enough to get you started.
This particular hoisting behavior also applied to functions as we'll see later in the series.
If you will like to take a deep dive into hoisting, please read the following post by lydia hallie.
let keyword was introduced in ES6 (ES2015). Any variable declared with the
let keyword cannot be called before being created.
We'll revisit our previous example by changing
When the code is executed you will get an error stating
ReferenceError: can't access lexical declaration 'a' before initialization.
But, in the source code after the variable is declared with
let you can assign another value then the code will execute just fine.
const on the other does not allow this.
const keyword was introduced in ES6 (ES2015) alongside
let and unlike
let you cannot assign another value to a variable declared with
If you try to assign another value to a variable declared with
const you will get an
invalid assignment Type error.
Up next, Arrays.