Difference Between Let and Var

What is the difference between let and var?

For example, Ayah’s students sample code solution used for (let element of list, but
when I clicked on the for…of button it came up with for var element of ‘blank space’ :wink:

So my question is what is the difference between let and var, and on Ayah’s Student why did grasshopper pull up var instead of let?:man_shrugging::man_shrugging::man_shrugging:

1 Like

Hey there,

var is a keyword used to create global variables, and is used in our Fundamentals I course. In Fundamentals II, we introduce let, which is used to create local variables, and we use let pretty much exclusively in the app after we introduce it.

For loops are introduced in Fundamentals I, which is why pressing the For...of key automatically adds var to the loop’s setup. I agree that it’s a bit confusing, and we’re looking into a solution for the issue.

Hope this clarifies things!
Ben

I barely remember the difference between global and local variables.
could you refresh my memory

2 Likes

A global variable is one that can be used in the entire code I think. A local variable is exclusive to one section of the code.
Global example:
Var I=1
If (I===1)
print true
The answer would be true.
Var I=1
If (I===1)
var z=2
Else
Var g=3
Print g
This would give an undefined error since g is defined only inside of the if statement. If I put this instead:
Else
Var g=3
Print g
Then g would equal 3. Now I am still new so my coding is prolly sloppy, but the point is I can be used anywhere and in any function after it is defined, but g and z can only be used inside the area they are defined in.

2 Likes

Hey there,

A global variable is a variable that can be used anywhere, in all code blocks.

A local variable is a variable that can be used only in the code block where it is declared, and any code blocks nested inside of that.

This is called “scope”, as in, a variable has global scope vs local scope. Understanding scope can be a bit tricky at first, but it gets easier. Questions about scope are fairly common in programming job interviews.

For example:

for (let num of [1,2,3,4,5]) {
    var x = 'global variable'
}

console.log(x) // this will print 'global variable', even though
// we are printing x outside the code block where it is declared
for (let num of [1,2,3,4,5]) {
    let x = 'local variable'
}

console.log(x) // this causes an error, because we
// are trying to use x outside the block where
// it was declared

You can read more about scope here.

Hope this helps! Let me know if you have any questions.
Ben

1 Like

Thank you! that helps very much.