Use strict in controller.js file

 

In this blog, we will see the use of "use strict" directive, which is new in ECMAScript version 5.

Lots of developers don’t use "use strict" to ensure their code is running in a secure way. It's important to follow best practices with your code. This article will help you do just that!

The purpose of using strict is to indicate that code should be run in strict mode. For example, an undeclared variable cannot be used in strict mode.

All modern browsers except Internet Explorer 9 and below support "use strict".

                                                             

Declaring ‘’Use strict”

Strict mode is declared by adding "use strict". Beginning of a script or function. Declared at the top of the script and has global scope (all code in the script runs in strict mode).

Example

"use strict";
myRandomFunction();

function myRandomFunction () {
  x = 
9;   // This will also cause an error because x is not declared
}

Declared inside a function, it has local scope (only the code inside the function is in strict mode):

x = 9;       // This will not cause an error.
myFunction();


function myRandomFunction() {
  
"use strict";
  y = 
10;   // This will cause an error
}

 

Why strict mode?

Strict mode makes it easy to write "safe" JavaScript.

Strict mode turns the previously accepted "bad syntax" into a real error. For example, in regular JavaScript, mistyped variable names create new global variables.

Strict mode throws an error, so you can't accidentally create a global variable. In normal JavaScript, assigning a value to a non-writable property does not give the developer an error message. In strict mode, assignment to a non-writable property, getter-only property, non-existent property, variable, or object throws an error.

 

Previous
Next Post »