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

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



Recently, I ran some of my JavaScript code through Crockford's JSLint, and it gave the following error:



Problem at line 1 character 1: Missing "use strict" statement.



Doing some searching, I realized that some people add "use strict"; into their JavaScript code. Once I added the statement, the error stopped appearing. Unfortunately, Google did not reveal much of the history behind this string statement. Certainly it must have something to do with how the JavaScript is interpreted by the browser, but I have no idea what the effect would be.


"use strict";



So what is "use strict"; all about, what does it imply, and is it still relevant?


"use strict";



Do any of the current browsers respond to the "use strict"; string or is it for future use?


"use strict";




25 Answers
25



This article about Javascript Strict Mode might interest you: John Resig - ECMAScript 5 Strict Mode, JSON, and More



To quote some interesting parts:



Strict Mode is a new feature in ECMAScript 5 that allows you to place a program, or a function, in a "strict" operating context. This strict context prevents certain actions from being taken and throws more exceptions.



And:



Strict mode helps out in a couple ways:



Also note you can apply "strict mode" to the whole file... Or you can use it only for a specific function (still quoting from John Resig's article):


// Non-strict code...

(function()
"use strict";

// Define your library strictly...
)();

// Non-strict code...



Which might be helpful if you have to mix old and new code ;-)



So, I suppose it's a bit like the "use strict" you can use in Perl (hence the name?): it helps you make fewer errors, by detecting more things that could lead to breakages.


"use strict"



Currently, it's supported by all major browsers (bar IE 9 and below).





Changing the default after so many years ? Too late for that : it would break so many existing sites/scripts/applications... The only possible thing is to help make things better, for the future.
– Pascal MARTIN
Mar 4 '10 at 21:54





I tried a small code snippet that would be invalid when using "use strict" in Firefox 3.6, Safari 5, Chrome 7 and Opera 10.6 (all Mac). No errors whatsoever, so i guess 'use strict' is not supported in any browser yet. Didn't test in IE9 though ;)
– Husky
Nov 10 '10 at 9:54


"use strict"





Quick update: Firefox 4 has complete support for strict mode, and as far as I can tell, no other browser does. Safari and Chrome have "partial" support, but I don't really know what that means.
– Sasha Chedygov
Feb 8 '11 at 2:02





Chrome 11 seems to pass all of these tests as does IE10 ie.microsoft.com/testdrive/HTML5/TryStrict/Default.html#
– gman
May 13 '11 at 17:27






@Julius - This couldn't have been implemented using a reserved keyword, because then code trying to trigger strict mode would break in old browsers. Adding a "random" string literal doesn't break anything.
– nnnnnn
Mar 5 '14 at 11:22



It's a new feature of ECMAScript 5. John Resig wrote up a nice summary of it.



It's just a string you put in your JavaScript files (either at the top of your file or inside of a function) that looks like this:


"use strict";



Putting it in your code now shouldn't cause any problems with current browsers as it's just a string. It may cause problems with your code in the future if your code violates the pragma. For instance, if you currently have foo = "bar" without defining foo first, your code will start failing...which is a good thing in my opinion.


foo = "bar"


foo





Fail fast and fail loudly.
– Niels Bom
Jan 29 '13 at 22:20





If you are writing Javascript inline in HTML files, start each new block with <script>"use strict";. The flag only applies to the block in which it is included.
– nobar
Oct 5 '13 at 18:50


<script>"use strict";





It's funny, this resulted in strings must have single quotes. So write 'use strict'; instead
– nilsi
Jan 30 '15 at 8:49



'use strict';





then what would happen to the hoisting concept of javascript ?
– Sunil Sharma
May 14 '15 at 8:33





When I'm adding "use strict"; to the top of my JavaScript code, I am asked to use the function form of 'use strict' instead. Can you explain why is better to use the function form of 'use strict'? Thank you
– Andrew Lam
Jun 3 '17 at 4:24



"use strict";



