Gyaan

use strict

beginner strict-mode best-practices

Strict mode makes it easier to write “secure” JavaScript.

  • Strict mode changes previously accepted “bad syntax” into real errors.
  • In normal JavaScript, mistyping a variable name creates a new global variable. In strict mode, this will throw an error, making it impossible to accidentally create a global variable.
  • In normal JavaScript, a developer will not receive any error feedback assigning values to non-writable properties.
  • In strict mode, any assignment to a non-writable property, a getter-only property, a non-existing property, a non-existing variable, or a non-existing object, will throw an error.
// Without strict mode — silently creates a global variable
function withoutStrict() {
  myVar = 10; // No error, creates a global variable
}

// With strict mode — throws an error
function withStrict() {
  "use strict";
  myVar = 10; // ReferenceError: myVar is not defined
}
"use strict";

// Cannot delete a variable or function
let x = 10;
// delete x; // SyntaxError

// Duplicate parameter names are not allowed
// function sum(a, a) {} // SyntaxError

// Cannot use reserved keywords as variable names
// let private = 10; // SyntaxError