Is this a bad way of doing this?

Tell us what’s happening:

  **Your code so far**

function truncateString(str, num) {
let result = ""
for (let i = 0; i < num; i++) {
  result = result + str[i];
}
if (result.length < str.length) {
  return result + "...";
} else {
  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/88.0.4324.190 Safari/537.36.

Challenge: Truncate a String

Link to the challenge:

it is not bad, it works

though you may consider how to reduce unnecessary code, for example, if the string is not to be truncated, building result is useless, you don’t even use it

function truncateString(str, num) {
  let s = "";
  for (let i = 0; num < str.length ? i < num : i < str.length; i++){
    s += str[i];
  }
  return num < str.length ? `${s}...` : s 
}

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

This way ensures you only loop as long as you need by making us of ternary, and then another ternary for the return to see wether you needed the ellipses .

@ilenia Like this?

function truncateString(str, num) {
  if(num >= str.length) {
    return str;
    } else {
    let result = ""
    for (let i = 0; i < num; i++) {
    result = result + str[i];
  }
    return result + "...";
  }
}
truncateString("A-tisket a-tasket A green and yellow basket", 8);

thats really good! whenever there are specific conditions when you can exit early, check for those first to avoid unnecessary calculations.

I forgot if you would have learned these at that point in the challenges, but there is a specific method in the String Object that can do what the for loop is doing in your code: String.prototype.slice(). If you’d like you can read about this method here on MDN

Yeah, and it was in the solutions. I still need to work on using those functions more.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.