Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between running Node.js program from file and from terminal?

I was experimenting with this code using node a.js command:

console.log(this); // {}

(function func() {
  console.log(this); // Object [global]
})();

and:

'use strict';

console.log(this); // {}

(function func() {
  console.log(this); // undefined
})();

and the answer for these outputs I found here: What is the 'global' object in NodeJS

But when I run same commands from terminal by itself:

  1. Open PowerShell
  2. Type node
  3. Type .editor
  4. Copy-paste the same commands
  5. Press Ctrl + D

I got:

console.log(this); // Object [global]

(function func() {
  console.log(this); // Object [global]
})();

and:

'use strict';

console.log(this); // Object [global]

(function func() {
  console.log(this); // undefined
})();
  • OS: Windows 11
  • PowerShell: 7.5.3
  • Node.js: 22.15.0
like image 237
EzioMercer Avatar asked Nov 01 '25 02:11

EzioMercer


1 Answers

When I run the code using node a.js, the file is treated as a CommonJS module. In a module, the top-level this refers to module.exports, which is an empty object by default. So for me:

console.log(this); // {}

Then, when I call a regular function (without strict mode),

(function func() {
  console.log(this); // Object [global]
})();

When I enable 'use strict', the top-level this is still {} (since it's still a module), but inside the function, this becomes undefined because strict mode prevents it from defaulting to global.

However, when I switch to the Node REPL by opening PowerShell, typing node, then .editor, the behavior changes. In the REPL, the code is not treated as a module—it runs in the global context. That means that for me, at the top level, this is actually the global object:

console.log(this); // Object [global]

Inside a normal function (without strict mode), this is also the global object, so I see:

(function func() {
  console.log(this); // Object [global]
})();

If I enable 'use strict', the top-level this in the REPL still refers to the global object (because REPL doesn't use the module wrapper), but inside the function, this is undefined due to strict mode:

'use strict';

console.log(this); // Object [global]

(function func() {
  console.log(this); // undefined
})();
like image 75
Amric Paul Avatar answered Nov 02 '25 15:11

Amric Paul



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!