0

Simple question from a newbie here...

I am trying to create a function that accepts an array and an empty string. The function will then perform the .join() method on the array, and is supposed to set the result to the empty string.

The function seems to join (checked with console.log), however it doesn't set the result to the variable outside. What am I missing here?

The code

//empty string
var newStr ='';

var myArr = ['it','was', 'the', 'best', 'of', 'times'];

var rejoiner = function (arr, str) {
  str = arr.join(' ');
  //checking that the function is working
  console.log(str);
}

Then, run the function rejoiner, passing in myArr and newStr...

rejoiner(myArr, newStr);

Then check to see if newStr was set (failure! not set!)...

newStr;
Kian Alavi
  • 27
  • 4
  • Javascript is pass-by-value. See also this question: http://stackoverflow.com/questions/6605640/javascript-by-reference-vs-by-value – Thom Wiggers Jul 25 '15 at 21:08

3 Answers3

1

It almost works as you wrote it. If you return str from the function, you can set newstr that way.

//empty string var newStr =''; 
var myArr = ['it','was', 'the', 'best', 'of', 'times']; 
var rejoiner = function (arr) { 
    var str = arr.join(' '); //checking that the function is working 
    console.log(str); 
    return str;
};

newStr = rejoiner(myArr);
DarthDerrr
  • 461
  • 3
  • 9
0

Function parameters are copies. It's as if you'd written

var arr = myArr, str = newStr;
str = arr.join(' ');
console.log(str);

Assigning to str doesn't change newStr. In JavaScript, f(x) can't change x.

melpomene
  • 84,125
  • 8
  • 85
  • 148
0

It just worked fine for me!:

//empty string
            var newStr ='';

            var myArr = ['it','was', 'the', 'best', 'of', 'times'];

            var rejoiner = function (arr, str) {
              str = arr.join(' ');
              //checking that the function is working
              console.log(str);
            }

            rejoiner(myArr, newStr);

Check your console log!

FlokiTheFisherman
  • 224
  • 1
  • 5
  • 13