Differences between "var" and "let" keywords?
(Source/Credits: https://dev.to/nunocpnp/differences-between-var-and-let-keywords-2b85)
This post will be the first of a large series of small posts that will cover some questions you are l...
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
```javascript 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.
```javascript 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 !
Comments section
anze3db
•May 1, 2024
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
) 😉nunocpnp Author
•May 1, 2024
Absolutely , this is a es5 question , today ill post the es6 version the differences between let and const
fantomx1
•May 1, 2024
clap clap medium
kendyl93
•May 1, 2024
We can read in MDN that let and const are actually hoisted.
Furthermore in ecma-international it is writtten that:
nunocpnp Author
•May 1, 2024
True, but in the article I'm talking about var and let .
edisonpappi
•May 1, 2024
and 2 more thing
nunocpnp Author
•May 1, 2024
In the article I'm only talking about the differences in "var" and "let" not in const !
jamesthomson
•May 1, 2024
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.