Reputation: 725
I'm a TA and a student came in asking why the following code didn't swap the first 2 elements in an array and instead resulted as undefined. Here's the code the student showed me:
var swapFirstTwoElementsOf = function (a) {
a = [a[1],a[0]].concat(a.slice(2, a.length));
}
Why does this return undefined?
Upvotes: 0
Views: 372
Reputation: 5131
You need to return the variable. The local reference is reassigned, but the original variable a is not. You need to do something like
var swapFirstTwoElementsOf = function (a) {
return [a[1],a[0]].concat(a.slice(2, a.length));
}
var myArray = [0, 1, 2, 3];
myArray = swapFirstTwoELementsOf(myArray);
Previously, the function was evaluating to undefined because it wasn't returning anything.
Upvotes: 4