Is the if
statement in the following example redundant?
if (str[0] === ' ') {
str = str.trimStart()
}
It seems unnecessary to me since trimStart()
does not seem to have any negative effect on a string without a space at the beginning. Additionally, if the string does have a space at the beginning, you are running twice as many operations as needed.
Is the if
statement ever necessary in situations like the one above?
The if
is not necessary, but you should save the trimmed value somewhere, like
str = str.trimStart();
-- Edit --
"Is the 'if' ever necessary...?"
The test that you are doing in the original is redundant. But you might want to check that str has a value and/or check that this value is a string before calling trimStart(), like
if (str && typeof str === 'string') ...