Select Page

What is the difference between strict and non-strict modes in Javascript?


If you ask your code to be executed under strict mode, JavaScript will force you to declare your variables else it will throw an exception or call foul that your code has error.


nanadwumor

May 21, 2023

Javascript - strict and non-strict language


  • Javascript can be executed in a strict mode just as a language like Java
  • you precede the code with “use strict” if you want Javascript to execute in strict mode

  • only code that comes after “use strict” is affected by the strict condition

RECOMMENDED ARTICLES


No Results Found

The page you requested could not be found. Try refining your search, or use the navigation above to locate the post.


Compared to languages like Java and c++, JavaScript is quite liberal and allows you to do things such as use a variable without first declaring it (type).

For Instance, in Java, you cannot just write

websiteName =“VillageCoder”;


Join Other Subscribers on Our YouTube Channel and Don’t Miss a thing!


Java will force you to tell the compiler the type of variable  websiteName  is. It is a String and thus, a more appropriate statement should be

String websiteName =“VillageCoder”;

However, in JavaScript, you can throw caution to the wind and just write

websiteName =“VillageCoder”;

 without a variable declaration. You will have no problems.

Whereas this freedom is good, it leads to a lot of unchecked bugs. So in Ecmascript 5, a new condition was added to JavaScript – the “strict” mode.

If you ask your code to be executed under strict mode, JavaScript will force you to declare your variables else it will throw an exception or call foul that your code has error. 

To execute code in strict mode, you precede the code with “use strict”.

Program demonstrates the strict mode

Output

strict and non-strict mode

Note that only the code that comes after “use strict” is affected by the strict condition. The code that comes before it executes in non-strict condition. Let’s look at an example.

Program demonstrates that strict mode affects only code beneath it

Output

difference between a strict and non-strict mode in Javascript

The introduction of the “strict” mode

The strict mode was introduced by ECMAScript 5.

Advantages of the strict mode

(1) The strict mode helps to detect otherwise silent errors that are difficult to detect. 

(2)  The strict mode makes debugging much easier as bugs are easily identified. 

(3) It helps prevent unnecessary errors. 

(4) It helps reduce memory leaks as Exception is thrown when variables bare not declared. 

(5) A strict mode code can be made to run faster than identical code that’s not in strict mode.




You May Also Like…


No Results Found

The page you requested could not be found. Try refining your search, or use the navigation above to locate the post.



0 Comments

Submit a Comment

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