0

I am trying to avoid using global variables in my server.js file but need variables accessible and writable by various functions. However, I am unsure if scope works the same way as on the client side (since it seems more 'hidden'). I read somewhere that modules have their own scope but if I place variables there and they are accessible in server.js isn't that the same thing as a global scope? For example:

//module.js

var config = [
  {var1: 1},
  {var2: 2},
  {var3: 3}
]

module.exports = {
  config
};

//server.js
const { config } = require("./config.js")

function function1() {
  var a = config[0].var1
  bar b = config[0].var2

  config[0].var3 = a+b // changing var3 value in module

}

Is using modules this way acceptable? If not what would be considered a better practice here?

Thanks

1

1 Answer 1

1

each module has own scope but you can import or export any of variables , functions and etc to other modules and use them in there, like change value of variables but the value will change in module that you imported , not in main

run code below and I think it works as you want it to.

//module.js
var config = [
  {var1: 1},
  {var2: 2},
  {var3: 5} 
]

console.log(config[2].var3) //5

module.exports = config

//server.js
const  config  = require("./app.js")

function function1() {
  var a = config[0].var1
  var b = config[1].var2

  config[2].var3 = a+b // changing var3 value in module
  console.log(config[2].var3) 
}
function1() //3
console.log(config[2].var3)//3


//client.js
const  config  = require("./app.js")
console.log(config[2].var3) //5
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for the info. Just to clarify, the client.js above is still on the server side isn't it? As my understanding is that 'require' is not available on the client side public js modules.
i had a mistake ,actually the name of module.js is app.js in my code in my previous answer to you ,i specified module.js because i wanted ,You understand better,please replace
please replace app.js to module.js or vice versa
and those modules are separate , and their name is desired,actually i created them to show you how modules can deal together

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.