In JavaScript, the use strict
statement allows us to choose strict mode to write and execute our code.
Normal JS is very beginner friendly.
- It tolerate syntax errors by remaining silent about them - which can result in unnoticed bugs.
- It does a lot of heavy lifting for mapping variables with their identifiers by checking the scope chain for each name - which costs time and memory.
- It makes life easier by treating the parameter values set at function definition to be the same as the values passed to the function at invocation as items of the
arguments
object - which can sometimes render actual passed in values unimportant. - It autoboxes the
this
value of a function and exposes theFunction.prototype.caller
andFunction.prototype.arguments
APIs that gives access to the caller function andarguments
object respectively. All of these three poses security concerns.
Strict Mode
Strict mode addresses these issues and brings about changes to give developers more control over their code. The changes can be classified into four categories. Below we briefly discuss some of them in each category. For detailed explanation and code examples, please refer to this excellent MDN article
1. Changes related to mistakes arising from syntax and type conversion
Mistakes related to syntax and type conversion throw errors, instead of silently ignoring them. There are several of them.
For example,
- mistyped variables throw ReferenceError.
- Assignment to a non-writable global (like
undefined
orNaN
) throw a TypeError.
Please refer to this section of the MDN Strict Mode article for more examples.
2. Changes related to variable usage
- Variable name mapping is optimized by prohibiting the use of
with
. -
eval
can introduce new variables in it's own enclosed scope only, not in the surrounding / global scope. - Deleting declared variables is not allowed.
3. Changes related to eval
and arguments
object
-
eval
andarguments
object are made easier to work with. They are treated like other pre-assigned language keywords and cannot be used to name variables and functions. -
arguments
object of a function is set only when the function is invoked. So setting a value for an argument in the function definition does not update thearguments
object and updating an item in thearguments
object witharguments[i] = 'Something, not necessarily a string'
does not change the value of the corresponding parameter variable.
4. Changes related to security
- Written code is made more secure by preventing autoboxing of
this
.undefined
andnull
values ofthis
do not autobox to the Global object. -
Function.prototype.caller
andFunction.protoype.arguments
throw TypeError, so this prevents traversing the call stack - making strict mode code more secure.
References
Top comments (2)
Also important to note is that native Jacascript (ES) modules are in strict mode by default - so
'use strict'
has no effectYep!