JavaScript Tutorial

Javascript Strict Mode

JavaScript is a scripting language that sometimes allows code to produce correct results even if it contains errors. To address this issue, JavaScript provides a strict mode.

Strict mode in JavaScript can be enabled by using the expression "use strict";. When strict mode is enabled, any silent errors or mistakes in the code will throw an error instead.

The "use strict"; expression must be placed as the first statement in a script or a function to activate strict mode. Let's consider an example without using strict mode:

Input:-

[tryjavascript_take a example without using “use strict”.]

Output:-

Here, I did not provide any type, still, I am getting the value of x. Now we will try using “use strict”.

Input:-

[tryjavascript_try with using “use strict”]

Output:-

Now we will try duplicate names with the use of “use strict”.

Input:-

[tryjavascript_names with use of “use strict”]

Output:-

When using strict mode in JavaScript, there are several important points to keep in mind:

  1. Using an undeclared variable is not allowed: In strict mode, you must explicitly declare variables before using them with var, let, or const keywords.

  2. Using an undeclared object is not allowed: Similar to variables, objects must be declared before use.

  3. Reserved words cannot be used as variables: Strict mode prohibits using reserved words as variable names. These reserved words include eval, arguments, implements, interface, package, private, protected, public, static, and others.

  4. Writing to a read-only property is not allowed: If a property is defined as read-only, attempting to modify its value will throw an error.

  5. Deleting a variable or object is not allowed: In strict mode, the delete operator cannot be used to delete variables or objects.

  6. Deleting a function is not allowed: Strict mode prevents deleting functions using the delete operator.

  7. Duplicating a parameter name is not allowed: In strict mode, duplicate parameter names in function declarations or function expressions are not allowed.

  8. Octal numeric literals are not allowed: Octal literals (base 8) are not allowed in strict mode. Instead, you can use hexadecimal (0x) or binary (0b) literals.

Go back to Previous Course