Module 2: Language Fundamentals
Variables: let, const, and var
Choose declarations deliberately and understand reassignment and scope.
A variable name refers to a value. Prefer const by default, use let when the binding must be reassigned, and avoid var in new code because its function-scoping and hoisting rules can be surprising.
const siteName = "ServerSideStory";
let visitCount = 0;
visitCount += 1;
console.log(siteName, visitCount);
const prevents reassignment of the binding; it does not deeply freeze an object or array:
const tags = ["javascript"];
tags.push("web-development"); // Allowed: the array is mutated.
// tags = []; // TypeError: the binding cannot be reassigned.
Naming rules#
Identifiers may contain letters, digits, underscores, and dollar signs, but cannot start with a digit. Use descriptive camelCase names for variables and functions, and constants such as MAX_RETRIES for values that are truly fixed by convention.
Initialization#
A let declaration exists in its scope before its declaration is reached, but access in that period throws because it is in the temporal dead zone. A const declaration must also be initialized when declared.
Why avoid var?#
var is function-scoped rather than block-scoped and can be redeclared in the same scope. Those behaviours can produce unexpected values inside loops and conditional blocks. You will study scope and hoisting in the functions module.
Practice#
Declare a fixed product name with const and a cart quantity with let. Increase the quantity and log the total using a fixed unit price.