Write a function without using join()? JS

My code doesn’t work. I would like to get ‘Mike-Cox’ but it returns only ‘Mike-’.

Looking for your help!

Here is my code

var arr=;
var str=’ ';

function join(arr,str){
var i;
var result =’ ’
for (i=0;i < arr.length -1 ; i ++){
return result + arr[i] + str;

}
if (i = array.length -1){
return arr[i];
}
}
console.log(join([‘Mike’, ‘Cox’], ’ - '));

Instruction

Write a function named join that takes an array and a string and returns all the elements joined by the passed string. Do not use join() method.

For example,

console.log(join([‘Mike’, ‘Cox’], ’ - ‘); // ’ Mike-Cox’

console.log(join([‘A’, ‘B’], C )); // ‘ACB’

1 Like

when you use return inside a function it will return value and then exit function and all code after return statement never runs.
in your case you need to store all value inside result variable and before adding value to result check for last value of the array . if the value is the last value of the array then add it to result and then return the result. i.e

function join(arr,str){
   var result ="";
   for (var i=0;i<arr.length;i++){
       if (i == arr.length -1){
          result += arr[i];
          return result;
       }
       result += arr[i] + str;
   }
}
console.log(join(['Mike', 'Cox'], ' - '));
2 Likes

It worked! Thank you so much!

It is great that you solved the challenge, but instead of posting your full working solution, it is best to stay focused on answering the original poster’s question(s) and help guide them with hints and suggestions to solve their own issues with the challenge.

We are trying to cut back on the number of spoiler solutions found on the forum and instead focus on helping other campers with their questions and definitely not posting full working solutions.

Thank you for understanding.