How to Keep JavaScript Code from Breaking with “use strict”

JavaScript is a powerful language. It can be used to do anything from making simple animations on a website to building complex user interfaces in modern web applications. But there are some pitfalls that JavaScript developers need to watch out for, including the accidental breaking of code due to sloppy coding practices.

One way around this problem is adding “use strict” at the top of your code files, which enforces stricter rules about variable and function naming conventions and syntax errors. In this blog post we will discuss what “use strict” does in JavaScript and why you might want it enabled on your projects!

'use strict'; // Enabling strict mode globally

// Your code here

ECMAScript 5.x has introduced the “use strict” directive. The JavaScript directive “use strict” is not a statement and is ignored by older versions of the programming language.

The purpose of “use strict” is to indicate that the code should be executed under strict mode. For example, developers cannot use undeclared variables.

All modern browsers except Internet Explorer 9 and lower support the use of the strict directive.

function myFunction() {
  'use strict'; // Enabling strict mode within a function

  // Your code here
}
'use strict';

function myFunction() {
  myVariable = 'hello'; // Throws a ReferenceError in strict mode because myVariable is not declared with var, let, or const
}
'use strict';

var obj = {};
Object.defineProperty(obj, 'myProperty', {value: 42, configurable: false});

delete obj.myProperty; // Throws a TypeError in strict mode because myProperty is not configurable
'use strict';

var myObj = {
  myProperty: 42,
  myProperty: 24 // Throws a SyntaxError in strict mode because of the duplicate property name
};

Some features of “use strict”:

  1. Disallows undefined global variables.
  2. Assignment failures in strict mode will throw errors.
  3. Attempting to delete the undeletable properties will result in an error
  4. You should try your best to be unique when it comes to object literals. In other words, don’t use the same property name more than once in an object literal or a clash will happen! 
  5. Parameter names passed to a function must be unique. For example, you cannot create a function with 2 i variables like function(i, i){}.
  6. Do not allow the use of octal notation for numbers.
  7. Do not allow the with keyword.
  8. eval function will not introduce new variables.
  9. Do not allow the deletion of plain names.

Leave a Comment

Your email address will not be published. Required fields are marked *


Scroll to Top

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close