What is use strict in JavaScript

JavaScript is a loosely typed (dynamic) scripting language. Unlike stricter languages like Java or C#, JavaScript doesn’t require you to declare variables before using them.

However, to make your code more secure and catch errors early, JavaScript introduced "use strict" in ECMAScript 5. This enables strict mode.

 What is "use strict"?

It is a way to tell JavaScript to run in a stricter, safer mode.

"use strict";

var x = 1; //  OK
y = 1;     //  Error in strict mode (y is not declared)

You can place "use strict":

  • At the top of your script
  • At the top of a function (to apply only inside it)

 What Strict Mode Does NOT Allow

Strict mode stops you from doing things that can lead to bugs or bad practices.

1. Using Variables Without Declaring

"use strict";
x = 5; //  Error: x is not defined

2. Using Reserved Keywords

"use strict";
var let = 10; // Error: 'let' is a reserved word

3. Duplicate Property Names in Objects

"use strict";
var obj = {
  name: "John",
  name: "Doe" //  Error: Duplicate property
};

4. Duplicate Function Parameters

"use strict";
function sayHi(name, name) { //  Error: Duplicate parameter
  console.log(name);
}

5. Assigning to Read-Only Properties

"use strict";
const obj = {};
Object.defineProperty(obj, "id", { value: 1, writable: false });

obj.id = 2; //  Error: Cannot assign to read-only property

6. Modifying arguments Object

"use strict";
function test(a) {
  arguments[0] = 99; //  Not allowed in strict mode
  console.log(a);    // Still prints the original value
}
test(10);

7. Octal Numbers Not Allowed

"use strict";
var num = 0123; //  Error: Octal literals are not allowed

8. Using with Statement

"use strict";
with (Math) { //  Error
  console.log(cos(2));
}

9. eval() Cannot Create Variables

"use strict";
eval("var x = 10;");
console.log(x); //  Error: x is not defined outside eval

 Final Takeaways

  • "use strict" makes JavaScript code more secure and less error-prone.
  • Helps you avoid common bugs like undeclared variables or naming mistakes.
  • Recommended to use it at the beginning of every JavaScript file or function.
Best Practice: Always start your code with "use strict"; to avoid silent errors.