JavaScript Lessons

JavaScript Use Strict Explained: Write Safer Code

Strict mode turns silent JavaScript mistakes into real errors. See how "use strict" works, where to place it, and how it makes your code safer and easier to debug.

Serhat ALPASLAN3 min read

JavaScript is one of the most widely used programming languages in web development. However, JavaScript’s flexible nature can sometimes lower code quality and cause bugs to surface. That’s why JavaScript’s “use strict” feature can be used to improve code quality.

The “use strict” feature makes JavaScript code execute in a stricter way. It helps keep your code safer and more consistent. “Use strict” is a statement you add at the top of your JavaScript code. This statement makes the code run in strict mode.

For example, the following code does not use the “use strict” feature:

function myFunction() {
x = 3.14;
return x;
}

In this code, the “x” variable is used before it is declared. Because of JavaScript’s flexible nature, this does not throw an error. However, writing this code with the “use strict” feature makes it throw an error:

"use strict";
function myFunction() {
x = 3.14;
return x;
}

In this code, it throws an error because the “x” variable is used before it is declared. This makes the code safer and more consistent.

The “use strict” feature also disables some JavaScript features. For example, the “with” statement cannot be used when the “use strict” feature is enabled. This makes the code more consistent.

The following example uses the “with” statement:

var person = {name: "John", age: 25};
with (person) {
name = "Jane";
age = 30;
}

In this code, the “with” statement is used to access the properties of the “person” object. However, writing this code with the “use strict” feature makes it throw an error:

"use strict";
var person = {name: "John", age: 25};
with (person) {
name = "Jane";
age = 30;
}

In this code, it throws an error because the “with” statement is used. This makes the code more consistent.

The “use strict” feature also surfaces some JavaScript errors. For example, the “NaN” (Not a Number) value throws an error when the “use strict” feature is enabled. This makes the code safer.

The following example uses the “NaN” value:

var x = 10 / "Hundred";

In this code, the “Hundred” value is not a numeric value, so it returns the “NaN” value. However, writing this code with the “use strict” feature makes it throw an error:

"use strict";
var x = 10 / "Hundred";

In this code, it throws an error because the “Hundred” value is not a numeric value. This makes the code safer.

The “use strict” feature makes JavaScript code execute in a stricter way. It helps keep your code safer and more consistent. “Use strict” is a statement you add at the top of your JavaScript code. This statement makes the code run in strict mode.

Share it if it helped

Write a comment