What is the difference between `let` and `var` when declaring and what about reassigning?

So can I reassign variables using let just one time or several times?

I think it is a some kind of very confusing mistake there:

The var keyword is used in pre-ES6 versions of JS.
let is the preferred way to declare a variable when it can be reassigned,

Actually it is not true about the difference between let and var.
There’s a difference in scope, but not in reassignment. Reassigned could be variables declared by any non-const keyword. That’s the definition of variable. It can be reassigned by using assignment operator.

If they meant redeclared, it works only in strict mode and is just the polar opposite.

Redeclaration:
Assuming strict mode, var will let you re-declare the same variable in the same scope. On the other hand, let will not:

‘use strict’;
let me = ‘foo’;
let me = ‘bar’; // SyntaxError: Identifier ‘me’ has already been declared
‘use strict’;
var me = ‘foo’;
var me = ‘bar’; // No problem, me is replaced.

3 Likes

Just completed the Variable assignment, and decided to switch to the forum for some additional questions.

So, the keyword let is not replacing var, right? You are saying that even though the ‘purpose’ is the same, it alters when applying ‘use strict’ directive? And, if it’s not too much to ask (newbie question), when would I have to, or when should I, use the ‘use strict’ directive?

console.log(k);
const k="figure";

Error: Reference Error k is not defined

console.log(k);
let k="figure";

Error: Reference Error k is not defined

console.log(k);
var k="figure";

O/p:Undefined

Explain this phenomenon what’s the difference using let & const throwing error .using var code is executed .

I found an article:

https://www.geeksforgeeks.org/difference-between-var-and-let-in-javascript/

which shows an example similar to yours, but doesn’t explain it perfectly.

let and const where introduced in an update (es6, also know as emcascript 2015), and are an improvement.

the error is certainly better, if the program just continues with undefined, the program might crash later and its more difficult to debug, while if an error is thrown, you instantly know where the problem is.

1 Like

Everything made sense to me except one thing. Why would one use const in any situation when you could just use let?

Not only are you able to change the value of let but it does the same thing as const. Why not just use let all the time in case you do need to change it.

You might find this article an interesting read…

https://mathiasbynens.be/notes/es6-const

1 Like

What i dont understand is Let also cant be reassigned in the same scope.

let x = ‘test’;
let x = ’ test2’;

console.log (x) // SyntaxError: Identifier ‘x’ has already been declared

let x = ‘text’;
x = ‘text2’;

console.log (x); // test2

what is the difference here?

re-assigning and declaring a new variable with the same name, are two different things.