Strict Mode

Added in ES 2009.
In a Strongly Typed programming language you must declare your variables before using them AND also declare the data type of each variable.
JavaScript is not a Strongly Typed programming language.
This means you can get away with not declaring your variables

var1 = 10; 

There is an option that can force you to explicitly declare a variable before it can be used.

'use strict'

This is similar to Option Explicit found in VBA.
This allows you to place an entire file/script or just an individual function in a "strict" operating context.
When in strict mode JavaScript will use a reduced and safer feature set of JavaScript.

'use strict'   // entire file/script

(function () {
'use strict' //only this function

});

Unpredictable Results

If you do not use 'strict mode' it can lead to unpredictable results and strange run-time errors.
When you do not explicitly declare your variables anything that is not recognised as a keyword, statement or function is assumed to be a variable.
Therefore if you accidentally mis-spell a variable a new one will be created causing you some odd results.


Default Automatically

Modules and Classes enable strict mode automatically.


Leading Zeros are Octal Numbers

Any variable value that starts with a 0 (zero) is interpreteted as an octal number.
When working in strict mode, numbers cannot be prefixed with any zeros.


Objects must be declared before they can be used/assigned

obj1 = { property1 : 10, property2 : 20 }; 

Duplicate parameter names are not allowed

function fun1 ( parameter1, parameter1 ) 

Escape characters are not allowed

let var1 = \010; 

Cannot write to a read-only property

let obj1 = {}; 
Object.defineProperty( obj1, "x", {value:0, writable : false });
obj1.x = 20; // no error, it just gets ignored

Cannot write to a get-only property

let obj1 = { get x() { return 0 } }; 
obj1.x = 10;

Cannot delete an undeletable property

delete Object.prototype; 

The string 'eval' cannot be used as a variable name

let eval = 20; 

The string 'arguments' cannot be used as a variable name

let arguments = 30; 

The 'with' statement is not allowed

with (Math) { x = cos(4) }; 

© 2020 Better Solutions Limited. All Rights Reserved. © 2020 Better Solutions Limited TopPrevNext