# Need help with Truncate a string challange

Need help with Truncate a string challange
0

#1

Hello,
please, could someone check my code. It works for all unless for truncateString(“A-”, 1).
My code is as follow

function truncateString(str, num) {
// Clear out that junk in your trunk
var strLength = str.length;
var firstPart;
if (strLength > num) {
firstPart = str.slice(0, num - 3);
str = firstPart + “…”;
if (num <= 3) {
firstPart = str.slice(0, num);
str = firstPart + “…”;
}
}

return str;
}

Thank you.

#2

review the order of your if statements, particularly the 2nd and 3rd statements (hint: think about in what situation your 3rd statement will apply considering how your 2nd statement works)

#3

Thank you fentablar, but the problem is not in the order rather than missing another condition in the first if statement (num > 3).

#4

Maybe I’m not following you; your 1st if is:

…given that, how would amending it to use num > 3 make any difference (if str > num, why would the value of num matter)?

#5

Thank you again for your good question. To replay, please take a look at the two codes below:
first one:

var strLength = str.length;
var firstPart;

if (strLength > num && num > 3) {
firstPart = str.slice(0, num - 3);
str = firstPart + “…”;
}

if (strLength > num && num <= 3) {
firstPart = str.slice(0, num);
str = firstPart + “…”;
}
second one:
var strLength = str.length;
var firstPart;

if (strLength > num) {
firstPart = str.slice(0, num - 3);
str = firstPart + “…”;
}

if (strLength > num && num <= 3) {
firstPart = str.slice(0, num);
str = firstPart + “…”;
}
Now, for the first one the two if statements are totaly separated, while in the second code, they may interact between each other which make the logic of if statements incorrect.

#6

Well, if statements don’t interact with each other, they take an order of precedence which is predicated first by the order they appear in the function and second by their respective conditions.

Back to what I asked in my prior post, let me just point out that for this exercise, if str > num, then it really doesn’t matter what value num is, because you’re going to return the entirety of str regardless of what num is. So, “str > num && num > 3” and “str > num && num <=3” mean the same thing, because the only relevant part is the “str > num”.

Which, ultimately, means that the only thing your code is doing is looking for “str > num”… The code you have in your first post is actually closer to the mark, just need to swap the order of the 2nd and 3rd if statements.