Dogshit Dogshit - 3 months ago 8
Javascript Question

What does string.split do?

i know what string.split() does but im trying to understand someones React app, and i came across this:

newStr = newStr.split ? newStr.split(' ').reverse().join(' ') : newStr;

Answer

In that context, newStr.split is testing to see whether newStr has a .split property - if it does, it assumes it is a method and calls .split(' ').reverse().join(' ') (reversing the order of words), otherwise it returns newStr unaltered.

That code will result in an error if newStr is null or undefined, or if it is some object with a .split property that is not a function that returns an array.

(As mentioned by Bergi) it would make more sense to test the type of newStr directly:

newStr = typeof newStr === "string" ? newStr.split(' ').reverse().join(' ') : newStr;

// OR
if (typeof newStr === "string") newStr = newStr.split(' ').reverse().join(' ');