JavaScript strict mode advantages. Why is it there?

Just a few examples why JavaScript strict model is handy. Strict mode helps write cleaner JavaScript code and more secure Javascript.

Rules:

  • Prevent using undeclared variables
  • Prevent using JavaScript keywords as variable name
  • Prevent deleting variables (objects or functions) using delete
  • eval() not allowed to create variables

Prevent using undeclared variables

function f() {
 "use strict"; // Use ECMAScript 5 strict mode in browsers that support it
 var xfoo;
 xFoo = 1; 
}

Without “use strict” there wold be no error. Strict mode eliminates JavaScript silent errors by changing them to throw errors.

There will be an error: assigning to an undeclared variable, since inside the function f() you cannot use undeclared variables.

Prevent using keywords as variable name

"use strict"; 
function f(eval) {}

You cannot have eval as variable name. Actually you can but not in a strict mode. This is why strict mode is cleaner.

Prevent deleting variables (objects or functions) using delete

Example: Syntax error

'use strict';
var x;
delete x;

Example: Good

'use strict';
var x;
x = null; // garbage collected

eval() not allowed to create variables

"use strict";
eval("var x = 53");
alert (x); // Error 

Details of “use strict”

Pay attention to these details:

  • Use string literal "use strict"; to declare strict mode
  • Literal “use strict” must be at the beginning of a script, function or module

Use string literal "use strict"; to declare strict mode

Literal “use strict” is just a string. Old browsers cannot throw errors even if they don’t understand what it means.

Example: No error

"use strict";
var e
function myFunction() {
  e = 2.71;
  alert(e)
}
myFunction();

Example: Error

"use strict";
function myFunction() {
  e = 2.71;
  alert(e)
}
myFunction();

Literal “use strict” must be at the beginning of a script, function or module

Example: Strict mode not working

function myFunction() {
  e = 2.71;  
  "use strict";
  alert(e)
} 
myFunction();

Example: Error because of strict mode

//var e
function myFunction() {
  "use strict";
  e = 2.71;
  alert(e)
} 
myFunction();

tags: strict mode & category: javascript