r/learnjavascript • • Oct 22 '21

Difference between var, let and const.

Post image
430 Upvotes

49 comments sorted by

3

u/SepehrU Oct 23 '21

What do you mean by "redeclareable"? Does it really differ with "reassignable" since in JavaScript variable are dynamic type and only thing you can do is just change their values?!

2

u/codedblood Oct 23 '21

checkout this useful doc var

2

u/SepehrU Oct 23 '21

I'm just really curious now... 🤔

110

u/ex-igne-vita Oct 22 '21

var is not "global scoped" unless it's declared in the global scope... and if let or const are declared in the global scope then they're "global scoped" too.

If you want a variable to be global scoped, don't declare it at all, just define it.

30

u/ISlicedI Oct 22 '21

I got very confused by this, thanks for calling it out. Btw I've done 8 years of JavaScript and was doubting myself here.

8

u/ManInBlack829 Oct 23 '21

Hopefully because you never use global variables and this just never comes up, right?

1

u/[deleted] Oct 23 '21

Don’t think I’ve ever used global scoped variables tbh. Interesting.

4

u/senocular Oct 23 '21

If you want a variable to be global scoped, don't declare it at all, just define it.

Without a declaration, this will throw an error in strict mode unless you qualify with the global object

"use strict"
myVar = 1 // Error
globalThis.myVar = 1 // OK

In the global scope, var actually provides benefit because it will also prevent shadowing by other global let and const declarations, something you don't get when omitting the declaration (sloppy mode) or assigning to the global object directly

// in global
myGlobal = 1
// ...
let myGlobal = 2 
console.log(myGlobal) // 2 :(

vs

// in global
var myGlobal = 1
// ...
let myGlobal = 2 // Error
console.log(myGlobal) // 1 :)

2

u/justhereforlife Oct 22 '21

To add on to your point, if you omit the var (assuming not in strict mode) won't a global scoped variable be created? I don't believe the same is true of let/const. Could that be what the graphic is trying to convey?

Question marks because Im not certain if what I'm saying is actually the case haha

5

u/elisecode247 Oct 22 '21

Yes, an undeclared variable is added to the global context.

function testVariableScope() {
    undeclaredVariable = "this is global";
}
testVariableScope(); 
console.log(undeclaredVariable); // "this is global";

4

u/mareksl Oct 22 '21

Well, if you omit the var, what will be the difference between that and omitting the let/const?

2

u/ex-igne-vita Oct 23 '21

Var/let/const declare a variable. Putting an equals sign and a value to the right of a variable defines the variable. These are often both done in the same statement, but they don’t have to be. You can declare a variable without defining it, and you can define a variable without declaring it, which does in deed create a global variable on the window object, which is what I was talking about in my last sentence.

2

u/ZergistRush Oct 23 '21

"I don't think the same is true for let and const" how can you tell them apart if you omit let and const, just like var? 🤣

30

u/zerik100 Oct 22 '21

tldr; never use var and if you think your code requires var then there's something wrong with your code

31

u/dada_ Oct 23 '21

I recommend you always use const by default, and fall back to let only when it's genuinely useful or necessary.

Why? Because not reassigning variables makes your code easier to reason about. If something is a const, you can be sure it will always have the same variable associated with it, whereas let will point to a different variable depending on when you're reading it.

Personally I'd say my code is probably like 97% const, and 3% let. var is absolutely never needed.

7

u/zerik100 Oct 23 '21

yeah const is by far my most used declaration keyword. i use let very rarely and even when i do i often refactor my code later to use const instead.

2

u/Drugba Oct 23 '21

Never is a strong word. Not sure I agree.

The most obvious need for var that I can think of is to deal with older browsers where you aren't compiling your code.

Ignoring that though, I think it's important to note to any newer devs that, while someone should probably use let and const for any new code they write, it doesn't mean that they can just switch all vars in an existing code base to be let or const and have things work (we had a junior try this in an attempt to clean up technical debt). The lack of hoisting and scope differences mean they're not a drop in replacement for each other. Code using var that was "not ideal, but not wrong" can actually be broken by using let.

-11

u/LucVolders Oct 23 '21 edited Oct 23 '21

Undoubdly unpopular opinion:

Use var, declare your vars global at the beginning of your script and document and track them well. Otherwise you are a lazy programmer. Nothing wrong with var.

3

u/robotomatic Oct 23 '21

Please NEVER follow this advice. What is described here is the height of laziness. Scope your variables appropriately, default to const and only use let where needed. Save yourself a ton of trouble. Don't be like this guy. Just don't.

-2

