leonbolierpictures
leonbolierpictures

Reputation: 11

different outputs for the same function

Can someoen please explain the different outputs for this 2 functions?

var reverse = function(string) {
    var myArray = string.split('').reverse().join('');
    return myArray;
}

alert(reverse("this is a string")); // gnirts si a siht



var reverse = function(string) {
    var myArray = string.split('');
    myArray.reverse();
    myArray.join('');
    return myArray;
}

alert(reverse("this is a string")); // g,n,i,r,t,s, ,s,i, ,a, ,s,i,h,t

Upvotes: 1

Views: 59

Answers (3)

Azad
Azad

Reputation: 5274

the myArray.join('') in your second function return a string in your case you are not asigning it to variable just return an array. It will return same results if you changed your code like this.

var reverse = function(string) {
    var myArray = string.split('');
    myArray.reverse();
    myArray = myArray.join('');
    return myArray;
}

Upvotes: 0

Josh Crozier
Josh Crozier

Reputation: 240978

In the second function, you are splitting a string, then returning the reversed array.

The .join() method doesn't alter the myArray variable it is operating on, thus it's like .join() isn't even being called. In other words,

myArray.join('');

isn't the same as:

myArray = myArray.join('');

This will give you the same results as your first function:

var reverse = function(string) {
    var myArray = string.split('');
    myArray.reverse();
    myArray = myArray.join('');
    return myArray;
}

..or you could just return the joined array:

return myArray.join('');

Upvotes: 1

dfsq
dfsq

Reputation: 193271

The problem with your second function is that you need to reassign result of join operation (or simply return myArray.join('')), otherwise it doesn't mutate original myArray. So you just return reversed array, not a string. What happens next is that alert calls toString method internally which is equivalent to myArray.join() (note, join is without arguments), which is the same as join(',') by default.

Correct code would be

var reverse = function(string) {
    var myArray = string.split('');
    myArray.reverse();
    myArray = myArray.join(''); // or simply return myArray.join(','); 
    return myArray;
}

Upvotes: 0

Related Questions