Blog coding and discussion of coding about JavaScript, PHP, CGI, general web building etc.

Tuesday, December 22, 2015

What does

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.

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

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

Answer by seth for What does "use strict" do in JavaScript, and what is the reasoning behind it?


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.

Answer by Pascal MARTIN for What does "use strict" do in JavaScript, and what is the reasoning behind it?


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:

  • It catches some common coding bloopers, throwing exceptions.
  • It prevents, or throws errors, when relatively "unsafe" actions are taken (such as gaining access to the global object).
  • It disables features that are confusing or poorly thought out.

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.

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

Answer by Stephen for What does "use strict" do in JavaScript, and what is the reasoning behind it?


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).

Answer by Jamie Hutber for What does "use strict" do in JavaScript, and what is the reasoning behind it?


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

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.  

Answer by user2436758 for What does "use strict" do in JavaScript, and what is the reasoning behind it?


"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.

Answer by Pank for What does "use strict" do in JavaScript, and what is the reasoning behind it?


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.

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.

Answer by DWoldrich for What does "use strict" do in JavaScript, and what is the reasoning behind it?


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!

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.

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.

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 refactorings 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.

Answer by RENGANATHAN M G for What does "use strict" do in JavaScript, and what is the reasoning behind it?


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

Answer by FutureNerd for What does "use strict" do in JavaScript, and what is the reasoning behind it?


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.

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

Answer by little dinosaur for What does "use strict" do in JavaScript, and what is the reasoning behind it?


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.

Answer by Shubh for What does "use strict" do in JavaScript, and what is the reasoning behind it?


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.

Few important things which I have learned after using 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.

Uncaught ReferenceError: nameoftree is not defined

Sample

Eliminates with statement :

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

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.

Answer by gprasant for What does "use strict" do in JavaScript, and what is the reasoning behind it?


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

List of features (non-exhaustive)

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

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

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

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

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

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

  7. Forbids the with keyword eval in strict mode does not introduce new variables

  8. Forbids deleting plain names (delete x;)

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

  10. 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. )

  11. arguments.callee is not supported

[Ref: Strict mode, Mozilla Developer Network]

Answer by Myni for What does "use strict" do in JavaScript, and what is the reasoning behind it?


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.

Why Strict Mode?

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

Answer by Elyasin for What does "use strict" do in JavaScript, and what is the reasoning behind it?


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.

Directives are similar to statements, yet different.

  • use strict does not contain key words: The directive is a simple expression statement, which consists of a special string literal (in single or double quotes). JavaScript engines, that do not implement ECMAScript 5, merely see an expression statement without side effects. It is expected that future versions of ECMAScript standards introduce use as a real key word; the quotes would thereby become obsolete.
  • use strict can be used only at the beginning of a script or of a function, i.e. it must precede every other (real) statement. It does not have to be the first instruction in a script of function: it can be preceded by other statement expressions that consist of string literals ( and JavaScript implementations can treat them as implementation specific directives). String literals statements, which follow a first real statement (in a script or function) are simple expression statements. Interpreters must not interpret them as directives and they have no effect.

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.

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):

  • You cannot use the with-statement in strict mode.
  • In strict mode all variables have to be declared: if you assign a value to an identifier that has not been declared as variable, function, function parameter, catch-clause parameter or property of the global Object, then you will get a ReferenceError. In normal mode the identifier is implicitly declared as a global variable (as a property of the global Object)
  • In strict mode the keyword this has the value undefined in functions that were invoked as functions (not as methods). (In normal mode this always points to the global Object). This difference can be used to test if an implementation supports the strict mode:
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.)

  • 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.)

  • In strict mode, when passing code to eval(), you cannot declare or define variables or functions in the scope of the caller (as you can do it in normal mode). Instead, a new scope is created for eval() and the variables and functions are within that scope. That scope is destroyed after eval() finishes execution.
  • In strict mode the arguments-object of a function contains a static copy of the values, which are passed to that function. In normal mode the arguments-object has a somewhat "magical" behaviour: The elements of the array and the named function parameters reference both the same value.
  • In strict mode you will get a SyntaxError when the delete operator is followed by a non qualified identifier (a variable, function or function parameter). In normal mode the delete expression would do nothing and is evaluated to false.
  • In strict mode you will get a TypeError when you try to delete a non configurable property. (In normal mode the attempt simply fails and the delete expression is evaluated to false).
  • In strict mode it is considered a syntactical error when you try to define several properties with the same name for an object literal. (In normal mode there is no error.)
  • In strict mode it is considered a syntactical error when a function declaration has multiple parameters with the same name. (In normal mode there is no error.)
  • In strict mode octal literals are not allowed (these are literals that start with 0x. (In normal mode some implementations do allow octal literals.)
  • In strict mode the identifiers eval and arguments are treated like keywords. You cannot change their value, cannot assign a value to them, and you cannot use them as names for variables, functions, function parameters or identifiers of a catch block.
  • In strict mode are more restrictions on the possibilities to examine the call stack. arguments.caller and arguments.callee cause a TypeError in a function in strict mode. Furthermore, some caller- and arguments properties of functions in strict mode cause a TypeError when you try to read them.

Answer by zangw for What does "use strict" do in JavaScript, and what is the reasoning behind it?


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

  • 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.

  • Declaring function in blocks

    if(a
  • Octal syntax

    var n = 023;  
  • this point to the global object.

     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;

  • Using eval or arguments as variable or function argument name

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

Source:

Transitioning to strict mode

Strict Mode

strict mode you should use it


Fatal error: Call to a member function getElementsByTagName() on a non-object in D:\XAMPP INSTALLASTION\xampp\htdocs\endunpratama9i\www-stackoverflow-info-proses.php on line 72

0 comments:

Post a Comment

Popular Posts

Powered by Blogger.