18

I'm a new to node.js and javascript.I checked code examples of node.js and it used use strict mode.

For example, a server.js:

'use strict';
//some server code

Also, I got to know that use strict is present at head of every js file. It confused me and so I want to know what is best practice in Nodejs to use strict mode?


Thank you all, My question is focus on the strict mode. In this mode, some code mistake can be reported. In back-end, the strict error reporter also run? And If I need use it, I should add it in every js file header? Or add it in main file(server.js or etc.) head? Or use some node.js self style?

Edward
  • 352
  • 1
  • 3
  • 14
  • 1
    There is no difference from browser js. It just enables the strict mode. – zerkms Jun 04 '15 at 03:22
  • 1
    What are you asking? Are you asking if strict mode should be used in nodejs development? If so, the answer is [YES](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode), for the same reason it is a recommended practice in browser Javascript development too. – jfriend00 Jun 04 '15 at 03:23
  • 1
    You probably want to read this: http://stackoverflow.com/q/1335851/218196 – Felix Kling Jun 04 '15 at 03:30

3 Answers3

13

Use it always. If nothing else, it ensures that your code is properly written, and cross browser compatible as it can be. It also will reveal mundane syntax errors that would otherwise go unfound, and lead to hours of unnecessary debugging.

  • Thx, You mean use it in every js file? – Edward Jun 04 '15 at 09:43
  • correct. You place it as the very first line your js files, or as the first line in a function. You usually do the later if you are concatenating js files, and each files contains a self executing function. – Jeffrey A. Gochin Jun 04 '15 at 12:29
  • 2
    @JeffreyA.Gochin when you are in node (as OP mentioned) the cross browser argument goes out the process (because node doesn't have window :P; See what I did there ?) – Nicu Surdu Jun 23 '17 at 14:12
  • 4
    What do you mean "cross-browser"? The question is about Node.js. – Daniel Darabos Aug 30 '17 at 08:32
6

“use strict” is a behavior flag you can add to to first line of any JavaScript file or function. It causes errors when certain bad practices are use in your code, and disallows the use of certain functions, such as with.

References:

  1. Restrictions on Code in Strict Mode by Microsoft MSDN
  2. Node.js Best Practices
1

Nodejs is server-side javascript, so many coding practices are similar in both. So using strict mode is common.

It ensures that you are not violating certain coding conventions like undeclared variables x=14;, use of specific variable names arguments,eval which are names of few global variables and functions.

Saba
  • 3,418
  • 2
  • 21
  • 34