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.

35 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?

4 Likes
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 .

2 Likes

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.

7 Likes

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.

1 Like

You might find this article an interesting read…

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

4 Likes

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.

6 Likes

That was pretty interesting. Thanks for the link.

1 Like

With let x = ‘test’ you have already assigned the value to ‘x’ once. Thus, the variable name has already been defined in the system and cannot be declared again.

It’s like giving the same variable name 2 values and confusing the system which one to pick. Hope it helps.

2 Likes

The let keyword was introduced in ES6 (a version of JavaScript announced in 2015) and is basically an improved version of the var keyword. Variables declared with var are function scoped while variables declared with let are block scoped.

This means that variables declared with var are only accessible within their containing functions and their child functions:

function foo() {
  var x = 1;

  function bar() {
    console.log(x); // 1
  }

  bar();

  console.log(x); // 1
}

foo();
console.log(x); // ReferenceError: x is not defined

and variables declared with let are only accessible within their containing block and their child blocks:

if (condition) {
  let x = 1;
  
  if (condition) {
    console.log(x); // 1
  }

  console.log(x); // 1
}

console.log(x); // ReferenceError: x is not defined

The reason let was introduced in ES6 was because function scope was confusing and error-prone.

When creating a variable with the var keyword, it will become a property of the window object, but when creating a variable with the let keyword it will not be a property of the window object

var x = 1;
let y = 1;

console.log(window.x); // 1
console.log(window.y); // undefined

There are some other slight differences such as hoisting and closures but these are the main differences

So basically, let is an improved version of var. Most of the times, you would use let

7 Likes

I saw scope word when compare let and ver. But I don’t clearly understand what is scope?

Enter a classroom. Declare something. Only the people in that classroom will hear that declaration and have any knowledge of its expression.

That is scope. The environment where a variable is declared, also known as a namespace. If we write something on the blackboard in that classroom, it is confined to that blackboard. The classroom is akin to a namespace. It’s the place that inscription can be found.

That classroom is part of a wing which is part of a building which is part of a campus. Therein we have built a chain of various namespaces, known as the scope chain. It gets confusing when we try to venture to another classroom and see if we find that inscription on the board. Under scope chain architecture this would never happen. All those rooms are linked to the same link in the chain, the wing. We cannot traverse sideways on the scope chain, only upwards.

From the classroom we move up the chain to the wing, then to the building, then to the campus. Abstract, I know, but think on it.

5 Likes

how do i make the node,js output stay. It closes the second i open it

  1. Definition:

    1. Var - is old declaration method of variable
    2. Let - Recently (2015) introduced form of variable declaration
  2. Usage

    1. var - Mainly used to declare variables in Javascript programs.
    2. let - Same as var but provides additional functionlality of enforcing the block scope accessiblity.
  3. Declaration

    1. var - can be declared anywhere and the varaible is hoisted.
    2. let - can be declared anywhere and confined to block scope.
  4. Accessiblity

    1. var - Global access.
    2. let - Block scope access or lexical scoping
  5. Mode

    1. var - In strict mode, var allows a variable to be re-declared in same scope.
    2. let - let does not allow the re-declaration of the same variable again.
  6. Browser Support

    1. All browsers support var.
    2. Few browsers won’t support the let statement.
  7. Hoisting

    1. var - global vairables are hoisted
    2. let - Block scoped variables are actully not hoisted.
  8. Compatablity

    1. var - Supported by all browsers and JS runtime environments.
    2. let - Transpilers such as Babel can be used to convert it to older versions to provide support in all browsers.

    Conclusion

    The usage of var in JavaScript has a lot of space to errors during the execution of code. The var declaration’s global scope causes a decrease in the usage of the same identifier across different locations in the same class or file. This reduces the reusability of the code. The declaration of a variable using var behaves similarly to that of let but with the only difference of lexical scope across the code.

    The declaration of a variable using ‘let’ causes the variable to be accessed across the enclosed scope resulting in the identifier to be declared and used again outside the blocked statement or expression scope. Var can’t be replaced with let as it has its own usages across different scopes. Let should only be used where block scoping is of primary importance, and hoisting is not needed in the execution scope.

    Lexical Scope (static scoping) - defines how variable names are resolved in nested functions: inner functions contain the scope of parent functions even if the parent function has returned.

    var scope = "I am global";
    function whatismyscope(){
       var scope = "I am just a local";
       function func() {return scope;}
       return func;
    }
    
    whatismyscope()()
    
    

    The above code will return “I am just a local”. It will not return “I am a global”. Because the function func() counts where is was originally defined which is under the scope of function whatismyscope.

    It will not bother from whatever it is being called(the global scope/from within another function even), that’s why global scope value I am global will not be printed.

    This is called lexical scoping where “functions are executed using the scope chain that was in effect when they were defined” - according to JavaScript Definition Guide.

    Lexical scope is a very very powerful concept

    Hoisiting - Hoisting is JavaScript’s default behavior of moving all declarations to the top of the current scope (to the top of the current script or the current function).

    BUT WHY?

    Prior to ES2015, JavaScript supported only function level scoping unlike other languages like C++/Java which has block level scoping. With ES2015, in addition to function level scoping, JavaScript also supports block level scoping with the help of “let” and “const” keywords.

    But before we get into details of ES2015 stuff, let’s discuss what we exactly mean by phrases “function level scope” and “block level scope”.

    Put Simply:

    Let: Variables declared using ‘let’ keyword are similar to variables declared using ‘var’ keyword with just once difference. Variables declared using ‘let’ will have block scope and will not get hoisted to the starting of the function. So if we try to access those variables outside their block scope, we’ll get a reference error saying variable is not defined.

    Also variables declared with “let” keyword can be redefined but not redeclared.

This is a great question! Thanks for bringing it up!

I would approach as if I was doing something science-y. A constant is a value that never changes, like pi, the speed of light etc.

It would lock it in if you never needed to change it, and wanted to ensure you never ‘accidentally’ changed it while coding.

But you are correct, you could just use let

What is tripping you up here is the fact that var is hoisted in a different way than let or const. See: Hoisting - MDN Web Docs Glossary: Definitions of Web-related terms | MDN