Skip to content

Instantly share code, notes, and snippets.

@dfkaye
Created November 29, 2023 23:06
Show Gist options
  • Save dfkaye/25b3faae78a0fb25a7d0fa3c559eb411 to your computer and use it in GitHub Desktop.
Save dfkaye/25b3faae78a0fb25a7d0fa3c559eb411 to your computer and use it in GitHub Desktop.
Note about strict mode and destructuring parameters.
// 30 August 2023
// Note about strict mode and destructuring parameters.
// Setting strict mode at the top of the console...
"use strict";
// ...makes the following assignment in the try block fail:
console.group("init");
try { undeclared_variable = 'should fail'; }
catch (e) { console.warn(e); }
finally { }
console.groupEnd("init");
// That results in the error message,
// "Uncaught ReferenceError: assignment to undeclared variable
// undeclared_variable"
// If we do that outside a try block, that halts the console. No subsequent
// statements are evaluated or executed.
// We can test this behavior better by moving statements into functions that
// declare "use strict"; at the top.
// Here we use console.groups, IIFEs (immediately invoked function expressions),
// and try-catch-finally blocks to avoid crashing the console...
(function test(value) {
console.group(value);
"use strict";
try { undeclared_variable = value; }
catch(e) { console.warn(e) }
finally { console.log("done"); }
console.groupEnd(value);
})("should fail");
// Another one.
(function test(value) {
console.group(value);
"use strict";
try { another_undeclared_variable = value; }
catch(e) { console.warn(e) }
finally { console.log("done"); }
console.groupEnd(value);
})("should fail again");
// Now for the quirk.
// A function with destructuring parameters may *not* declare "use strict"!
// The following nested IIFE in its own try block results in a *syntax* error,
// preventing the console from completing the evaluation step, so that no code
// executes.
(function (value) {
console.group(value);
try {
(function test({ value }) {
// un-comment the next line to experience the error...
// "use strict";
})({ value });
}
catch(e) { console.warn(e) }
finally { console.log("done"); }
console.groupEnd(value);
})("destructuring parameter");
// Uncaught SyntaxError: "use strict" not allowed in function with destructuring
// parameter.
// Now you know.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment