Fundamentals
"use strict"
A directive, written as a plain string, "use strict" or 'use strict', not an actual statement or keyword.
js
"use strict";
// the rest of the script runs in strict mode- Only counts when it's the very first thing in the script (or the very first thing in a function body, for function-level strict mode). Anywhere else, it's just a harmless, ignored string.
- Once it's there, the whole script switches to the "modern" way JS runs: several silent mistakes that would otherwise fail quietly now throw real errors instead, undeclared variables, assigning to a read-only property, and a handful of other legacy behaviors get disabled.
- Modern JS features, ES6 classes and modules among them, are strict mode automatically, without needing the directive written out.
Declaring variables: var, let, const
Three keywords for storing data, one of them mostly retired.
js
let name = "Alice" // modern, the default choice
const age = 25 // like let, but can't be reassigned
var city = "Boston" // old-school, rarely used todayletis the modern, everyday way to declare a variable. Use this unless there's a specific reason not to.constbehaves exactly likelet, with one restriction: once aconstvariable is assigned, it can't be reassigned. Reach forconstby default when a value genuinely won't change, it documents that intent for whoever reads the code next.varis the old way of declaring variables, from beforeletandconstexisted. It has a handful of quirky differences fromlet(how it scopes, how it hoists), rarely relevant day to day, worth knowing only if older code forces the issue.- Name variables so the name alone explains what's inside,
userAgeoverx,isLoggedInoverflag. Code gets read far more often than it gets written, a clear name pays for itself immediately.