Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does accessing variables declared without `var` work without having to use `require` in other files?

Tags:

node.js

Here's an example

$ cat main.js
App = {
  version : 1.1
};
require('./mymod.js');

$ cat mymod.js
console.log(App.version);

$ node main.js
1.1

Note how I declared App in main.js without var. This allowed me to access App from mymod.js without having to call require. If I declare App with a var, this won't work.

I want to understand why this happens? Is it the intended behaviour for node.js or a bug? Is this behavior consistent with ECMAScript or CommonJS standards?

This trick gives a powerful mechanism to circumvent the require module system of node.js. In every file define your objects and add them to the top level App namespace. Your code in other files will be automatically have access to those objects. Did I miss something?

like image 296
Jayesh Avatar asked Oct 21 '25 17:10

Jayesh


2 Answers

If you assign a variable without using var, it is automatically a global variable. That's just the way JavaScript works. If you put 'use strict'; (quotes required) at the top of your js file, this becomes an error instead.

like image 138
Chris Tavares Avatar answered Oct 23 '25 06:10

Chris Tavares


All has to do with local scope vs global scope.

You can even do this (which is much neater):

app.js:

exports = {
  version : 1.1
}; 

main.js:

var App = require('./app.js');
console.log(App.version);
like image 42
Naftali Avatar answered Oct 23 '25 08:10

Naftali