1

In browser, diffrent javascript file share one scope:

a.js:

var a=1; //we add "var", so we not intent it be a global var.

b.js:

console.log(a) //a=1, but b.js can also see this var!

In nodejs:

a.js ....

b.js ....

console.log(a)// b.js cannot see the var, declare by "var" keywork

is there any doc say those difference ?

3
  • var a=1 does not make a not global variable (in browser), it depends on where you put this declaration (scope) Commented Nov 26, 2015 at 13:38
  • in file beginning,not in a funciton Commented Nov 26, 2015 at 13:40
  • So on global scope.. (browser) Commented Nov 26, 2015 at 13:40

2 Answers 2

2

that is correct. All of the files are loaded in the browser combined but in node.js uses modules per file so basically to combine the files from b.js you need to do

var a=require('a.js');

then your variable will be in a.a

for this to work you need to exports.a=1 in a.js

Be sure to keep in your mind that while javascript is the same language, different programming techniques are used in frontend and backend.

Sign up to request clarification or add additional context in comments.

Comments

1

nodejs encapsulates scope per file, sort of like ruby. If you want to share variables you should export them:

file1.js:

exports.a = 5;

file2.js:

exports.b = 6;

main.js:

var file1 = require('./file1.js');
var file2 = require('./file2.js');
console.log(file1.a); // 5
console.log(file2.b); // 6

Anything you export in a file by assigning to export.variablename = yourObject; will be accessible when you include the file from elsewhere: var exportedStuff = require('./file.js') would let you access yourObject at exportedStuff.variablename.

The reason for all of this is to force you to be more organized about how you write your code. As opposed to just slapping global variables around everywhere, it forces you to organize your code into modules, and also gives you the ability to emulate private scoping in an easier way than on the web.

In the web when you omit var, and just have varname = 5 then when variable does not already exist, it's the same as saying window.varname. This is NOT the case in nodejs. In Node if you want to use global you must do global.varname = 5

2 Comments

but, just like browser, if you dont add any "var" in a variable, then all var can see each other. this confuse me.
actually, if you dont prefix a var in js file A, then even in nodejs, js file B also can see this var. I have make a test, in my first nodejs project. windows7, and a recent nodejs version

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.