Truncate a String-why my solution works?

Tell us what’s happening:

Your code so far


function truncateString(str, num) {
// Clear out that junk in your trunk
if(num<str.length){
return str.slice(0,num)+"...";
}
return str
}

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

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36.

Challenge: Truncate a String

Link to the challenge:
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-algorithm-scripting/truncate-a-string

this is my solution,it works . but i dont understand why lol
reading the definition of slice on MDN-
" The slice() method returns a shallow copy of a portion of an array into a new array"

the thing is that “str” is not an array.its a string. so how does this work?

Strings also have their version of slice(). It’s conceptually not different from the array slice() function.

1 Like

got it, thanks for the link.