#1 Data Analytics Program in India
₹2,499₹1,499Enroll Now
3 min read
Question 36 of 50easy

What is Strict Mode in JavaScript?

Understanding use strict and its effects.

What You'll Learn

  • How to enable strict mode
  • What it prevents
  • Why use it

Enabling Strict Mode

code.jsJavaScript
// For entire script
'use strict';

// For single function
function myFunction() {
  'use strict';
  // strict mode only in this function
}

// ES6 modules are always in strict mode

What Strict Mode Prevents

code.jsJavaScript
'use strict';

// 1. Undeclared variables
x = 10; // ReferenceError

// 2. Deleting variables
let y = 1;
delete y; // SyntaxError

// 3. Duplicate parameters
function sum(a, a) { } // SyntaxError

// 4. Octal literals
let num = 010; // SyntaxError

// 5. Writing to read-only properties
const obj = {};
Object.defineProperty(obj, 'x', { value: 1, writable: false });
obj.x = 2; // TypeError

// 6. this in functions is undefined
function test() {
  console.log(this); // undefined, not window
}

Benefits

FeatureWithout StrictWith Strict
Undeclared varsCreates globalError
Silent failuresIgnoredThrows error
this in functionwindowundefined

Best Practice

Modern JavaScript (ES6+ modules, classes) is automatically in strict mode. For older code, always use 'use strict'.