DEV Community

Cover image for JS interview in 2 minutes / var ⚔️ let ⚔️ const
Nick K
Nick K

Posted on • Updated on

JS interview in 2 minutes / var ⚔️ let ⚔️ const

Question:
What are the differences between declaring variables using var, let and const?

✨ Bonus: What is hoisting?

Quick answer:
These are a few ways to declare variables. var is a legacy one, let and const are new ones, where let is for mutable variable reference and const is for immutable reference.

Hoisting is when you use a variable before you define it.

Longer answer:
Let's start with var. Syntax is kind of straightforward.

var x = 1, y = 2;
console.log(x, y) // 1, 2
Enter fullscreen mode Exit fullscreen mode

As you may guess, it is legacy for some reason. And you were right, there are even a few reasons.

For example, var declaration happens before any code execution, so you can basically use a variable in code and declare it later.

x = 2
var y = x + 1
console.log(y) // 3
var x;
Enter fullscreen mode Exit fullscreen mode

It is totally weird and tricky from my point of view, because only variable definition comes before the execution, but not initialization.

var y = x + 1
console.log(x) // undefined
console.log(y) // NaN
var x = 2;
Enter fullscreen mode Exit fullscreen mode

So, when you use variable before definition is called hoisting ✨ (Don't use that. Really.)

upd: hoisting is actually can be useful with function declarations, e.g. recursive functions. Take a look on this comment https://dev.to/lowla/comment/1m48f

The real issue with var is its scope. var declare variable for the current function scope, but not for the block scope. Here.

for (var i = 0; i < 5; i++) {
  setTimeout(() => console.log(i))
}
Enter fullscreen mode Exit fullscreen mode

Guess what. The output is 5,5,5,5,5.

🤯🤯🤯

Ok, ok, that was dark times, and you are safe now (almost).

let and const come into play. They will work exactly as you would expect (almost). Back to the previous example.

// Notice let
for (let i = 0; i < 5; i++) {
  setTimeout(() => console.log(i))
}
Enter fullscreen mode Exit fullscreen mode

The output is ok, it is 0,1,2,3,4.

So, what is the difference between let and const? Basically, let is for the variables you want to be able to update and const is for static ones.

The "almost" issue I've mentioned before is that when you use const the value isn't changeable only for some primitive types like numbers.

let a = 1
a = 2 // 👌

const b = 1
b = 2 // Error: Assignment to constant variable.
Enter fullscreen mode Exit fullscreen mode

But const doesn't make complex types as arrays or objects immutable.

const y = [1]
y.push(2) // 👌
console.log(y) // [1,2]
Enter fullscreen mode Exit fullscreen mode

🤷 Life is strange, yeah 🤷

Real-life applications:

So as for real life applications, there is a useful destructive assignment.

let [a, b] = [1,2,3]
console.log(a, b) // 1, 2

let [c, ...d] = [1,2,3]
console.log(c, d) // 1, [2,3]

let { e, f } = { a: 1, e: 2, f: 3 }
console.log(e, f) // 2, 3

let { g, ...h } = { a: 1, g: 2 }
console.log(g, h) // 2, { a: 1 } 
Enter fullscreen mode Exit fullscreen mode

There is an especially useful case, when you need to remove some field.

let { password, ...safeUser } = user
return safeUser 
Enter fullscreen mode Exit fullscreen mode

Another real-life tip is not to mutate any array or object, but it is a bit out of scope of this article.

Resources:
MDN/var
MDN/let
MDN/const

Other posts:


Btw, I will post more fun stuff here and on Twitter. Let's be friends 👋

Top comments (9)

Collapse
 
lowla profile image
Laureline Paris • Edited

Hi there 🙌
I do not agree with how you define hoisting even though it’s not entirely false.
I would have say « you encounter hoisting problematic when you call a variable before it’s assignations »
But hoisting perse is how javascript handle your code and how it would read it - which leads to : it’s insightful to understand how javascript works .
When reading one’s code Javascript has hidden process which includes hoisting.
Hoisting is the fact that javascript reads your file and before executing your lines it hoists your variable and function ( meaning that it keeps the the variables declaration, without their value, and functions on « top of the file » before processing to any logic

Common cases are when one calls either a function ( with function keyword ) or variable with the « var » ’ keyword - indeed - before their definitions. :)

Then this was exactly why let and const were created in order to have a better control of those - ( good to know ) knowing that non mutable objects prevents from memory allocation loss in any programming language

[ edit ] Here is a the doc to which we can understand the arguments I have above regarding the def of hoisting developer.mozilla.org/en-US/docs/G...

Collapse
 
hexnickk profile image
Nick K

Thanks! I actually didn't realise that hoisitng can be useful with function declaration. Let me just add an update pointing to your comment. Thanks again!

Collapse
 
pelayomendez profile image
Pelayo Méndez

Actually when you do this:
x = 2
You are declaring the variable.

That's why:
x = 2
var y = x + 1
console.log(y) // 3

Collapse
 
pelayomendez profile image
Pelayo Méndez • Edited

Maybe something like this will help to understand better your point:

console.log(x) // undefined
x = 2
var y = x + 1
console.log(y) // 3
var x;

console.log(x) // error
x = 2
var y = x + 1
console.log(y)

I came back over and over to this topic and always find new thigs ;)

Collapse
 
hexnickk profile image
Nick K

I came back over and over to this topic and always find new thigs ;)

yeah, some part of JS is so confusing 🤷 Thanks for a detailed example!

Collapse
 
dylanesque profile image
Michael Caveney

I would argue that knowledge of hoisting isn't a "bonus" for this topic, since it's a major part of the difference between var and const/let.

Collapse
 
hexnickk profile image
Nick K

Yeah, this actually makes sense 👍

I need to come up with a new structure for posts covering multiple related questions.

Collapse
 
whimsyniche profile image
Victor D

I literally had this JS question asked to me about the const, let, var 😂
Perfect and what a coincidence

Collapse
 
hexnickk profile image
Nick K

wow, hope this article helped :)