Declaring Names Once With const and let
In this lesson, you ported the top of the backup check to JavaScript and found that JavaScript declares each name once, then assigns it.
- In Python, a name exists as soon as you assign to it, and assigning again points it at a new value.
- The port is
backup-check.jsin the folderbackup-check/, whosepackage.jsonholds{ "type": "module" }, so the file runs as a module, in strict mode. - Like Python, JavaScript reads the whole file before it runs any of it. A
letdeclares a name, and a name can be declared only once, so a secondletfor it is aSyntaxErrorthat stops every line, even the ones above it. - JavaScript keeps declaring and assigning apart: you declare a name once, with
constorlet, then assign it new values with no keyword. - Assigning to a name that was never declared stops a module with a
ReferenceErrorwhen that line runs, where Python would create the name. That’s strict mode at work. +=works as in Python.warnings += 1;is short forwarnings = warnings + 1;, so the name gets a new value.- That reassignment is why
warningsstays aletin the finished port below, even though the lines that add to it come later. - Start every name as
const, and useletonly when the code really reassigns it. The keyword is a promise to the reader: thelets show at a glance which names change. - Python marks a constant with an UPPER_CASE name, but nothing at runtime stops a reassignment. A
constis enforced. - Watch out: unlike the second
let, which stopped the whole file, aconstthat’s reassigned gives aTypeErroronly when that line runs. - Watch out: a
constfixes what the name points at, not the contents, so an array or object in it can still change, as a Python list can. - In older code, you’ll meet
var, an earlier way to declare names. Writeletandconstinstead.
Here’s the line-by-line port, where the second status line got its own let:
let bucket = "kestrel-db-backups";
let region = "eu-west-1";
let notifyEmail = "[email protected]";
let warnings = 0;
let status = "checking settings";
console.log(`Status: ${status}`);
let status = "ready to back up";
console.log(`Status: ${status}`);