The statement "use strict"; instructs the browser to use the Strict mode, which is a reduced and safer feature set of JavaScript.


"use strict";



Disallows global variables. (Catches missing var declarations and typos in variable names)


var



Silent failing assignments will throw error in strict mode (assigning NaN = 5;)


NaN = 5;



Attempts to delete undeletable properties will throw (delete Object.prototype)


delete Object.prototype



Requires all property names in an object literal to be unique (var x = x1: "1", x1: "2")


var x = x1: "1", x1: "2"



Function parameter names must be unique (function sum (x, x) ...)


function sum (x, x) ...



Forbids octal syntax (var x = 023; some devs assume wrongly that a preceding zero does nothing to change the number.)


var x = 023;



Forbids the with keyword


with



eval in strict mode does not introduce new variables


eval



Forbids deleting plain names (delete x;)


delete x;



Forbids binding or assignment of the names eval and arguments in any form


eval


arguments



Strict mode does not alias properties of the arguments object with the formal parameters. (i.e. in function sum (a,b) return arguments[0] + b; This works because arguments[0] is bound to a and so on. )


arguments


function sum (a,b) return arguments[0] + b;


arguments[0]


a



arguments.callee is not supported


arguments.callee



[Ref: Strict mode, Mozilla Developer Network]





Nit: global variables are allowed, just have to be explicit (e.g. window.foo = bar).
– gcampbell
Jun 20 '16 at 9:41


window.foo = bar





Requires all property names in an object literal to be unique (var x = x1: "1", x1: "2") is this valid
– Arun Killu
Jul 29 '17 at 8:26





Your example in 11 is missing a modification of a (otherwise it makes no sense). I. e. function sum(a,b) a = 0; return arguments[0] + b; alert(sum(1, 2)) will return 3 with strict mode and 2 without strict mode, due to aliasing.
– David Gausmann
Mar 14 at 11:04





you just saved me couple of hours of debugging with #6
– jazzcat
Jun 12 at 14:15



If people are worried about using use strict it might be worth checking out this article:


use strict



ECMAScript 5 'Strict mode' support in browsers. What does this mean?
NovoGeek.com - Krishna's weblog



It talks about browser support, but more importantly how to deal with it safely:


function isStrictMode()
return !this;

/*
returns false, since 'this' refers to global object and
'!this' becomes false
*/

function isStrictMode()
"use strict";
return !this;

/*
returns true, since in strict mode the keyword 'this'
does not refer to global object, unlike traditional JS.
So here, 'this' is 'undefined' and '!this' becomes true.
*/





I disagree. I think this shows why its very useful. In essence it means that this returns its function and not the window
– Jamie Hutber
Feb 26 '13 at 15:25


window





when do you ever want the window with this that you can't target with window?
– Jamie Hutber
Jul 18 '13 at 8:34


this


window





It refers to itself. this belongs to its own function and not the global window
– Jamie Hutber
Jul 28 '13 at 21:17


this





In the second one this one is actually undefined.
– Broxzier
Aug 14 '13 at 11:40



this


undefined





The point is that your JS program will start failing due to accessing a property of an undefined, instead of silently doing the wrong thing on the global object. Makes tracking down subtle bugs much easier.
– Stephen Chung
Jul 31 '15 at 5:47



A word of caution, all you hard-charging programmers: applying "use strict" to existing code can be hazardous! This thing is not some feel-good, happy-face sticker that you can slap on the code to make it 'better'. With the "use strict" pragma, the browser will suddenly THROW exceptions in random places that it never threw before just because at that spot you are doing something that default/loose JavaScript happily allows but strict JavaScript abhors! You may have strictness violations hiding in seldom used calls in your code that will only throw an exception when they do eventually get run - say, in the production environment that your paying customers use!


"use strict"


"use strict"



