Ask coding questions

← Back to all posts
Why variable is accessible via global object in Node.js?
EmilySeville7cf

Hello! For instance I have the following code:

When I run it via Run button it outputs 2 but when it is executed directly with node index.js command it prints undefined. How can I see default .replit config which used while running script? Maybe it help me answer my question.

Answered by SixBeeps [earned 5 cycles]
View Answer
Voters
EmilySeville7cf
Comments
hotnewtop
SixBeeps

According to the MDN Web Docs:

In a web browser, when scripts create global variables defined with the var keyword, they're created as members of the global object. (In Node.js this is not the case.)

So technically you shouldn't even have the ability to do what your code is doing normally.

But...

Take a look at this article, which says:

Note that in both NodeJS CommonJS modules and native ECMAScript modules, top-level variable declarations are scoped to the module, and are not, therefore added as properties to the global object.

So what might be happening is that the Run button uses a different interpreter than Node by itself, which is strange but not out of the question.

As for your side question, no; it is not possible to look at the default configuration for the Run button.

EmilySeville7cf

@SixBeeps, I've issued this problem to developers also. Thanks!