JavaScript Corners – Part 2

JavaScript Corners – Part 2

I’m continuing my series on JavaScript corner cases.

Last time I looked how function names interact with each other and with variable names. Today I’m looking at how parameters interact with variables.

Take a look at the following code snippet:

(function(x) {
  var x;
  console.log('x', x);
})(1);

It creates a function that takes a parameter named x, and then calls that function with an argument 1 with a value of 1.  The curve ball here is that we’ve then also declared a variable with exactly the same name as a parameter. Does the symbol x then refer to the parameter or the variable? Do variables shadow parameters?

The variable hasn’t been given a value, so it must be undefined, right? If x refers to the variable, then the console output will be “undefined“, while if x refers to the parameter, then the console output will be “1“. So which is it…

On my computer, using node, this outputs 1. So it seems x refers to the parameter, and not the variable… right?

But now consider the following code snippet:

(function(x) {
  var x = 2;
  console.log('x', x);
})(1);

This creates a variable, and then gives it the value 2. According to our theory thus far in this post, the console will still output the value 1, since the x refers to the parameter and not the variable, as we saw from the previous snippet.

But if you run this code, it actually outputs 2. So it seems that it’s not that variables or a parameters “win” the battle to get into the namespace. Rather, it seems that parameters actually are themselves variables, and in the same namespace. The parameter x and the variable x are actually one and the same.

I’ll leave you with this bonus challenge: what does the following do?

(function (x) {
  var x;
  arguments[0] = 2;
  console.log(x);
})(1);

 

 


  1. You may have heard of parameters being called “formal parameters”, and arguments being called “actual parameters”, but I think this originates largely from people who didn’t understand the distinction and so confused things for everyone else 

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.