0

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?

1

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

3 Comments

No problem. I often spend ages on a problem ,finally ask SO, then find some silly solution. Cheers!
Note that var tmp = a[0]; a[0] = a[1]; a[1] = tmp; would swap the first two elements of the original array without the function needing to return anything - you can't reassign the original variable from inside the function, but you can modify the object it already references. (Though I realise the code was a question from a student so suggesting alternative methods may or may not be appropriate.)
If I noticed the student/TA part I would claim to be the student to mess around!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.