Skip to content

Truncate a string with ternary operator #7669

Closed
drk7891 opened this Issue · 1 comment

2 participants

@drk7891

Challenge Truncate a string has an issue.
User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_3) AppleWebKit/601.4.4 (KHTML, like Gecko) Version/9.0.3 Safari/601.4.4.

My code:

function truncate(str, num) {
  var newString = str;
  var trim;

  num < 3 ? trim = num : trim = num - 3;

  if(str.length > num) {
    newString = newString.slice(0, trim) + "...";
  }
  return newString;
}

truncate("A-tisket a-tasket A green and yellow basket", 11);

Using a ternary operator to check if the num is less than 3 results in all tests passing but throws an error in the editor. The error is on num - 3 and states Expected an assignment or function call and instead saw an expression.

@ltegman
Free Code Camp member

This is normal. It's the linter telling you this is a bad practice use of a ternary that results in hard to read code. It should pass because the code isn't technically wrong, it's just something you probably want to not do. Thanks and happy coding!

@ltegman ltegman closed this
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.