Truncate a String Challenge Help

Truncate a String Challenge Help
0.0 0


I’ve been working on the Truncate a String solution and it works for me in JSbin. On the FreeCodeCamp challenge page it says it passes all of the test cases except one.: truncateString(“Absolutely Longer”, 2); However in the console of the challange page it gives the correct result. I need advice on what I am missing. Thank you!

var elips = "...";
var subtr = -3;

function truncateString(str, num) {
  if (str.length <=3 | num+subtr<=0 ) {
  subtr = 0; 
  elips = "...";
  } else if  (str.length-num<=0 ) {
  subtr = 0; 
  elips = "";
  } else { 
  elips = "...";
  subtr = -3;
  truncString = "";
  truncString = str.slice(0, num+subtr) + elips;
  return truncString;


truncateString("Absolutely Longer", 2);
//truncateString("A-", 1);
//truncateString("A-tisket a-tasket A green and yellow basket", 11);
//truncateString("Peter Piper picked a peck of pickled peppers", 14);


I’ve edited your post for readability. When you enter a code block into the forum, remember to precede it with a line of three backticks and follow it with a line of three backticks to make easier to read. See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.


The problem is arising from your use of global variables.

Global variables persist after function calls have completed, so we have to be very careful about modifying globals in functions. Your initial if assumes that substr is -3, but your else if sets substr to 0.


Sorry about the formatting.

I’ve placed the variables within the function. Thanks for the reminder. I will be sure to watch that closer from now on.
Since moving the variables gives the same results as before, I’m still curious why the result now passes even though it’s the same string.


If you run only the one test, it will give you the right results, but that’s because nothing has changed your global variables yet.



Wow, you are so smart. I never would have figured that out. Thanks so much!