Why JavaScript use “use strict” directive in programming?

0 votes
Ravi Vishwakarma asked 13 days ago in Web Application by Ravi Vishwakarma

    Why JavaScript use “use strict” directive in programming?

1 Answer

0 votes
Ethan Karla answered 9 days ago by Ethan Karla

Strict mode isn't just a subset: it intentionally has different semantics from normal code.

Browsers not supporting strict mode will run strict mode code with different behavior from browsers that do, so don't rely on strict mode without feature-testing for support for the relevant aspects of strict mode.

Strict mode code and non-strict mode code can coexist, so scripts can opt into strict mode incrementally.

Strict mode makes several changes to normal JavaScript semantics.

1. Strict mode eliminates some JavaScript silent errors by changing them to throw errors.

2. Strict mode fixes mistakes that make it difficult for JavaScript engines to perform optimizations: strict mode code can sometimes be made to run faster than identical code that’s not strict mode.

3. Strict mode prohibits some syntax likely to be defined in future versions of ECMAScript.

4. It prevents, or throws errors, when relatively “unsafe” actions are taken (such as gaining access to the global object).

5. It disables features that are confusing or poorly thought out.

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

7. helps to write a cleaner code

8. changes previously accepted silent errors (bad syntax) into real errors and throws an error message

9. makes it easier to write 'secure' JavaScript

How to use strict mode

Strict mode can be used in two ways, remember strict mode doesn’t work with block statements enclosed in {} braces.

1. Used in global scope for the entire script.

2. It can be applied to individual functions.

Using Strict mode for the entire script

 // applicable to whole program

'use strict';
function hello() {
    string = 'hello'; // throws an error

Unused semicolon 

‘use strict’

A = ‘hello’ // throw an error

Undeclared variable not allowed

‘use strict’

A = “hello”; // throw an error

Undeclared object are not allowed

‘use strict’

Person = { name : “ravi “ , age:20 }; // throw an error