+ 2

Is there a difference between "let" and "var" in JS?

I'm not quite sure if there is some difference in functions with let and var declaring a variable... pls help

8th Oct 2017, 1:46 PM
Aleksa Ivanovic
5 Respostas
+ 7
Var : 1. Old 2. Function scoped 3. Hoisted 4. In global scope its added to window/global object. 5. supports redeclaaration Let: 1. Newer came in 2015 (ES6) 2. Block scoped 3. Not hoisted 4. Its not added like var to global objects 5. throws error during redeclaration 2 and 3 are important to know, hoisting being a bit confusing but explained in code below https://code.sololearn.com/WdGAFeNRAe9M/?ref=app https://code.sololearn.com/WiHHHOb3qp8W/?ref=app
19th Sep 2018, 5:36 PM
Morpheus
Morpheus - avatar
+ 3
The let statement declares a block scope local variable, optionally initializing it to a value. let allows you to declare variables that are limited in scope to the block, statement, or expression on which it is used. This is unlike the var keyword, which defines a variable globally, or locally to an entire function regardless of block scope. example code with output in the comments: function varTest() { var x = 1; if (true) { var x = 2; // same variable! console.log(x); // 2 } console.log(x); // 2 } function letTest() { let x = 1; if (true) { let x = 2; // different variable console.log(x); // 2 } console.log(x); // 1 } [source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let]
8th Oct 2017, 1:53 PM
Chrizzhigh
Chrizzhigh - avatar
+ 1
@Chrizzhigh so the only difference there is in scoping?
8th Oct 2017, 1:55 PM
Aleksa Ivanovic
+ 1
so far i have not read anything else ... but maybe someone else can correct me if i am wrong =)
8th Oct 2017, 2:02 PM
Chrizzhigh
Chrizzhigh - avatar
0
sure thing 😂
8th Oct 2017, 2:51 PM
Aleksa Ivanovic