If you are going to take the plunge, it is a good idea to apply "use strict" alongside comprehensive unit tests and a strictly configured JSHint build task that will give you some confidence that there is no dark corner of your module that will blow up horribly just because you've turned on Strict Mode. Or, hey, here's another option: just don't add "use strict" to any of your legacy code, it's probably safer that way, honestly. DEFINITELY DO NOT add "use strict" to any modules you do not own or maintain, like third party modules.


"use strict"


"use strict"


"use strict"



I think even though it is a deadly caged animal, "use strict" can be good stuff, but you have to do it right. The best time to go strict is when your project is greenfield and you are starting from scratch. Configure JSHint/JSLint with all the warnings and options cranked up as tight as your team can stomach, get a good build/test/assert system du jour rigged like Grunt+Karma+Chai, and only THEN start marking all your new modules as "use strict". Be prepared to cure lots of niggly errors and warnings. Make sure everyone understands the gravity by configuring the build to FAIL if JSHint/JSLint produces any violations.


"use strict"


JSHint/JSLint


Grunt+Karma+Chai


"use strict"


JSHint/JSLint



My project was not a greenfield project when I adopted "use strict". As a result, my IDE is full of red marks because I don't have "use strict" on half my modules, and JSHint complains about that. It's a reminder to me about what refactoring I should do in the future. My goal is to be red mark free due to all of my missing "use strict" statements, but that is years away now.


"use strict"


"use strict"


"use strict"





WHY are devs in this thread so cavalier about "use strict"?? It THROWS EXCEPTIONS in otherwise working JavaScript, for goodness sakes! Just sprinkle it on the code like sugar on Corn Flakes, eh? NO! BAD! "use strict" should be used cautiously, preferably only in code you control that has unit tests that pass against all major browsers and that exercise all code paths. You got tests? Okay, "use strict" is fine for you, knock yourselves out.
– DWoldrich
May 8 '14 at 8:38





Yes. Obviously "use strict" can break seemingly valid javascript which hasn't broken before. But the code not having broken before is not equal to the code being correct and doing what it's supposed to. Usually referencing undeclared variables signals a typo, etc. Use strict allows you to catch these kinds of errors, and hopefully before you ship production code.
– Jostein Kjønigsen
Mar 9 '15 at 7:46





... or just apply "use strict" as part of a last pass over your code, fix all the obvious problems, shrug, say "good enough," then take it out for production :)
– Wolfie Inu
Nov 10 '15 at 8:49





Personally, I never/very rarely add "use strict"; to existing code. That being said, I'll almost always use it when I'm writing new code from scratch
– Martin
Mar 25 '16 at 20:48


"use strict";





If you're already using JSLint, you've probably fixed most of the places where "use strict" would break things, though.
– Jonathan Cast
Dec 4 '17 at 15:22



Using 'use strict'; does not suddenly make your code better.


'use strict';



The JavaScript strict mode is a feature in ECMAScript 5. You can enable the strict mode by declaring this in the top of your script/function.


'use strict';



When a JavaScript engine sees this directive, it will start to interpret the code in a special mode. In this mode, errors are thrown up when certain coding practices that could end up being potential bugs are detected (which is the reasoning behind the strict mode).



Consider this example:


var a = 365;
var b = 030;



In their obsession to line up the numeric literals, the developer has inadvertently initialized variable b with an octal literal. Non-strict mode will interpret this as a numeric literal with value 24 (in base 10). However, strict mode will throw an error.


b


24



For a non-exhaustive list of specialties in strict mode, see this answer.


'use strict';



In my new JavaScript application: Absolutely! Strict mode can be used as a whistleblower when you are doing something stupid with your code.



In my existing JavaScript code: Probably not! If your existing JavaScript code has statements that are prohibited in strict-mode, the application will simply break. If you want strict mode, you should be prepared to debug and correct your existing code. This is why using 'use strict'; does not suddenly make your code better.


'use strict';



Insert a 'use strict'; statement on top of your script:


'use strict';


// File: myscript.js

'use strict';
var a = 2;
....



Note that everything in the file myscript.js will be interpreted in strict mode.


myscript.js



