Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is "strict mode" and how is it used?

I've been looking over the JavaScript reference on the Mozilla Developer Network, and I came across something called "strict mode". I read it over and I'm having trouble understanding what it does. Can someone briefly explain (in general) what its purpose is and how it is useful?

like image 509
nkcmr Avatar asked Dec 28 '11 03:12

nkcmr


People also ask

Why we use strict mode in react?

StrictMode is a tool for highlighting potential problems in an application. Like Fragment , StrictMode does not render any visible UI. It activates additional checks and warnings for its descendants.

How can use strict mode in JavaScript with example?

Strict Mode in Function For example, myVariable = 9; console. log(myVariable); // 9 function hello() { // applicable only for this function 'use strict'; string = 'hello'; // throws an error } hello(); If you use 'use strict'; inside a function, the code inside the function will be in strict mode.

What is strict mode What are some of the advantages disadvantages of using it?

what are the advantages and disadvantages to using it? If you put "use strict"; at the top of your code (or function), then the JS is evaluated in strict mode. Strict mode throws more errors and disables some features in an effort to make your code more robust, readable, and accurate.

What is strict mode in JavaScript?

First, strict mode eliminates some JavaScript silent errors by changing them to throw errors. Second, strict mode fixes mistakes that make it difficult for JavaScript engines to perform optimizations: strict mode code can sometimes be made to run faster than identical code that's not strict mode.

What does “use strict” mean in C++?

The purpose of "use strict" is to indicate that the code should be executed in "strict mode". With strict mode, you can not, for example, use undeclared variables. The numbers in the table specify the first browser version that fully supports the directive. You can use strict mode in all your programs.

What is the difference between strict1 and strict2 in JavaScript?

