32

Possible Duplicate:
What does “use strict” do in JavaScript, and what is the reasoning behind it?

Actually I know what the use strict does in JavaScript as the question asked here:
What does "use strict" do in JavaScript, and what is the reasoning behind it?

But I can't understand why we should use strict mode in JavaScript libraries? I mean what's the benefits of using that?

5
  • Your answer is already [here on SO][1]. [1]: stackoverflow.com/questions/1335851/… Commented Nov 21, 2012 at 5:51
  • 2
    The reasons for using it in libraries are the same as using it generally, as linked in your question. Why do you think there's a difference just because it's library code? Commented Nov 21, 2012 at 5:53
  • 1
    I voted to close as duplicate because I don't see an answer here being any different or any clearer than the one already given. Commented Nov 21, 2012 at 5:55
  • @T.J.Crowder But I can't understand the using it generally. I said in libraries because I saw it in jQuery, not more. Commented Nov 21, 2012 at 5:55
  • @AfshinMehrabani: You can't understand the benefit of using strict mode, having read the question you linked and its answers and references? Perhaps you could ask a specific question about one of the many listed benefits and why you don't see the point? Commented Nov 21, 2012 at 5:59

1 Answer 1

10

The question you linked, its answers, and the references it gives list a bunch of reasons for using strict mode.

Let me call out just one of them: The Horror of Implicit Globals¹

Non-strict code:

function foo(a) { var myvar; myar = a * 4; // ... return myvar; } 

Now, this code:

console.log(foo(2)); 

...should log "8", right? But it doesn't, it always logs "undefined":

function foo(a) { var myvar; myar = a * 4; // ... return myvar; } console.log(foo(2));

And what's more, it silently creates a global variable called myar. Why? Because I had a typo in my code (I missed out the v in myvar when setting it to a * 4).

Compare with:

function foo(a) { "use strict"; var myvar; myar = a * 4; // ... return myvar; } console.log(foo(2));

Now, instead of a weird return value and a global variable getting created, I get a nice error message: ReferenceError: "myar" is not defined

Now, that particular aspect of strict mode could be accomplished using a lint tool instead. But you don't always involve a lint tool in your coding-in-anger toolchain, when you're just trying to fix something and bouncing between your editor and the browser. So it's nice when the browser helps you out.

Separately, strict mode does things that can't be done by lint tools, such as disallowing with, changing the default value of this in function calls that don't set it, etc.


¹ (that's a post on my anemic little blog)

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.