Or, insert a 'use strict'; statement on top of your function body:


'use strict';


function doSomething()
'use strict';
...



Everything in the lexical scope of function doSomething will be interpreted in strict mode. The word lexical scope is important here. See this answer for a better explanation.


doSomething



I found a nice article describing several things that are prohibited in strict mode (note that this is not an exclusive list):



Historically, JavaScript has been confused about how functions
are scoped. Sometimes they seem to be statically scoped, but some
features make them behave like they are dynamically scoped. This is
confusing, making programs difficult to read and understand.
Misunderstanding causes bugs. It also is a problem for performance.
Static scoping would permit variable binding to happen at compile
time, but the requirement for dynamic scope means the binding must be
deferred to runtime, which comes with a significant performance
penalty.



Strict mode requires that all variable binding be done statically.
That means that the features that previously required dynamic binding
must be eliminated or modified. Specifically, the with statement is
eliminated, and the eval function’s ability to tamper with the
environment of its caller is severely restricted.



One of the benefits of strict code is that tools like YUI Compressor
can do a better job when processing it.



JavaScript has implied global variables. If
you do not explicitly declare a variable, a global variable is
implicitly declared for you. This makes programming easier for
beginners because they can neglect some of their basic housekeeping
chores. But it makes the management of larger programs much more
difficult and it significantly degrades reliability. So in strict
mode, implied global variables are no longer created. You should
explicitly declare all of your variables.



There are a number of situations that could cause this
to be bound to the global object. For example, if you forget to
provide the new prefix when calling a constructor function, the
constructor's this will be bound unexpectedly to the global object, so
instead of initializing a new object, it will instead be silently
tampering with global variables. In these situations, strict mode will
instead bind this to undefined, which will cause the constructor to
throw an exception instead, allowing the error to be detected much
sooner.


this


new


this


this


undefined



JavaScript has always had read-only properties, but you
could not create them yourself until ES5’s Object.createProperty
function exposed that capability. If you attempted to assign a value
to a read-only property, it would fail silently. The assignment would
not change the property’s value, but your program would proceed as
though it had. This is an integrity hazard that can cause programs to
go into an inconsistent state. In strict mode, attempting to change a
read-only property will throw an exception.


Object.createProperty



The octal (or base 8) representation of numbers was extremely
useful when doing machine-level programming on machines whose word
sizes were a multiple of 3. You needed octal when working with the CDC
6600 mainframe, which had a word size of 60 bits. If you could read
octal, you could look at a word as 20 digits. Two digits represented
the op code, and one digit identified one of 8 registers. During the
slow transition from machine codes to high level languages, it was
thought to be useful to provide octal forms in programming languages.



In C, an extremely unfortunate representation of octalness was
selected: Leading zero. So in C, 0100 means 64, not 100, and 08 is an
error, not 8. Even more unfortunately, this anachronism has been
copied into nearly all modern languages, including JavaScript, where
it is only used to create errors. It has no other purpose. So in
strict mode, octal forms are no longer allowed.


0100


08



The arguments pseudo array becomes a little bit more
array-like in ES5. In strict mode, it loses its callee and caller
properties. This makes it possible to pass your arguments to untrusted
code without giving up a lot of confidential context. Also, the
arguments property of functions is eliminated.


callee


caller


arguments


arguments



In strict mode, duplicate keys in a function literal will produce a
syntax error. A function can’t have two parameters with the same name.
A function can’t have a variable with the same name as one of its
parameters. A function can’t delete its own variables. An attempt to
delete a non-configurable property now throws an exception. Primitive
values are not implicitly wrapped.


delete


delete



ECMAScript 5 adds a list of reserved words. If you use them as variables or arguments, strict mode will throw an error. The reserved words are:



implements, interface, let, package, private, protected, public, static, and yield


implements


interface


let


package


private


protected


public


static


yield





it is very nice explanation. However, I have one doubt that can I use "strict" mode in conjunction with other java script libraries, like Angular js?
– UVM
Aug 5 '16 at 3:39