u/Tintin_Quarentino Oct 23 '21

Seconded. Although I do like the thinking of "always use const, followed by let, followed by var".

21

u/voyotv Oct 22 '21

All of them are hoisted, but let and const are uninitialized until the line they are executed.

1

u/theDreamingStar Oct 23 '21

And hence, the Temporal Dead Zone.

3

u/great_site_not Oct 23 '21

The single most "sounds cooler than it is" feature of JavaScript!

-6

u/tehciolo Oct 23 '21

None of them are hoisted. There is no such thing as hoisting.

5

u/segafrompk Oct 23 '21

Hoisting is just a term to explain in simple words how the js engine works. But you're right, there's no hoisting, it's just easier to explain it like that then to explain the real way memory is reserved for variables

3

u/tehciolo Oct 23 '21

It may be an easier concept to grasp, but it is entirely false, which I think creates quite a bit of unnecessary confusion.

2

u/shuckster Oct 23 '21

It's an analogy, and any analogy can be picked apart until it no longer makes sense. Hoisting is a perfectly reasonable jumping-off point to explain the behaviour.

For example, you know exactly what I mean when I say "jumping-off point". But in preparing to explain hoisting, I'm not worrying about being securely tied to a bungie or parachute, or if there's any water over the precipice, and if so, whether or not it's deep enough to make my fall survivable.

1

u/tehciolo Oct 23 '21

Analogies are very useful, surely.

I just happen to believe that this one creates more confusion than it solves.

I am totally aware this is an unpopular opinion, and I am fine with that.

1

u/shuckster Oct 23 '21

Not sure if it’s so unpopular. I’ve heard Kyle Simpson say something similar, but in the context of teaching advanced concepts, which is exactly at the point where it’s appropriate to pull apart the analogy.

7

u/alexey_st0 Oct 23 '21

Is there anybody who's still using var instead of let and const ?

5

u/yoitsericc Oct 23 '21

Let is not function scoped. It is block scoped - most functions just happen to be within a block.

This thing is a bit redundant.

3

u/SepehrU Oct 23 '21

Thanks for your quick and clear response. So that's literally redeclaration. I thought you can just do that once and since then you can just reassign it

1

u/AKcenty Nov 18 '21

so use var unless you know what you're doing

-5

u/dbor15 Oct 23 '21

I honestly only use var when doing anything. I don't know if it's making my life worse or not, but it works good enough.

-3

u/alexey_st0 Oct 23 '21

How var can be hoisted? If I'm not mistaken, only var declaration can be hoisted but initialization must be before its usage? Like this:

a = 2

console.log(a)

var a

4

u/inabahare Oct 23 '21 edited Oct 23 '21

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var#description

var declarations, wherever they occur, are processed before any code is executed. This is called hoisting, and is discussed further below.

0

u/[deleted] Oct 22 '21

[deleted]

5

u/senocular Oct 23 '21

var, let, and const declarations are all hoisted. The difference is var declarations are hoisted and initialized to undefined whereas let and const declarations are hoisted uninitialized. This means you can access var variables before their declarations and get undefined but attempting to do so with let or const variables means you'll get an error.

3

u/inabahare Oct 23 '21
console.log(a);

{
    var a = 1;
}

console.log(a);

If you change that to let or const you will get an error on the first line, because a isn't defined. If you remove the first log you'd still get an error saying a isn't defined if you use var

1

u/rados_a51 Oct 23 '21

I think that it will not throw up errors if you do something like this:
console.log(b);
var b = "test";

0

u/[deleted] Oct 22 '21

[deleted]

3

u/Shakespeare-Bot Oct 22 '21

Yikes, so much incorrect info hither. Others has't already did comment


I am a bot and I swapp'd some of thy words with Shakespeare words.

Commands: !ShakespeareInsult, !fordo, !optout

1

u/bot-killer-001 Oct 22 '21

Shakespeare-Bot, thou hast been voted most annoying bot on Reddit. I am exhorting all mods to ban thee and thy useless rhetoric so that we shall not be blotted with thy presence any longer.

18

u/[deleted] Oct 22 '21

[removed] — view removed comment

10

u/[deleted] Oct 22 '21

This is the only important thing to know about var. There's a reason that let and const were introduced. You don't need var anymore and you shouldn't be using it.

-8

u/pxldgn Oct 23 '21

yes, there is a reason - and that is absolutely nothing to do with replacing var. ;)

these were introduced to fix the closure in loop issue.

5

u/[deleted] Oct 23 '21

Yes, the loop issue that was due to var being function scoped instead of block scoped. So let was introduce to replace var.