3

How to access global variable from a function when the name is same as argument name in Node.js ?

var name = null;

function func(name) {
  // How to set the global variable with the passed value
}
3

1 Answer 1

4

Assuming you're talking about a node.js module, your first name variable is not actually global - it's just in a higher scope in the module (defined at the module level). As such, there is no way to access it from within a function that has an argument with the same name in Javascript.

You will have to change the name of one or the other of the two conflicting names in order to be able to access both.

var name = null;

// change the name of the argument
function func(aname) {
     name = aname;
}

func("Bob");
console.log(name);   // "Bob"

If it was actually a global in node.js, then you could access it with the global prefix as in:

global.name = "Bob";

function func(name) {
    global.name = name;
}

function("Alice);
console.log(global.name);   // "Alice"

FYI, in general I'd stay away from global variables named name. If this were browser code, there's already a window.name that would conflict.

Here's a little primer on actual using global variables in node.js (which is generally not recommended). Sharing exported properties/variables/methods is what is recommended in node.js.

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

Comments

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.