JavaScript Let Keyword

One of the biggest problems with declaring variables with the var keyword is that you can overwrite variable declarations without an error.

Here the console will display the string David.

As you can see in the code above, the camper variable is originally declared as James and then overridden to be David. In a small application, you might not run into this type of problem, but when your code becomes larger, you might accidentally overwrite a variable that you did not intend to overwrite. Because this behavior does not throw an error, searching and fixing bugs becomes more difficult.
A new keyword called let was introduced in ES6 to solve this potential issue with the var keyword. If you were to replace var with let in the variable declarations of the code above, the result would be an error.

This error can be seen in the console of your browser. So unlike var, when using let, a variable with the same name can only be declared once. Note the "use strict". This enables Strict Mode, which catches common coding mistakes and “unsafe” actions. For instance:

let camper = 'James';
let camper = 'David';

"use strict";
x = 3.14;

Leave a Reply

Matt is the author of five Apress books including Learn RStudio IDE, Quick, Effective, and Productive Data Science, Objective-C Recipes, Swift Quick Syntax Reference, Objective-C Quick Reference, and the upcoming Pro Data Visualization with R and JavaScript. He has over 20 years of experience in technology, psychometrics, and data analytics working in major higher education institutions such as The College Board and Educational Testing Service. He has earned a Master’s degree in Information Systems Management and a Bachelor’s degree in Quantitative Psychology.