Joe Crawley
Joe Crawley

Reputation: 725

Problems swapping an array element in javascript

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

Answers (1)

Raekye
Raekye

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

Related Questions