@UVM: The strict-mode directive affects only lexical scope. i.e. only the file/function that it is declared. If you have another file/function that does not have the 'use strict' directive, they will be executed in non-strict mode, even when called from a function running in strict mode. See this asnwer for an explanation.
– Krumia
Aug 5 '16 at 4:11


'use strict'





thanks for your explanation. I understand that "strict" mode affects only the "code" , not its "execution"
– UVM
Aug 5 '16 at 4:23






On second look, you're right. I thought you meant it only threw exceptions, but didn't change the way the code worked (like changing this). Now I see you were referring to calling other functions.
– CyberEd
Oct 23 '16 at 3:55


this





There are some cases where octal is useful. The C syntax for it is horrible, but I would have liked to have seen languages add a new octal syntax which could then allow the leading-zero form to be deprecated. Of course, for Javascript to have supported the leading-zero form was just silly.
– supercat
Feb 9 '17 at 21:08



I strongly recommend every developer to start using strict mode now. There are enough browsers supporting it that strict mode will legitimately help save us from errors we didn’t even know were in your code.



Apparently, at the initial stage there will be errors we have never encountered before. To get the full benefit, we need to do proper testing after switching to strict mode to make sure we have caught everything. Definitely we don’t just throw use strict in our code and assume there are no errors. So the churn is that it’s time to start using this incredibly useful language feature to write better code.


use strict



For example,


var person =
name : 'xyz',
position : 'abc',
fullname : function () "use strict"; return this.name;
;



JSLint is a debugger written by Douglas Crockford. Simply paste in your script, and it’ll quickly scan for any noticeable issues and errors in your code.





@JamieHutber : Please visit this link caniuse.com/use-strict AND kangax.github.io/es5-compat-table. It will give exact idea for all browser.
– Pank
Jan 18 '14 at 13:21




I would like to offer a somewhat more founded answer complementing the other answers. I was hoping to edit the most popular answer, but failed. I tried to make it as comprehensive and complete as I could.



You can refer to the MDN documentation for more information.



"use strict" a directive introduced in ECMAScript 5.


"use strict"



Directives are similar to statements, yet different.


use strict


use


use strict



The use strict directive indicates that the following code (in a script or a function) is strict code.
The code in the highest level of a script (code that is not in a function) is considered strict code when the script contains a use strict directive.
The content of a function is considered strict code when the function itself is defined in a strict code or when the function contains a use strict directive.
Code that is passed to an eval() method is considered strict code when eval() was called from a strict code or contains the use strict directive itself.


use strict


use strict


use strict


eval()


eval()


use strict



The strict mode of ECMAScript 5 is a restricted subset of the JavaScript language, which eliminates relevant deficits of the language and features more stringent error checking and higher security. The following lists the differences between strict mode and normal mode (of which the first three are particularly important):


with


Object


ReferenceError


Object


this


undefined


this


Object


var hasStrictMode = (function() "use strict"; return this===undefined ());



Also when a function is invoked with call() or apply in strict mode, then this is exactly the value of the first argument of the call()or apply() invocation. (In normal mode null and undefined are replaced by the global Object and values, which are not objects, are cast into objects.)


call()


apply


this


call()


apply()


null


undefined


Object



In strict mode you will get a TypeError, when you try to assign to readonly properties or to define new properties for a non extensible object. (In normal mode both simply fail without error message.)


TypeError


eval()


eval()


eval()


SyntaxError


delete


delete


false


TypeError


delete


false


0x


eval


arguments


arguments.caller


arguments.callee


TypeError


TypeError





"In strict mode octal literals are not allowed (these are literals that start with 0x ...)" octal literals start with a leading 0.
– Alex Gittemeier
Aug 11 '16 at 19:52


0



My two cents:



One of the goals of strict mode is to allow for faster debugging of issues. It helps the developers by throwing exception when certain wrong things occur that can cause silent & strange behaviour of your webpage. The moment we use use strict, the code will throw out errors which helps developer to fix it in advance.


