Skip to main content

What does "use strict;" means in Javascript

What does "use strict;" means in Javascript

What does "use strict;" means in Javascript

Strict mode makes several changes the way Javascript is handled by the interpreter. 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 code can sometimes be made to run faster than identical code that's not strict mode and prohibits some syntax likely to be defined in future versions of ECMAScript (i.e classes etc).

Strict mode applies to entire scripts or to individual functions. It doesn't apply to block statements enclosed in {}; attempting to apply it to such contexts doesn't do anything. Basically what use strict does is to introduce better error-checking into your code.

Strict mode can be enabled adding a string with the following content on top of your script "use strict"; i.e :

On a script tag or referenced file :

<script>
"use strict";
// Execute some script strictly
</script>

On function (anonymous or not anonymous)

(function(){"use strict";
// All the code will be analyzed in strict mode
})();

function myAction(){
 "use strict";
// Threat me strictly

}

Prevent duplicates in an object

The following object have 2 properties with the same name:

var myObject = {
  hello:"A string",
  anotherProperty:2,
  other:"Hi",
  hello:"A string"
};

Without strict mode, the object will have the property but with the latest declared value. Withstrict mode, the js interpreter will throw Uncaught SyntaxError: Duplicate data property in object literal not allowed in strict mode.

Use of with statement disallowed

The use of the with statement in strict mode :

"use strict";
var a, x, y;
var r = 10;

with (Math) {
 a = PI * r * r;
 x = r * cos(PI);
 y = r * sin(PI / 2);
}

Will throw Uncaught SyntaxError: Strict mode code may not include a with statementUse of the with statement is not recommended, as it may be the source of confusing bugs and compatibility issues.

Prevents Global Variable Declaration

The declaration of a global variable within a scope is disallowed, for example:

var history = [];

function ExecuteSomething(message){
    // Note that the code doesnt use => var toSaveInHistory, therefore there is an error
    toSaveInHistory = message;
    return console.log(message);
}

ExecuteSomething("My custom log");

The previous code would throw Uncaught ReferenceError: toSaveInHistory is not definedbecause indeed toSaveInHistory is not declared in the closure. Strict mode forbids implicit creation of global property.

Prevents the use of a reserved keyword as a variable name

The use of a future reserved word for an identifier is invalid. The identifier name is reserved in strict mode , i.e:

  • implements
  • interface
  • package
  • private
  • protected
  • public
  • static
  • yield

Arguments as an identifier or modify Arguments variable

With strict mode, the variable "arguments" (which is identified as an array in all function, this variable contains all the arguments that were sent to the execution of the function, read more about how argument variable works here) cannot be used as an identifier (variable or function name, parameter name, and so on) nor change the values of members of the local arguments object, i.e:

"use strict";
var arguments = "something";
// Throws => Invalid usage of 'arguments' in strict mode

// or
function executeSomething(age,name){
   arguments[0] = 12;
   return true;
}

executeSomething(15,"Batman");

Variable declared inside an eval function

If a variable is declared inside an eval function, it cannot be used outside that function, i.e :

eval("var myVariable = 10;");
document.write(myVariable);

The previous code throws 'myVariable' is undefined.

Forbids octal syntax

Assigning an octal value to a numeric literal, or attempting to use an escape on an octal value is disallowed, i.e :

var myOctal = 012;
var myEscapedOctal = \012;

The previous code throws Octal numeric literals and escape characters not allowed in strict mode.

Extending a non-extensible object property

Without strict mode, many things are silently ignore, as add a property to a non extensible object will make nothing. But if strict mode is enabled, you'll get an exception i.e :

var myItem = {};
Object.preventExtensions(myItem); 
myItem.otherProperty = 222;

The previous code throws Cannot create property for a non-extensible object.

Supported browsers

Currently use strict is supported by all major browsers (excluding IE 9 and below). For more information see Can i use use strictHowever there are many places in the web where they'll tell that is not a problem to use strict mode in ie8 or 9, if you still doubt, just trust microsoft :

Comments

Popular posts from this blog

How to use Ngx-Charts in Angular ?

Charts helps us to visualize large amount of data in an easy to understand and interactive way. This helps businesses to grow more by taking important decisions from the data. For example, e-commerce can have charts or reports for product sales, with various categories like product type, year, etc. In angular, we have various charting libraries to create charts.  Ngx-charts  is one of them. Check out the list of  best angular chart libraries .  In this article, we will see data visualization with ngx-charts and how to use ngx-charts in angular application ? We will see, How to install ngx-charts in angular ? Create a vertical bar chart Create a pie chart, advanced pie chart and pie chart grid Introduction ngx-charts  is an open-source and declarative charting framework for angular2+. It is maintained by  Swimlane . It is using Angular to render and animate the SVG elements with all of its binding and speed goodness and uses d3 for the excellent math functio...

Understand Angular’s forRoot and forChild

  forRoot   /   forChild   is a pattern for singleton services that most of us know from routing. Routing is actually the main use case for it and as it is not commonly used outside of it, I wouldn’t be surprised if most Angular developers haven’t given it a second thought. However, as the official Angular documentation puts it: “Understanding how  forRoot()  works to make sure a service is a singleton will inform your development at a deeper level.” So let’s go. Providers & Injectors Angular comes with a dependency injection (DI) mechanism. When a component depends on a service, you don’t manually create an instance of the service. You  inject  the service and the dependency injection system takes care of providing an instance. import { Component, OnInit } from '@angular/core'; import { TestService } from 'src/app/services/test.service'; @Component({ selector: 'app-test', templateUrl: './test.component.html', styleUrls: ['./test.compon...

How to solve Puppeteer TimeoutError: Navigation timeout of 30000 ms exceeded

During the automation of multiple tasks on my job and personal projects, i decided to move on  Puppeteer  instead of the old school PhantomJS. One of the most usual problems with pages that contain a lot of content, because of the ads, images etc. is the load time, an exception is thrown (specifically the TimeoutError) after a page takes more than 30000ms (30 seconds) to load totally. To solve this problem, you will have 2 options, either to increase this timeout in the configuration or remove it at all. Personally, i prefer to remove the limit as i know that the pages that i work with will end up loading someday. In this article, i'll explain you briefly 2 ways to bypass this limitation. A. Globally on the tab The option that i prefer, as i browse multiple pages in the same tab, is to remove the timeout limit on the tab that i use to browse. For example, to remove the limit you should add: await page . setDefaultNavigationTimeout ( 0 ) ;  COPY SNIPPET The setDefaultNav...