Search code examples
javascriptscopeclosuresshadowhoisting

Assigning a variable to itself in a function


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


Solution

  • 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.