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

4 Ways to Communicate Across Browser Tabs in Realtime

1. Local Storage Events You might have already used LocalStorage, which is accessible across Tabs within the same application origin. But do you know that it also supports events? You can use this feature to communicate across Browser Tabs, where other Tabs will receive the event once the storage is updated. For example, let’s say in one Tab, we execute the following JavaScript code. window.localStorage.setItem("loggedIn", "true"); The other Tabs which listen to the event will receive it, as shown below. window.addEventListener('storage', (event) => { if (event.storageArea != localStorage) return; if (event.key === 'loggedIn') { // Do something with event.newValue } }); 2. Broadcast Channel API The Broadcast Channel API allows communication between Tabs, Windows, Frames, Iframes, and  Web Workers . One Tab can create and post to a channel as follows. const channel = new BroadcastChannel('app-data'); channel.postMessage(data); And oth...

Certbot SSL configuration in ubuntu

  Introduction Let’s Encrypt is a Certificate Authority (CA) that provides an easy way to obtain and install free  TLS/SSL certificates , thereby enabling encrypted HTTPS on web servers. It simplifies the process by providing a software client, Certbot, that attempts to automate most (if not all) of the required steps. Currently, the entire process of obtaining and installing a certificate is fully automated on both Apache and Nginx. In this tutorial, you will use Certbot to obtain a free SSL certificate for Apache on Ubuntu 18.04 and set up your certificate to renew automatically. This tutorial will use a separate Apache virtual host file instead of the default configuration file.  We recommend  creating new Apache virtual host files for each domain because it helps to avoid common mistakes and maintains the default files as a fallback configuration. Prerequisites To follow this tutorial, you will need: One Ubuntu 18.04 server set up by following this  initial ...

Working with Node.js streams

  Introduction Streams are one of the major features that most Node.js applications rely on, especially when handling HTTP requests, reading/writing files, and making socket communications. Streams are very predictable since we can always expect data, error, and end events when using streams. This article will teach Node developers how to use streams to efficiently handle large amounts of data. This is a typical real-world challenge faced by Node developers when they have to deal with a large data source, and it may not be feasible to process this data all at once. This article will cover the following topics: Types of streams When to adopt Node.js streams Batching Composing streams in Node.js Transforming data with transform streams Piping streams Error handling Node.js streams Types of streams The following are four main types of streams in Node.js: Readable streams: The readable stream is responsible for reading data from a source file Writable streams: The writable stream is re...