Guvi-blog-logo

How To Use “use strict” String For Strict Mode In JavaScript?

String-Mode-in-JavaScript

You must have encountered “use strict” in several JavaScript codes, mostly at the top of the file. Most modern libraries use it regularly to ensure good and secure code writing conventions. Let’s learn what this useful concept is and how to enable Strict Mode in JavaScript:

What is “use strict”?

“use strict” is a literal expression that was introduced after ES5 (ECMAScript Version 5). If the code is written in a version older than ES5, “use strict” will simply be ignored. It was used to declare that strict mode is now being followed in the execution process. “use strict” is not a keyword but a string because, when this feature was implemented a while ago, many older browsers didn’t support it, so when they encountered “use strict”, they simply ignored it, without running into any errors.

What is Strict Mode?

Strict mode, when followed in JavaScript, makes changes to its normal semantics. It changes both syntax and runtime behavior. In short, it is the stricter pattern of writing JavaScript. Strict mode removes errors that would be ignored in non-strict mode (or sloppy mode). This makes the code in JavaScript secure and less prone to encountering any error. Declaring the strict mode is as easy as writing a string. Yes, you need to just write “use strict” in quotes as you do with string declaration. That’s it.

 Or if you want to limit the strict mode to a lexical scope or a specific function, write “strict mode” inside that.

Also, you don’t need to explicitly mention ‘use strict’ in a module of ES6 (ECMAScript 6, version 2015) because the exported module is by default in strict mode.

Our platform offers an advanced curriculum for JavaScript & its relevant Web-Development courses, where you can learn JS at your pace. GUVI’s courses adheres to Project-Based learning, so you can learn by doing & building things from scratch.

Rules and Restrictions in Strict Mode

Strict mode makes changes in both syntax and runtime behavior of JavaScript. Here are some rules which are enforced in strict mode:

1. Cannot use undeclared variables

Strict mode doesn’t allow you to use undeclared variables and will throw a Reference Error, saying “not defined”. So, if you want to use a variable, you have to declare it using ‘var, const’ (or ‘let’ in ES6).

carbon.png

This can help in various ways to a developer, such as, limiting the chance when you mistype a variable name which will cause a logical error. Because of the mistyped/undefined variable name it will throw an error in strict mode. Also, it will prevent the unintended use of global variables because it is not a good practice.

2. Function or Variable deletion is NOT allowed

In the strict mode, if you try to delete a variable or a function using the ‘delete’ keyword, it will throw a syntax error. But in non-strict/sloppy mode, such attempts fail, and delete expression evaluates to “false”. Also, there will be errors when you intentionally try to delete a property of an object that is not configurable.

Similarly, if you try to delete a function, it will also throw the SyntaxError as in the case of a variable.

3. Duplicating or overlapping of parameters is NOT allowed

Strict mode restricts using two or more parameters with the same name. But in non-strict mode, no errors will be thrown.

Catching this error will help you to avoid unnecessary errors if you accidentally mistype the variable name. In sloppy or non-strict mode, the same parameter name will lead to unwanted behavior like the value of the later parameter will override the previous. 

4. ‘Eval’ cannot alter scope

Strict mode, for security reasons, enforces restrictions to the ‘eval( )’ method. The code passed into it cannot make declaration/modifications of variables or define functions in its surrounding scope. However, in a non-strict mode, no such security measures were present.

Also, ‘eval’ is treated as a keyword in strict mode; this means that you cannot use ‘eval’ as the name of any variable.

5. ‘with’ statement is NOT valid

In strict mode, the ‘with’ statements are not allowed. The ‘with’ statement adds the properties as well as properties of the object to the current scope. Hence, the statements nested inside the ‘with’ statement can call its properties and methods directly without referring to it. However, in strict mode, this is not possible. A SyntaxError will be thrown if used.

6. Writing or mutating to a Read-Only property is NOT allowed

Strict mode doesn’t allow you to assign value to a non-writable, get-only, or non-existing property. In doing so, an error will be thrown. In non-strict mode, they won’t work as well but no errors will be thrown. Those attempts will fail silently while transpilation. 

7. Function cannot be defined inside a statement or block

The strict mode only allows you to define the function at the very beginning of the script file or just inside another function. This means you cannot define a function inside an ‘if’ function, a ‘for’ function, or a block ({ }).

