Basic Algorithm scripting: Truncate a script

Hello everyone, first time posting and I want to say thank you to everyone who keeps this site running and helps out newbies like myself.

I’m currently on the ‘Truncate a string’ lesson in ‘basic algorithm scripting’ and my code is ticking all the boxes except 1 and I’m not sure why. I get that it’s not the most efficient method, I looked at the hint section when it wasn’t working and realised I should have been using slice but I feel that it should work anyway and I’m unsure as to what the problem is, my current code is:

function truncateString(str, num) {

  let array = str.split("")

  let answer = ""

  for (let i =0; i<num; i++) {

    answer= answer + array[i]

  } if (str.length > num){

    answer = answer + "..."

  } console.log(answer)

  return answer;


truncateString("A-tisket a-tasket A green and yellow basket", "A-tisket a-tasket A green and yellow basket".length + 2); 

it currently works on every input except the one shown, it can process .length but not .length+2 which currently brings back the string followed by ‘undefinedundefined’. What have I done wrong and is their a way to resolve this?

Thank you for all assistance provided!

Welcome, Arron.

For future posts, please use the Ask for Help button on the specific lesson/challenge in question. This will create a pre-populated post with your current code already in it, as well as some other useful information. You will still be able to add any necessary information, before posting.

To answer your question:

This is the test you are failing:

truncateString(“A-tisket a-tasket A green and yellow basket”, “A-tisket a-tasket A green and yellow basket”.length + 2);

This is the code that is causing the problem:

for (let i =0; i<num; i++) {
    answer= answer + array[i]

Add this just before the for loop in your function to see why:


Hope this helps

Ah of course, I see what I’ve done now. My for loop is overshooting. Thank you for guiding me towards finding the answer and I’ll be sure to use the ‘ask for help’ button next time.

1 Like