What is the diff between let and var types

I remember learning var type to make a variable or an array etc when I was going through the curriculum, but I have also noticed the use of let type. What is the difference between the two? I am new to javascript so apologizes for the confusion. Thankful for any clear easy explanations and examples if possible.

In ES6, there were two alternatives to var that were introduced.

The let is similar to var but it is more restrictive and “safer”. Whereas var has function level scoping, let is block level scoping and doesn’t hoist. The const is similar to let except that once declared you can cannot reassign it. If it is a primitive type, that also means that you can’t change it. The complex types (object, array, etc) can have their properties, elements changed when declared with const but cannot be reassigned.

I know there are a bunch of concepts in there. But those are all useful concepts for you to research and understand.

So I understand var can have local scope and global scoping. If let type can have block type scoping, which I am assuming is scoping for within of a block of code. What is the difference betwen local and block scoping?

Block level scoping is only within a code block.

for (let i = 0; i < 10; i++) {
  var a = 1;
  let b = 2;
// a has scope here
// b does not have scope here

In this case, a has scope outside that code block (contained in the curly braces) and everywhere inside the containing function, or globally if at the highest level. But b was declared with let so it does not have scope outside the code block.

You should be using let and const. They are safer. There are fewer chances to make a mistake.

I see how variable b has block scope. Does variable a have local or global scope in your example? I am coming from a c++ world so I might be messing things up sorry.

Oh, a has global scope hence why you commented outside the for loop for the scope because the loop is not a function, meaning no local scope. Am I correct?

A var has scope in it’s containing function. If it is at the root level, that scope is global.

1 Like