2

I'm trying to assign a variable to itself in a function, and if the variable has the same name as an argument to the function it doesn't seem to work, but does if they're not the same name. A code example shows this more clearly.

Is this behavior I should expect? This is a pared down example for my d3 use case which prompted this question. I've shown that below as well.

Non working example

var a;

function assign(a) {
    a = a;
}
assign("test")
console.log(a)

undefined

Working Example

var a;

function assign(b) {
    a = b;
}
assign("test")
console.log(a)

test

Use case

var data
d3.csv("data.csv", function(error, data) {
    //Doesn't work for me
    data = data
}
console.log(data)

undefined

vinayakj
  • 5,591
  • 3
  • 28
  • 48
canyon289
  • 3,355
  • 4
  • 33
  • 41

3 Answers3

5

In your first example, the argument a that is passed to the function shadows the variable a which is defined outside, so: a=a is assignment of the argument (that was passed to the function) to itself.

Tal
  • 145
  • 8
2

In Javascript the scope is functional level scope, so whenever the variable is referenced it is searched for its declaration in the containing scope(function), if it finds it it uses it else it keep searching in prototypical chain upto global scope. So in your case it tries to search a and it founds it as argument a so it stops the search there & uses a from argument.

So to avoid the conflict you have use two ways.

  1. Use the different names
  2. If you want to use the same name then use the explicit scope resolution.

Ex.

var a;

function assign(a) {
   Global.a = a //Global is placeholder here for outerscope that variable a is coming from.
}
assign("test")
console.log(a);

Useful links for more clear understanding

Community
  • 1
  • 1
vinayakj
  • 5,591
  • 3
  • 28
  • 48
0

you could use the window object to access the global variable.

var a;

function assign(a) {
    window.a = a; // specifying the scope.
};
assign("test")
console.log(a)

More information on 15-common-javascript-gotchas

sachin.ph
  • 1,078
  • 12
  • 24