2Block-Scoped Declarations: let and const

In this chapter you'll learn how the new let and const declarations work and what problems they solve. Throughout the chapter, you'll see some behaviors of var that have proved problematic, and you'll learn how let and const solve those problems. You'll see how let and const provide true block scope and prevent confusion caused by repeated declarations or by using a variable before you initialize it. You'll discover how block scope means you can use let to avoid the traditional “closures in loop” problem, and how const lets you create constants: “variables” whose values cannot change. You'll learn how let and const avoid creating even more properties on the already-overburdened global object. In short, you'll learn why let and const are the new var, and why var no longer has a place in modern JavaScript programming.

AN INTRODUCTION TO LET AND CONST

Like var, let declares variables:

let x = 2;
x += 40;
console.log(x); // 42

You can use let anywhere you can use var. Just as with var, you ...

Get 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.