function strict1(str) { 'use strict'; return eval(str); // str will be treated as strict mode code } function strict2(f, str) { 'use strict'; return f(str); // not eval (. 'Strict mode code!'"); strict1("'use strict'; 'Strict mode code!'"); strict2.

What's the difference between strict and non-strict mode?

Sometimes you'll see the default, non-strict mode referred to as "sloppy mode". This isn't an official term, but be aware of it, just in case. JavaScript's strict mode, introduced in ECMAScript 5, is a way to opt in to a restricted variant of JavaScript, thereby implicitly opting-out of "sloppy mode".


8 Answers

Its main purpose is to do more checking.

Just add "use strict"; at the top of your code, before anything else.

For example, blah = 33; is valid JavaScript. It means you create a completely global variable blah.

But in strict mode it's an error because you did not use the keyword "var" to declare the variable.

Most of the time you don't mean to create global variables in the middle of some arbitrary scope, so most of the time that blah = 33 is written it is an error and the programmer didn't actually want it to be a global variable, they meant to write var blah = 33.

It similarly disallows a lot of things that are technically valid to do. NaN = "lol" does not produce an error. It also doesn't change the value of NaN. Using strict this (and similar weird statements) produce errors. Most people appreciate this because there is no reason to ever write NaN = "lol", so there was most likely a typo.

Read more at the MDN page on strict mode.

like image 51
Simon Sarris Avatar answered Oct 06 '22 18:10

Simon Sarris


One aspect of strict mode not already mentioned in Simon's answer is that strict mode sets this to undefined in functions invoked through function invocation.

So things like this

function Obj() {
   this.a = 12;
   this.b = "a";
   this.privilegedMethod = function () {
      this.a++;
      privateMethod();
   };

   function privateMethod() {
     this.b = "foo";
   }
}

will cause an error when privateMethod is called (since you can't add a property to undefined), rather than uselessly adding a b property to the global object.

like image 43
Adam Rackis Avatar answered Oct 06 '22 17:10

Adam Rackis


Strict mode was added so that there would be an easily statically-analyzable subset of ECMAScript which would be a good target for future versions of the language. Strict mode was also designed in the hope that developers who limit themselves to strict mode would make fewer mistakes and that the bugs they do make would manifest in more obvious ways.

Harmony, which will hopefully become the next major version of ECMAScript is going to be built on top of ES5 strict.

Harmony builds on ES5 strict mode to avoid too many modes.

Some other language experiments also depend on strict mode. SES depends on ES5 strict mode's analyzability.

SES (Secure ECMAScript) Design Experiment

Design an Object Capability Programming Language by removing or repairing features in ES5/Strict.

There should be a straight-forward translation from SES to ES5/Strict.

Annex C of the standard explains the differences between strict mode and normal mode.

The strict mode restriction and exceptions

  • The identifiers "implements", "interface", "let", "package", "private", "protected", "public", "static", and "yield" are classified as FutureReservedWord tokens within strict mode code. (7.6.12 [?]).
  • A conforming implementation, when processing strict mode code, may not extend the syntax of NumericLiteral (7.8.3) to include OctalIntegerLiteral as described in B.1.1.
  • A conforming implementation, when processing strict mode code (see 10.1.1), may not extend the syntax of EscapeSequence to include OctalEscapeSequence as described in B.1.2.
  • Assignment to an undeclared identifier or otherwise unresolvable reference does not create a property in the global object. When a simple assignment occurs within strict mode code, its LeftHandSide must not evaluate to an unresolvable Reference. If it does a ReferenceError exception is thrown (8.7.2). The LeftHandSide also may not be a reference to a data property with the attribute value {[[Writable]]:false}, to an accessor property with the attribute value {[[Set]]:undefined}, nor to a non-existent property of an object whose [[Extensible]] internal property has the value false. In these cases a TypeError exception is thrown (11.13.1).
  • The identifier eval or arguments may not appear as the LeftHandSideExpression of an Assignment operator (11.13) or of a PostfixExpression (11.3) or as the UnaryExpression operated upon by a Prefix Increment (11.4.4) or a Prefix Decrement (11.4.5) operator. Arguments objects for strict mode functions define non-configurable accessor properties named "caller" and "callee" which throw a TypeError exception on access (10.6).
  • Arguments objects for strict mode functions do not dynamically share their array indexed property values with the corresponding formal parameter bindings of their functions. (10.6). For strict mode functions, if an arguments object is created the binding of the local identifier arguments to the arguments object is immutable and hence may not be the target of an assignment expression. (10.5).
  • It is a SyntaxError if strict mode code contains an ObjectLiteral with more than one definition of any data property (11.1.5). It is a SyntaxError if the Identifier "eval" or the Identifier "arguments" occurs as the Identifier in a PropertySetParameterList of a PropertyAssignment that is contained in strict code or if its FunctionBody is strict code (11.1.5).
  • Strict mode eval code cannot instantiate variables or functions in the variable environment of the caller to eval. Instead, a new variable environment is created and that environment is used for declaration binding instantiation for the eval code (10.4.2).
  • If this is evaluated within strict mode code, then the this value is not coerced to an object. A this value of null or undefined is not converted to the global object and primitive values are not converted to wrapper objects. The this value passed via a function call (including calls made using Function.prototype.apply and Function.prototype.call) do not coerce the passed this value to an object (10.4.3, 11.1.1, 15.3.4.3, 15.3.4.4).
  • When a delete operator occurs within strict mode code, a SyntaxError is thrown if its UnaryExpression is a direct reference to a variable, function argument, or function name(11.4.1).
  • When a delete operator occurs within strict mode code, a TypeError is thrown if the property to be deleted has the attribute { [[Configurable]]:false } (11.4.1). It is a SyntaxError if a VariableDeclaration or VariableDeclarationNoIn occurs within strict code and its Identifier is eval or arguments (12.2.1).
  • Strict mode code may not include a WithStatement. The occurrence of a WithStatement in such a context is an SyntaxError (12.10).
  • It is a SyntaxError if a TryStatement with a Catch occurs within strict code and the Identifier of the Catch production is eval or arguments (12.14.1)
  • It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a strict mode FunctionDeclaration or FunctionExpression (13.1)
  • A strict mode function may not have two or more formal parameters that have the same name. An attempt to create such a function using a FunctionDeclaration, FunctionExpression, or Function constructor is a SyntaxError (13.1, 15.3.2).
  • An implementation may not extend, beyond that defined in this specification, meanings within strict mode functions of properties named caller or arguments of function instances. ECMAScript code may not create or modify properties with these names on function objects that correspond to strict mode functions (10.6, 13.2, 15.3.4.5.3).
  • It is a SyntaxError to use within strict mode code the identifiers eval or arguments as the Identifier of a FunctionDeclaration or FunctionExpression or as a formal parameter name (13.1). Attempting to dynamically define such a strict mode function using the Function constructor (15.3.2) will throw a SyntaxError exception.
like image 29
Mike Samuel Avatar answered Oct 06 '22 18:10

Mike Samuel


ECMAScript 5 introduced the concept of strict mode.

Invoking Strict Mode in Code

Strict mode applies to entire scripts or to individual function. It doesn’t apply to block statement enclosed in {} braces, attempting to apply it to such contexts does nothing.

Entire Script:

Let’s say we are creating app.js, so adding the first statement use script will enforce strict mode for the entire code.

// app.js whole script in strict mode syntax
“use strict”;
// Now you can start writing your code

Strict mode for function:

To invoke strict mode for a function, put the exact statement “use strict”; at the start of the function body before any other statement.

function yourFunc(){
    "use strict";

    // Your function code logic
}

Strict mode incorporate several changes to normal JavaScript semantics. First, strict mode eliminates some JavaScript silent errors by changing them to throw errors.

For Instance: Code using Strict Mode

Enter image description here

In the above code example, without using strict mode in code, it won't throw an error. As we are accessing variable x without declaring it. So in strict mode accessing undeclared variables throws an error.

Now let's try to access a variable, x, without declaring it without strict mode.

(function(){
    x = 3;
})();

// Will not throw an error

Advantage of using strict mode:

  • Eliminate JavaScript silent errors by throwing errors.
  • Fixes mistakes that make it difficult for JavaScript engine to perform optimisation.
  • Make code sometimes run faster than identical code that’s not in strict mode
  • Prohibits some syntax likely to be defined in future version of ECMAScript.
like image 38
Nishant Kumar Avatar answered Oct 06 '22 18:10

Nishant Kumar


Strict mode makes several changes to normal JavaScript semantics.

  • strict mode eliminates some JavaScript silent errors by changing them to throw errors.

  • strict mode fixes mistakes that make it difficult for JavaScript engines to perform optimizations.

  • strict mode prohibits some syntax likely to be defined in future versions of ECMAScript.

like image 37
Renganathan M G Avatar answered Oct 06 '22 18:10

Renganathan M G


ECMAScript5 introduces some new objects and properties and also the so-called "strict mode".

Strict mode is a subset of the language that excludes deprecated features. The strict mode is opt-in and not required, meaning that if you want your code to run in the strict mode, you declare your intention using (once per function, or once for the whole program) the following string:

"use strict";
like image 20
Vahid Hallaji Avatar answered Oct 06 '22 17:10

Vahid Hallaji


2017 and I finally found the documentation:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode

Strict mode is a way to opt in to a restricted variant of JavaScript. Strict mode isn't just a subset: it intentionally has different semantics from normal code. Browsers not supporting strict mode will run strict mode code with different behavior from browsers that do, so don't rely on strict mode without feature-testing for support for the relevant aspects of strict mode. Strict mode code and non-strict mode code can coexist, so scripts can opt into strict mode incrementally.


Strict mode makes several changes to normal JavaScript semantics. First, strict mode eliminates some JavaScript silent errors by changing them to throw errors. Second, strict mode fixes mistakes that make it difficult for JavaScript engines to perform optimizations: strict mode code can sometimes be made to run faster than identical code that's not strict mode. Third, strict mode prohibits some syntax likely to be defined in future versions of ECMAScript.

like image 44
Tilak Maddy Avatar answered Oct 06 '22 19:10

Tilak Maddy


Strict mode is a new feature in ECMAScript 5 that allows Developers to put the code inside the "strict" context. This strict context helps developers to avoid errors by throwing more exceptions.

How to use Strict mode in js?

Simple. Toss this at the top of a program to enable it for the whole script:

"use strict";

Or place it within a function to turn on strict mode only within that context.

function imStrict(){
  "use strict";
  // … your code (executes in strict mode) …
}

Advantages of Using Strict mode in JS

1 . Functions are Block scope inside a Block Scope determines the visibility or accessibility of a variable or other resource in the area of your code

Case I (without strict mode) enter image description here

Case II (strict mode) enter image description here

2 . Throws error/exception if variables are assigned a value but not defined any type enter image description here In the above example "a" is not declared any value (let, const, var)

3. Throws an error if any reserved variables is used locally Keywords reserved for future JavaScript versions can NOT be used as variable names in strict mode.

These are: public implements interface let package private protected static yield For eg, enter image description here

4. "this" inside the simple function points to "undefined" in strict mode. The "this" keyword refers to the object that is called the function. If the object is not specified, functions in strict mode will return undefined and functions in normal mode will return the global object (window) Below are the examples for better understanding

Case I (without strict mode) enter image description here

Case II (strict mode) enter image description here

5. Deleting a variable (or object) and a function is not allowed. enter image description here

6. Duplicating a parameter name is not allowed enter image description here

The body of a class is executed in strict mode, by default. for eg: 

class Rectangle {
//code executed here are in Strict mode
}

References

  1. John Resig
  2. MDN
  3. W3School
like image 21
Arham Chowdhury Avatar answered Oct 06 '22 17:10

Arham Chowdhury