Tip 2 Reduce Scope Conflicts with let and const

In this tip, you’ll learn that in cases where a value is going to change, let is the best choice.

You saw in the previous tip that when you’re working with variables, you’re better off avoiding reassignment. But what do you do in situations where you really need to reassign a variable? In those cases, you should use let.

let is similar to var because it can be reassigned, but unlike var, which is lexically scoped, let is block scoped. You’ll explore scope more in Tip 3, ​ Isolate Information with Block Scoped Variables ​. For now, just know that block scoped variables exist only in blocks, such as an if block or a for loop. Outside those blocks, they aren’t accessible. As a rule, ...

Get Simplifying JavaScript now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.