use strict



Few important things which I have learned after using use strict :


use strict



Prevents Global Variable Declaration:


var tree1Data = name: 'Banana Tree',age: 100,leafCount: 100000;

function Tree(typeOfTree)
var age;
var leafCount;

age = typeOfTree.age;
leafCount = typeOfTree.leafCount;
nameoftree = typeOfTree.name;
;

var tree1 = new Tree(tree1Data);
console.log(window);



Now,this code creates nameoftree in global scope which could be accessed using window.nameoftree. When we implement use strict the code would throw error.


nameoftree


window.nameoftree


use strict



Uncaught ReferenceError: nameoftree is not defined



Sample



Eliminates with statement :


with



with statements can't be minified using tools like uglify-js. They're also deprecated and removed from future JavaScript versions.


with



Sample



Prevents Duplicates :



When we have duplicate property, it throws an exception



Uncaught SyntaxError: Duplicate data property in object literal not
allowed in strict mode


"use strict";
var tree1Data =
name: 'Banana Tree',
age: 100,
leafCount: 100000,
name:'Banana Tree'
;



There are few more but I need to gain more knowledge on that.



If you use a browser released in the last year or so then it most likely supports JavaScript Strict mode. Only older browsers around before ECMAScript 5 became the current standard don't support it.



The quotes around the command make sure that the code will still work in older browsers as well (although the things that generate a syntax error in strict mode will generally just cause the script to malfunction in some hard to detect way in those older browsers).





Then what does it do?
– Anish Gupta
May 20 '12 at 14:47





... this describes in part the compatibility, but not what it actually does.
– courtsimas
Jul 11 '12 at 16:04



Strict mode makes several changes to normal JavaScript semantics:



eliminates some JavaScript silent errors by changing them
to throw errors.



fixes mistakes that make it difficult for JavaScript
engines to perform optimizations.



prohibits some syntax likely to be defined in future
versions of ECMAScript.



for more information vistit Strict Mode- Javascript



"Use Strict"; is an insurance that programmer will not use the loose or the bad properties of JavaScript. It is a guide, just like a ruler will help you make straight lines. "Use Strict" will help you do "Straight coding".



Those that prefer not to use rulers to do their lines straight usually end up in those pages asking for others to debug their code.



Believe me. The overhead is negligible compared to poorly designed code. Doug Crockford, who has been a senior JavaScript developer for several years, has a very interesting post here. Personally, I like to return to his site all the time to make sure I don't forget my good practice.



Modern JavaScript practice should always evoke the "Use Strict"; pragma. The only reason that the ECMA Group has made the "Strict" mode optional is to permit less experienced coders access to JavaScript and give then time to adapt to the new and safer coding practices.





The reason strict mode is optional has nothing to do with what you've stated. The real reason is to not break existing code that may not conform.
– George Jempty
Oct 31 '13 at 13:34






Indeed, the less experienced coders ought to be the first ones to enable the "use strict";
– Antti Haapala
Aug 19 '14 at 5:37



When adding "use strict";, the following cases will throw a SyntaxError before the script is executing:


"use strict";



Paving the way for future ECMAScript versions, using one of the newly reserved keywords (in prevision for ECMAScript 6): implements, interface, let, package, private, protected, public, static, and yield.


implements


interface


let


package


private


protected


public


static


yield



Declaring function in blocks


if(a<b) function f()



Octal syntax


var n = 023;



this point to the global object.


this


function f()
"use strict";
this.a = 1;
;
f();



Declaring twice the same name for a property name in an object literal


a: 1, b: 3, a: 7



This is no longer the case in ECMAScript 6 (bug 1041128).



Declaring two function arguments with the same name function


f(a, b, b)



Setting a value to an undeclared variable


function f(x)
"use strict";
var a = 12;
b = a + x*35; // error!

f();



Using delete on a variable name delete myVariable;


delete


delete myVariable;



Using eval or arguments as variable or function argument name


