JavaScript Introducing ES2015 ES2015 Basics Let and Const

jlampstack
jlampstack
17,751 Points

Use of `let` outside of block level?

At the end Guil mentions that let should be used at the block level. Does this mean we should not use let outside of a function block?

What if we have a variable that will change and it's outside of the block? Should we use let in this case?

Or would we only want a variable to change when it's inside of a block and never at the root level?

Thanks to anyone who can help clarify! =)

6 Answers

The rule of thumb here is: if the variable is mutable use let. if the variable in immutable use const. using let outside of a block level function means it would be a global variable and can change.

Ari Misha
Ari Misha
19,219 Points

Hiya there! "let" keyword in ES6 binds the variable to its corresponding scope. Combing let with arrow functions, gives you a desired result. If we define a variable using let keyword in global scope, you can override it if you want.But thats where const keyword comes in. With const keyword, you can declare the value again even if its in the global scope. I hope it helped!

~ Ari

jlampstack
jlampstack
17,751 Points

Thanks Ari, this semi-answers what I'm trying to figure out. Why does Guil say you should use "let" when you want to define a block level variable? Does this mean we should not use"let" for global level?

I don't know if this definition that i found can help you to understand that statement but i think here is a great explanation of the let variable in general.

link: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let

jlampstack
jlampstack
17,751 Points

Jacob Mishkin This was the answer I was looking for. So in other words, we should only use const outside of a block level function?

No. in the most simplest terms if the variable needs to change use let if the variable needs to remain constant use const. Why do you need a global variable?

here is a solid blog post on scope in Javascript.

jlampstack
jlampstack
17,751 Points

Jacob Mishkin , My thinking is along your lines of thinking, but at 7:15 Guil says to use "let" when you're at a block level. Why would he say to use at block level and not to say it's OK to use at global level? Possibly I'm overthinking this.

That's not all he says. "use let when you need to reassign a variable, or to scope a variable at the block level" big difference from use let when you're at a block level. He talks about the global name space at the start of the video, and discusses why its not a great idea to pollute the global name space.

jlampstack
jlampstack
17,751 Points

Jacob Mishkin Thanks for the clarification.

yup!