all topics

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 today
  • let is the modern, everyday way to declare a variable. Use this unless there's a specific reason not to.
  • const behaves exactly like let, with one restriction: once a const variable is assigned, it can't be reassigned. Reach for const by default when a value genuinely won't change, it documents that intent for whoever reads the code next.
  • var is the old way of declaring variables, from before let and const existed. It has a handful of quirky differences from let (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, userAge over x, isLoggedIn over flag. Code gets read far more often than it gets written, a clear name pays for itself immediately.