This post will be the first of a large series of small posts that will cover some questions you are likely to come across during your job interviews.
I'll be more focused on JavaScript but there will be some posts about HTML , CSS and React JS in the future !
Ok , let's get started !
Difference nr 1!
"var" was introduced in JavaScript from the beginning while "let" was introduced in ES2015/ES6.
Difference n 2!
"Let" has a block scope while "var" as a function scope
Let's see this example
let x = function() {
if(true) {
var v = 2;
let l = 1;
}
console.log(v);
--> 2
console.log(l);
--> Uncaught Reference: l is not defined
}
x();
The console.log of the variable v will return 2 because of the function scope of the "var" keyword while the l variable will return an error because of the block scope of the "let" keyword.
Difference n 3!
Variables defined with "var" gets hoisted at the top of his function while variables defined with "let" don't get hoisted.
let x = function() {
if(true) {
console.log(v);
--> undefined
console.log(l);
--> Uncaught Reference: l is not defined
var v = 2;
let l = 1;
}
}
x();
In this case the variable v will return undefined while the l variable will return an error, this happens because declarations using var are hoisted / lifted to the top of their functional/local scope (if declared inside a function) or to the top of their global scope (if declared outside of a function) regardless of where the actual declaration has been made.
That's it ! nothing too complicated but it's important to keep these concepts fresh in your minds.
See you soon for more tips !
Top comments (9)
An important thing to note is that there are no good reasons for using
var
overlet
.let
is whatvar
should have been all along to not be confusing.So forget about
var
and just uselet
(or even better, useconst
) 😉Absolutely , this is a es5 question , today ill post the es6 version the differences between let and const
and 2 more thing
Unless the value is a primitive ;) You are correct if it's an Object (as stated in your example), just think that should be clarified.
In the article I'm only talking about the differences in "var" and "let" not in const !
We can read in MDN that let and const are actually hoisted.
Furthermore in ecma-international it is writtten that:
True, but in the article I'm talking about var and let .
I understand :) but personally I cannot agree with this sentence
However I like your series of a small posts. Keep going ! :)
clap clap medium