Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS Strict Mode

Are there any advantages to using "use strict" in NodeJS? For example, a global object is not a good idea to use, as all your requests will mutate said object (assuming the object in question should be unique to each user, of course). In this case, using strict mode would have been a good idea, no?

I feel like strict mode is a good idea to pair with Node, but I haven't been able to find any pros or cons to it via google.

Disclaimer: I know what use strict does, this question is focusing on the server sided pros/cons!

like image 922
Sterling Archer Avatar asked May 20 '14 16:05

Sterling Archer


People also ask

What is strict mode in Nodejs?

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.

Do I need use strict in node?

All Node. js code are interpreted by the V8 JavaScript engine. The V8 JavaScript Engine is an open source JavaScript engine developed by Google for Chrome web browser. So, there will be no major difference how "use strict"; is interpreted by the Chrome browser and Node.

Should I use strict mode JS?

First, all of your code absolutely should be run in strict mode. Core modern javascript functionality is changed (see . call() and apply()) or disfigured (silent Errors) by executing code outside of strict mode.


1 Answers

Well, clarity and speed.

Unlike what the popular answers and question in SO say - the real primary goal of strict mode and the "use strict" directive is to eliminate dynamic scoping in JavaScript which is why changing arguments via arguments and changing arguments itself is not allowed, why with is not allowed, and so on.

Clarity

Strict mode does not allow dynamic scoping, so you can always statically know what a variable refers to. with statements, changing variables via arguments and other types of non-static scoping make code less readable, in non strict mode:

// example from referenced thread
// global code
this.foo = 1;

(function () {
  eval('var foo = 2');

  with ({ foo: 3 }) {
    foo // => 3
    delete foo;
    foo // => 2
    delete foo;
    foo // => 1
    delete foo;
    foo // ReferenceError
  }
}());

This sort of headache is avoided in strict mode.

Speed

Strict mode is much faster than non strict mode. A lot of optimizations can only be made in strict mode since it can assume a lot more about what doesn't change and how to resolve references. V8 internally uses this extensively.

References:

  • Still not sure what dynamic/lexical scope is? Read this article by @EricLippert
  • This Excellent write up by @Domenic and the discussion it references.
like image 164
Benjamin Gruenbaum Avatar answered Sep 20 '22 22:09

Benjamin Gruenbaum