8. Octal numbers are NOT allowed

Octal numbers are numeric values starting with 0. For example: 0252, 010, 033, etc. In strict mode, you can assign an octal number. Though, it is supported in all older versions of browsers. 

However, in the ES6 version, octal numbers are supported by prefixing a number with ‘0o’ (Zero and o), for example, 0o45, 0o90, etc.

9. ‘Reserved’ keywords cannot be used

ES5 and strict mode are configured in such a way that they lookout for the future requirements of JavaScript. So, strict mode restricted the use of the name as an identifier which will probably be used in the future as a keyword. Those words are implements, interface, let, package, private, protected, public, static, yield, await, async, promise, etc.

Why Do We Need Strict Mode in JS?

The semantics of strict mode is quite distinct from “sloppy mode” which has a looser syntax and code writing convention that causes silent errors. This means the code will run without throwing errors but with unexpected results. The introduction of “strict mode” resolved this problem. It eliminates silent errors and instead throws it so that it won’t cause problems in development. Strict Mode also thoroughly checks the syntax-related issues which can cause problems in the future if ignored. It also optimizes the performance of the code to be run by a JavaScript engine. The problems of data leaking and globals are also fixed as they were caught beforehand in the development phase. 

TypeScript- an enhanced version of JavaScript

Nowadays, TypeScript, which is a superset of JavaScript, also recommends using strict mode while writing codes. TypeScript is a more strict way of writing JavaScript. It shows the error in real-time without actually running in the browser. TypeScript config file gives an option to use strict mode into every compiled file.

What are top 5 programming languages in 2022? Read to learn more?

Conclusion

Strict Mode was created to help developers avoid errors while coding in JavaScript. It made writing JavaScript code safer as well as code style more logical and readable. But for beginners, who are used to writing without strict mode can face problems initially but when they get used to it, results will be far better than the previous writing styles. 

Ofcourse, who doesn’t want a cleaner and error-free code? If you ask that – Should one start using strict mode all the time? then I would suggest YES!

Every modern browser is using strict mode now and you should too. Every aspiring developer/coder should start working on it right away.

Test your understanding of different concepts in JavaScript, attempt these practice MCQs now:

1.Which of the following is not true about “use-strict”?

(i)            It is a keyword

(ii)           It was introduced after ECMAScript Version 5

(iii)          It makes the code less prone to accidental errors

(iv)         None of these

Correct Answer: (i)

 “use-strict” is a string literal used in JavaScript to declare that strict mode is now being followed in the execution process.

2. JavaScript is a subset of which of these programming languages?

(i)            Python

(ii)           Ruby

(iii)          TypeScript

(iv)         C#

Correct Answer: (iii) TypeScript

3. Which of the following is true about use-strict rules/conventions?

(i)            Keywords cannot be used

(ii)           Undeclared variables cannot be used

(iii)          Duplicating of parameters is not allowed

(iv)         All of these

Correct Answer: (iv) All of these

4. What symbol is used for writing comments in JavaScript?

(i)            \\

(ii)           \**/

(iii)          \**\

(iv)         //

Correct Answer: (iv) Single line comments in JavaScript can be written after // symbol.

For writing multi-line comments we use /**/ symbol.

5. What is the output of the following code snippet?

var a = 10;

var b = 0;

document.write(a/b);

(i)            Error will be thrown

(ii)           Garbage value will be printed

(iii)          0 will be printed

(iv)         Infinity will be printed

Correct Answer: (iv) Infinity will be printed

Whenever division by zero happens in JavaScript infinity is printed as the output.

Contact Form

By clicking 'Submit' you Agree to Guvi Terms & Conditions.

Our Learners Work at

Our Popular Course

Share this post

Author Bio

GUVI Geek
GUVI Geek

Our Live Classes

Learn Javascript, HTML, CSS, Java, Data Structure, MongoDB & more
Learn Python, Machine Learning, NLP, Tableau, PowerBI & more
Learn Selenium, Python, Java, Jenkins, Jmeter, API Testing & more
Learn Networking, Security Testing, IAM, Access Management & more

Hey wait, Don’t miss New Updates from GUVI!

Get Your Course Now

Related Articles