"use strict" directive doesn't seem to work in server.js

I’ve added “use strict” to the top of my serveless server.js file and it appears to have no impact. Let me give an example below:

"use strict";

exports = { ... }

function myFunction() {
  x=1   // This should throw error under "use strict"

When I run fdk validate, no error is raised
When myFunction is called, no error is raised.

Am I doing this wrong?

Seems i may have answerd my own question - I experimented and put “use strict” in the function. Then it works as expected.

Is there a way to set “use strict” at global level in serverless server.js file?

Note: “fdk validate” does not raise the error. It only gets raised at runtime. I assume there is not a way to force it to validate strict mode errors?


This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.

I reckon this nuance is part of JS as a language.

use strict; has a couple of advantages,

  1. Eliminates some JavaScript silent errors by changing them to throw errors.
  2. Fixes mistakes that make it difficult for JavaScript engines to perform optimizations: strict mode code can sometimes be made to run faster than identical code that’s not strict mode.
  3. Prohibits some syntax likely to be defined in future versions of ECMAScript.

When the JS engine needs to execute the code, the engine parses it to give the developer advantages. This parsing happens when execution context (function) is invoked, not declared.

'use strict;

function myFunc(){
  x = 1;

exports = {..}
  1. In a typical server.js file, we don’t invoke the sever.js as a module. Instead of a product event like onTicketCreate only invokes the handler - onTicketCreateHandler().
  2. onTicketCreateHandler()'s execution context should have "use strict"; statement declared for the JS Engine to drive advantages of it in the current function definition.
  3. Usually, it’s simply onTicketCreateHandler() invokes and references to function or variable declarations out side of exports = {}. JS Engine further executes these functions. In above example myFunc() definition.
  4. Nowhere server.js is treated as an execution context in itself. Usually, node applications organize files in terms of modules and import them – where each module is treated as execution context.

Now, look at the following example.

Above, I had server.js to be treated execution context in itself by running node server.js.

It immediately throws errors.

This leaves us to let JS Engine know to execute the code in strict mode by having it enabled inside of function which you already figured.

cc: @stevemc

1 Like

This topic was automatically closed 6 days after the last reply. New replies are no longer allowed.