What is strict mode in JavaScript?

Have you ever noticed use of strict keyboard as shown in following image anywhere?

 

When I start creating application for Windows Store (Metro App), I noticed this on the top of the default.js file. Well it is nothing but a way to tell JavaScript for better coding and error checking in JavaScript code. If you put strict mode then you are not allowed to do many things in JavaScript code like assigning value to a read only variable.

You can put strict mode restriction

  1. On the function level
  2. On the page level   

 You can put strict restriction on function level as following

Now let us try to put some code in above function. In below code we are assigning value to a variable which is not declared. We have also put function is the strict mode.

When try to call this JavaScript function, you will get error as following. You see in the error message that “Variable undefined in strict mode”. If you go ahead and remove strict mode from the function then you should able to call the function.

If you have put strict mode then you will get error if you try to perform following operations.

  1. Assigning value to non-declared variable
  2. Assigning value to read only variable
  3. Defining duplicate property
  4. Defining duplicate parameters in a function
  5. Using future reserved keywords like interface, let, package etc.
  6. Cannot defined a function inside if-else or for statement

There are many other operations will give you error in strict mode. I hope now purpose of strict mode is clear to you. Thanks for reading!

Dhananjay Kumar is Developer, Blogger , Speaker, Learner , Mindcracker & Microsoft MVP.

Tagged with: , , ,
Posted in Web, Windows Store Apps
5 comments on “What is strict mode in JavaScript?
  1. Abhishek Sur says:

    Dhananjay…

    I really didnt know this trick. Good call.

    Cheers mate

  2. Jeewan says:

    Thanks …. It really good

  3. Monjurul Habib says:

    Thanks for sharing such a good trick…:)

  4. jagzaction says:

    Thanks sir

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Categories
Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my current or previous employer's view in anyway. © Copyright 2013
Follow

Get every new post delivered to your Inbox.

Join 2,134 other followers

%d bloggers like this: