1

I am trying to run this piece of code in browser and compiler and getting two different outputs. What could be the cause for this `

'use strict';

var fName = 'Matilda';
 const jonas = {
     fName: 'jonas',
     year: 1991,
     greet: ()=> console.log(`Hey, ${this.fName}`),
 };

 jonas.greet(); 

`

Browser Output: Hey, Matilda

Compiler Output: Hey, undefined

I have tried running this code in several different compilers, and getting the same output. I was expecting a consistency in output between environments. I'll be glad if someone can give me a good theoretical explanation for the same.

  • Simply typing "use strict" into your console does not enable strict mode. Replace your `console.log` with `console.log(this)` to see the effect. – user229044 Dec 21 '22 at 17:28

1 Answers1

1

The sites which embed your code generally do some preprocessing for security reasons. This results in "use strict" not being the first line in the script so strict mode isn't triggered.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • Is this true, or is this backwards? AFAIK the behavior here is that strict mode is *not* being activated in the console, where `this` is actually `Window` inside the method. In the mentioned online REPLs, `this` is assigned to the nameless global object. When I use this method, Chrome's console reports `false` while the online REPL reports `true`: https://stackoverflow.com/questions/10480108/is-there-any-way-to-check-if-strict-mode-is-enforced – user229044 Dec 21 '22 at 17:31