Using Strict Mode
Viewers: in countries Watching now:
- Creating variables, functions, and loops
- Writing conditional code
- Sending messages to the console
- Working with different variable types and objects
- Creating and changing DOM objects
- Event handling
- Working with timers
- Building smarter forms
- Using regular expressions
Using Strict Mode
Adding it up here means I'm saying turn on Strict mode for this entire file. You'd also add it as the first line of any function if you want to just do it function by function. But here's the thing, only certain browsers support Strict mode. Well, that's okay because browsers that don't understand it will simply look at this line, figure out it's a string literal by itself, and just ignore it. Browsers that do understand Strict mode, for example Firefox 4, will then be extra picky about your code.
So to prove that this works, I'm actually first going to just remove this, so we can run this code without Strict mode, and it's a very simple piece of code here that's just going to output the term "Hello world" here to this area of my HTML. And as I can see, Firebug isn't giving me any errors here. But if I jump back into the code and I turn on use strict mode, save that again, go back over into Firefox, and refresh this page, instantly we have a problem.
This is actually what JSLint currently recommends as a way of doing it, but I think it's kind of clunky, but it's an option. But secondly, and more importantly, if you're going to be working with Strict mode, don't turn it on and then only check your code in browsers that don't support it, because bear in mind even using Strict mode, or turning it on, your code may still work in non-strict browsers and only break in Strict mode in a supported browser, so make sure you check it across multiple different browsers with the different capabilities.