‘use strict’ is a rather useful statement to have at the beginning of all Javascript modules or functions. It ensures that all code in the module is executed in strict mode.
The usage is simple enough.
|
|
You can also enable strict mode to specific functions.
|
|
Strict mode has to be at the beginning of files or modules - will not have the desired effect if used anywhere else.
use strict
is ignored by older engines that do not know what a strict mode is. But, we live in better times and it is almost universally respected everywhere.
By using strict mode you ensure that common programming errors and unsafe actions are loudly announced rather than silently consumed or ignored.
What does strict mode do?
By using use strict
, you are telling the engine to ensure that -
- code follows right syntax. Else, throw errors
this
refers to objects that called function. If no object is present,this
refers to global object (e.g window)- all variables should be declared (and must follow conventions. Also
eval
,arguments
cannot be a variable name) - immutable or getter properties cannot be written to. Throw errors if you are attempting to do that (these are runtime errors btw)
- cannot “mistakenly” repeat arguments in a function (e.g.
getSum(x, x)
) with
is not allowed in code- object props must be unique (e.g.
const earth = {name: 'earth', name: 'mercury'
is invalid) - throw errors if attempting to delete an “non-deletable” property or if code is attempting to delete a variable/ object (e.g.
delete obj
,delete x
) - variables cannot be one of the future reserved words
- Octal numeric literals (e.g. let x = 010) and octal escape characters are not allowed