JavaScript Strict Mode

Writing safer and cleaner JavaScript code

🔒 What is Strict Mode?

Strict mode is a way to opt into a restricted variant of JavaScript. It helps you write cleaner code and catches common coding mistakes early.


// Enable strict mode
"use strict";

// Now JavaScript will be more strict about errors
let message = "Hello World!";
console.log(message);
                                    

How to Enable Strict Mode

📄

Entire Script

Add at the top of your script

"use strict";
// All code below is in strict mode
âš¡

Single Function

Add inside a function

function myFunction() {
    "use strict";
    // Only this function is strict
}

🔹 What Strict Mode Does

Strict mode changes how JavaScript behaves:

🔸 Prevents Undeclared Variables

// Without strict mode - creates global variable
function badExample() {
    message = "Hello"; // Oops! No var, let, or const
}

// With strict mode - throws error
function goodExample() {
    "use strict";
    message = "Hello"; // Error: message is not defined
}

Result:

ReferenceError: message is not defined

🔹 Common Strict Mode Benefits

🔸 No Duplicate Parameters

// This will cause an error in strict mode
"use strict";
function myFunction(a, a) { // Error: Duplicate parameter
    return a + a;
}

🔸 No Deleting Variables

"use strict";
let x = 10;
delete x; // Error: Cannot delete variables

🔸 Safer 'this' Keyword

"use strict";
function showThis() {
    console.log(this); // undefined (not window object)
}
showThis();

🔹 Practical Example

Here's a complete example showing strict mode in action:

"use strict";

// Good practices with strict mode
function calculateArea(width, height) {
    // Must declare variables
    let area = width * height;
    return area;
}

// This would cause an error
function badFunction() {
    undeclaredVar = "This will fail!"; // ReferenceError
}

// Proper way
function goodFunction() {
    let declaredVar = "This works!";
    return declaredVar;
}

console.log(calculateArea(5, 10)); // 50
console.log(goodFunction()); // "This works!"

Output:

50

"This works!"

🧠 Test Your Knowledge

How do you enable strict mode for an entire script?