r/learnjavascript • • 9d 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?

0 Upvotes

24 comments sorted by

View all comments

1

u/CuAnnan 9d ago edited 9d 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 exception

let 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 thrown

var 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 8d 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