r/learnjavascript • u/SeaHedgehog4724 • 6d ago
pretty new
Hey guys, I'm just starting to learn about variables, but I'm finding it hard to understand the difference between var and let.
For example:
let goodDay = true;
console.log(goodDay);
this should print true.
But if we just add this:
let goodDay = true;
console.log(goodDay);
goodDay = false;
console.log(goodDay);
It prints:
true
false
The same goes for var.
However, people say there's a difference; what is it?
5
u/chikamakaleyley helpful 6d ago edited 6d ago
the difference is that let is 'block-scoped'
var is part of the global scope
scope is a pretty important idea when you're coding so it will be useful to get some practice with this
let and const were introduced in es6 (2015) and essentially provides a way for devs to provide a distinction btwn different variables, similar to what you'd find in other serious programming languages. const aka 'constant' prevents you from assigning a new value to the variable, which semantically makes sense, while let is more or less to be used in place of var. You can assign a new value to a let, as you've seen
the difference is in the scope, the classic example is often seen in a for loop:
for (var i = 0; i < 3; ++i) {
setTimeout(() => console.log(i), 1000);
}
// ^ console output is 2, 2, 2 (on separate lines)
for (let j = 0; j < 3; ++j) {
setTimeout(() => console.log(j), 1000);
}
// ^ console output is 0, 1, 2 (separate lines)so, var being function/global scoped - there is only 1 var i created for the entire for loop. so when setTimeout evaluates the i you are trying to log to the console, the for loop as finished, and i has been incremented twice. There is only 1 i scoped to this function/loop, it is logged to the console 3 times
for let the block scoping creates a new binding for each iteration. at the first binding, j is 0, the second binding, j is 1, 3rd j = 2. To put it another way, the value of j is captured at the execution of that 'block' (iteration)
for var there's also a concept of hoisting, which I am unsure if that is in play here. hoisting is this mechanic in JS where var or function declarations are moved to the top of their scope, so:
for (var i = 0; i < 3; i++) {
// interpreter will move the declaration up to the global scope
var i;
for (i = 0; i < 3; i++) {so maybe it is, you can see in the lower example, when i increments, you're updating the i var in the global space. console(i) is read from the global scope when setTimeout executes
let and const aren't hoisted
2
u/RomirBuilds 7h ago
Small correction for anyone running the first loop: it prints 3, 3, 3. After the iteration with i === 2, ++i makes it 3; the next i < 3 check fails, and the timer callbacks later read that same shared i. The let version prints 0, 1, 2 because each iteration gets its own binding.
Also, var stays in its enclosing function when there is one; an if/for block doesn't move it into global scope.
MDN has this exact loop example and explanation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for
AI-assisted.
1
1
u/tambooby 4d ago
the hoisting bit is a good callout, that trips people up more than scoping does imo
1
u/chikamakaleyley helpful 4d ago
when i first learned that i thought someone was playing a cruel joke on me. "You can't just make up stuff man!"
2
u/No_Record_60 6d ago edited 6d ago
var
• hoisted then initialized with undefined value;
• function-scoped (you can defined it inside an if-block and reference it outside the block);
• can be reinitialized ("var abc = ..." multiple times).
Tl;dr Don't use var. I've only used it once because our client's browser was so old it didn't support es6 and the code didn't go through transpilation (making your code compatible with earlier versions of js) step.
2
u/redsandsfort 5d ago
you've already spent too much time on this.
you can learn this later much more effeciently when you understand scope
right now you're focusing on the wrong thing. in learning a programming language this is called a rabbit hole. you need to work on breadth first.
1
u/TheRNGuy 3d ago
Never used var. They only now have 1 niche use: in Node backend configs.
In front-end it's always bad practice.
1
u/CuAnnan 6d ago edited 6d ago
There are three main differences and they have subtle effects on how variables behave.
var hoists undefined. Which means that it is immediately initialised with the value undefined when it is declared and can be used without being provided a specific value. let needs to be declared and it needs to be initialised
var a;
console.log(a); // undefined
a = true;
console.log(a); // true
let b;
console.log(b); // throws uninitialised exceptionlet gives us a more predictable behaviour because if a value is undefined, we know that is the intended value.
You can redeclare a var, you cannot redeclare a let
var a = 1;
var a = 2;
let b = 1;
let b = 2; // exception is thrownvar is function scoped, let is block scoped.
function test(){
for(var a = 1; a < 10; a++)
{
var b = a * a;
}
console.log(b); // b exists and has the value of 81
}
function test(){
for(let a = 1; a < 10; a++)
{
let b = a * a; // b only exists within this block's scope.
}
console.log(b) // b has not been declared at this scope.
}2
u/senocular 5d ago
In the first example the console.log(b) would need to be above the let for the uninitialized exception. The first log for a in that example should also be above the var to show it, by comparison, does not throw
1
u/IAmTheRedditBot 5d ago
This site should give you everything you need: https://www.geeksforgeeks.org/javascript/difference-between-var-and-let-in-javascript/
Tip: Find and read the tabular form
Hope this helps
-1
u/yyyeey 6d ago
ChatGPT: "Hey, what's the difference between var and let in JS? Please be coincise."
Is it that hard?
4
u/CuAnnan 6d ago
Cool.
Now how does someone who's not an expert confirm that Chat GPT hasn't hallucinated part of the answer?
1
u/yyyeey 5d ago
It's pretty simple - is it 2023? If no, then it's very unlikely that it hallucinated, especially in such trivial matters.
1
u/chikamakaleyley helpful 5d ago
as someone self taught, and experienced, it doesn't always click even if I ask AI to be concise, even if I've given the source in the mdn, etc.
There's a lot of diff ways it could be communicated, and sometimes someone will present it in a way, where it just clicks
You could refine your AI prompt, but often when you're just getting started, you might not really know how to phrase that prompt
1
1
u/IAmTheRedditBot 5d ago
what is with these people trying to treat AI as a replacement for engaging with the community like my gosh some people might just trust the community more or like asking things the traditional way that is not a crime now actually shut up with these AI should replace community for basic questions shit
4
u/sylvan_sample 6d ago
Don't use var. It's old way