React javascript syntax error on question mark and dot

Viewed 588

while I am working on react, I got syntax error on this line:

return str?.length > n ? str.substr(0, n - 1) + "..." : str;enter image description here

I strongly believe there is nothing wrong with the syntax. Please help me out with this.

Thank you

2 Answers

Here's what you need return str && str.length > n ? str.substr(0, n - 1) + "..." : str;

That's an improper way of using Conditional (ternary) operators. Based here.

A Condition is followed by a question mark (?).

Probably because it found a question mark (?) together with a string (which should have a space in between from str?.length) and the dot (.) should be next to a variable (that is valid for using .length.

You should write it this way.

return str.length > n ? str.substr(0, n - 1) + "..." : str;
Related