Truncating a string that contains the .length; Isnt it just a number?

hey so I couldnt find an explanation on why the solution given works for when your feeding the function a number through the .length method. The solution code is :

function truncateString(str, num) {
if (str.length > num) {
return str.slice(0, num) + “…”;
} else {
return str;
}
}

I just want to know where the test case is feeding it a number through the length method how is this function getting access to the string?

Your code so far
My code so far is:
function truncateString(str, num) {

let x = ‘’;

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

x+=str[i];

}

x+=‘…’;
console.log(x);
return x;
}

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



**Your browser information:**

User Agent is: <code>Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36</code>

**Challenge:**  Basic Algorithm Scripting - Truncate a String

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

Hi @KC1990

I am not sure if I have understood your question but your code is good.
You just need to handle those cases are not working for.
For example, using this as test or console.log():

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

You need to improve your function because of this: if it is longer than the given maximum string length (second argument).
What happen inside your function is the second argument is equal or higher than str.length??

This tool helps to visualize your code running: Python tutor, it has an option for ES6 JavaScript as well.

I hope this helps, keep the good work!!