A-tisket a-tasket A green and yellow basket".length + 2 error

**I am trying to to return truncate string. It’s returned 5 tasks but error on **

"A-tisket a-tasket A green and yellow basket", 
"A-tisket a-tasket A green and yellow basket".length + 2

function truncateString(str, num) {
  // Clear out that junk in your trunk
  let result = "";
  for (let i=0; i<num; i++) {
    result += str[i];
  }
  if (num < str.length) {
    result = result + "...";
  } else if (num >= str.length) {
    result = result;
  }
 return result;
}

truncateString("A-tisket a-tasket A green and yellow basket", 8);

In the test case you reference, the value of num is 2 more than the length of str, so during the last two iterations of the for loop, str[i] reference elements which do not exist, so str[i] in those last two iterations are undefined, which is why your function returns “A-tisket a-tasket A green and yellow basketundefinedundefined” instead of the correct value of “A-tisket a-tasket A green and yellow basket”.

1 Like

thank you very much for your response. I really appreciate it. :+1::+1::+1:

improve this with ternary if https://codeburst.io/javascript-the-conditional-ternary-operator-explained-cac7218beeff