3

I'm still having some trouble understanding the scope of variables inside a node.js app. In regular javascript a nested function has access to the variables of it's parents. In node, this doesn't seem the case.

Here i have the file app.js that has a variable 'bookies' and a require 'routes'. The trouble i'm having is that the variable 'bookie' is not available in my routes.js file.

Why is that?

enter image description here

2
  • is it just routes you want to pass to or any modules you create? Commented Feb 19, 2014 at 14:48
  • I'm just trying things out so i can understand the concepts. Let's say i want to pass the variable to any module? Commented Feb 19, 2014 at 14:49

1 Answer 1

2

If you want to have bookie defined in the routes require you should pass the bookie like this:

var routes = require("./routes")(bookie);

This is because in Node, The top-level scope is not the global scope; var something inside a Node module will be local to that module.

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

5 Comments

then how would you pass variables from module to module?
But if i do this: var routes = require("./routes/routes")(bookie) i get : TypeError: object is not a function
If you want to pass variables from module to module you will have to create get and set functions which both modules can access. Can you show your routes file in the question?
Thx for you comment. I'm not looking for an answer for my particular situation but more for a general understanding of how the scope inside node.js works. As i come to understand, there isn't something like 'global' scope where i can declare a variable and then, trough closures access them. I have to pass them as parameters.
Well this is the best practice to do that, if you really want to use something global (eww) you can always use the global scope like: global.bookie = "jow"

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.