eval


arguments


"use strict";
arguments++;
var obj = set p(arguments) ;
try catch (arguments)
function arguments()



Sources:



Transitioning to strict mode on MDN



Strict mode on MDN



JavaScript’s Strict Mode and Why You Should Use It on Colin J. Ihrig's blog (archived version)



Including use strict in the beginning of your all sensitive JavaScript files from this point is a small way to be a better JavaScript programmer and avoid random variables becoming global and things change silently.


use strict



Quoting from w3schools:



The "use strict" directive is new in JavaScript 1.8.5 (ECMAScript
version 5).



It is not a statement, but a literal expression, ignored by earlier
versions of JavaScript.



The purpose of "use strict" is to indicate that the code should be
executed in "strict mode".



With strict mode, you can not, for example, use undeclared variables.



Strict mode makes it easier to write "secure" JavaScript.



Strict mode changes previously accepted "bad syntax" into real errors.



As an example, in normal JavaScript, mistyping a variable name creates
a new global variable. In strict mode, this will throw an error,
making it impossible to accidentally create a global variable.



In normal JavaScript, a developer will not receive any error feedback
assigning values to non-writable properties.



In strict mode, any assignment to a non-writable property, a
getter-only property, a non-existing property, a non-existing
variable, or a non-existing object, will throw an error.



Please refer to http://www.w3schools.com/js/js_strict.asp to know more



There's a good talk by some people who were on the ECMAScript committee: Changes to JavaScript, Part 1: ECMAScript 5" about how incremental use of the "use strict" switch allows JavaScript implementers to clean up a lot of the dangerous features of JavaScript without suddenly breaking every website in the world.


"use strict"



Of course it also talks about just what a lot of those misfeatures are (were) and how ECMAScript 5 fixes them.



"use strict" makes JavaScript code to run in a strict mode, which basically means everything need to be defined before using them, the main reason for strict mode is avoiding accidental global usages of any undefined methods.


strict mode


strict mode


undefined



Also in strict mode, things run faster, some warning or silents warnings, throw fatal errors, it's better always use it to make a neater code.



"use strict" is widely need to be used in ECMA5, in ECMA6 it's part of javascript by default, so don't need to be added if you using ES6.



Look at these statements and examples from MDN:



The "use strict" Directive
The "use strict" directive is new in
JavaScript 1.8.5 (ECMAScript version 5). It is not a statement, but a
literal expression, ignored by earlier versions of JavaScript. The
purpose of "use strict" is to indicate that the code should be
executed in "strict mode". With strict mode, you can not, for example,
use undeclared variables.



Examples of using "use strict":

Strict mode for functions: Likewise, to invoke strict mode for a
function, put the exact statement "use strict"; (or 'use strict';) in
the function's body before any other statements.



1) strict mode in functions


function strict()
// Function-level strict mode syntax
'use strict';
function nested() return 'And so am I!';
return "Hi! I'm a strict mode function! " + nested();

function notStrict() return "I'm not strict.";

console.log(strict(), notStrict());



2) whole-script strict mode


'use strict';
var v = "Hi! I'm a strict mode script!";
console.log(v);



3) Assignment to a non-writable global


'use strict';

// Assignment to a non-writable global
var undefined = 5; // throws a TypeError
var Infinity = 5; // throws a TypeError

// Assignment to a non-writable property
var obj1 = ;
Object.defineProperty(obj1, 'x', value: 42, writable: false );
obj1.x = 9; // throws a TypeError

// Assignment to a getter-only property
var obj2 = get x() return 17; ;
obj2.x = 5; // throws a TypeError

// Assignment to a new property on a non-extensible object
var fixed = ;
Object.preventExtensions(fixed);
fixed.newProp = 'ohai'; // throws a TypeError



For more info, visit this page here



Note that use strict was introduced in EcmaScript 5 and was kept since then.


use strict



Below are the conditions to trigger strict mode in ES6 and ES7:



