-2

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

var name = null;

function func(name) {
  // How to set the global variable with the passed value
}
2
  • In a browser environment all global variables are stored on the window namespace: window.name Commented Mar 13, 2016 at 21:24
  • @MitchKarajohn I assume that "global variable" actually means global variable :-) Commented Mar 13, 2016 at 21:29

3 Answers 3

1

Change the name of the parameter to something else. No other way, because it will always see the innermost name.

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

1 Comment

This is not true as Miroslav Saracevic just showed
1
var name = 'Name outer';

function func(name) {
  console.log(name);
  console.log(window.name);
}

func ('Name inner');

However, this would be bad practice and you should avoid having this situations.

2 Comments

Can you elaborate on why this is bad practice? +1
As Mitch said, only works if you have it in this exact structure, global in window scope. Would be better to pass it as arguments or have different names and generally making code more modular and readable. If you tend to stick to this way of making code, the next developer who sees this code will hate you and will have no idea from the glance what is going on there.
0

If you are really talking about a global variable this can be done this way:

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

in a browser or

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

in node.js but if you declared name within a function there is afaik no way to do that.

However, you should avoid gobal variables if possible because they are shared by all used code including libraries and you can't know if this has any side effects in case of a name colision.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.