use strict is a way to make your code safer, cause you can't use dangerous features which can work not as you expect.And as was writed before it makes code more strict.


use strict



"use strict"; is the ECMA effort to make JavaScript a little bit more robust. It brings in JS an attempt to make it at least a little "strict" (other languages implement strict rules since the 90s). It actually "forces" JavaScript developers to follow some sort of coding best practices.
Still, JavaScript is very fragile. There is no such thing as typed variables, typed methods, etc.
I strongly recommend JavaScript developers to learn a more robust language such as Java or ActionScript3, and implement the same best practices in your JavaScript code, it will work better and be easier to debug.



Small example to compare:



Non-strict mode:


for (i of [1,2,3]) console.log(i)

// output:
// 1
// 2
// 3



Strict mode:


'use strict';
for (i of [1,2,3]) console.log(i)

// output:
// Uncaught ReferenceError: i is not defined





Notice that the code above will add the i variable to the global scope (generally this not a best practice and strict mode helps to avoid that).
– michael
Feb 18 '17 at 12:41



The main reasons why developers should use "use strict" are:


"use strict"



Prevents accidental declaration of global variables.Using "use strict()" will make sure that variables are declared with var before use.
Eg:


"use strict()"


var


function useStrictDemo()
'use strict';
//works fine
var a = 'No Problem';

//does not work fine and throws error
k = "problem"

//even this will throw error
someObject = 'problem': 'lot of problem';


"use strict"



The string "arguments" cannot be used as a variable:


"arguments"


"use strict";
var arguments = 3.14; // This will cause an error



Will restrict uses of keywords as variables. Trying to use them will throw errors.



In short will make your code less error prone and in turn will make you write good code.



To read more about it you can refer here.



Use Strict is used to show common and repeated errors so that it is handled differently , and changes the way java script runs , such changes are :



Prevents accidental globals



No duplicates



Eliminates with



Eliminates this coercion



Safer eval()



Errors for immutables



you can also read this article for the details



Normally java script does not follow strict rules hence increasing chances of errors. After using "use strict", the java script code should follow strict set of rules as like in other programming languages such as use of terminators, declaration before initialization etc.


"use strict"



If "use strict" is used then the code should be written by following a strict set of rules hence decreasing the chances of errors and ambiguities.


"use strict"



JavaScript “strict” mode introduces in ECMAScript 5.


(function()
"use strict";
your code...
)();



writing "use strict"; at the very top of your JS file turns on strict
syntax checking. It does the following tasks for us :



(i) shows an error if you try to assign to an undeclared variable



(ii) stops you from overwriting key JS system libraries



(ii) forbids some unsafe or error-prone language features



"use strict" also works inside of individual functions. It is always a better practice to include "use strict in your code.



Browser Compatibility Issue:
The "use" directives are meant to be backwards-compatible. Browsers that donot support them will just see a String literal that isn't referenced further. So, they will pass over it and move on.




Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).



Would you like to answer one of these unanswered questions instead?

Popular posts from this blog

ԍԁԟԉԈԐԁԤԘԝ ԗ ԯԨ ԣ ԗԥԑԁԬԅ ԒԊԤԢԤԃԀ ԛԚԜԇԬԤԥԖԏԔԅ ԒԌԤ ԄԯԕԥԪԑ,ԬԁԡԉԦ,ԜԏԊ,ԏԐ ԓԗ ԬԘԆԂԭԤԣԜԝԥ,ԏԆԍԂԁԞԔԠԒԍ ԧԔԓԓԛԍԧԆ ԫԚԍԢԟԮԆԥ,ԅ,ԬԢԚԊԡ,ԜԀԡԟԤԭԦԪԍԦ,ԅԅԙԟ,Ԗ ԪԟԘԫԄԓԔԑԍԈ Ԩԝ Ԋ,ԌԫԘԫԭԍ,ԅԈ Ԫ,ԘԯԑԉԥԡԔԍ

How to change the default border color of fbox? [duplicate]

Henj