I decided to write this post after I kept stumbling across the same error. I found that a piece of code that utilised the .match() method would work fine when the input values were of a data type that it accepted. For example, strings and numbers would work fine, but when the input was boolean the code would throw up the error ‘x.match is not a function’. This baffled me, as I was expecting the code to not return anything, i.e. not to match, but not to throw up an error. Thankfully I discovered a smart way around this via the .test() method.
The .map() method employed in image 1 contains a very simple .match() method that will match with any array value that’s a lowercase letter.
Image 2 uses the same code as image 1 but has a different input – the input values here instead are boolean values. As boolean are not lowercase letters, I initially expected the code to return no matches, but to my surprise, it returned an error. This is obviously problematic.
In image 3, the code has replaced the .match() method with a .test() method and has used it in tandem with the ternary operator. The /[a-z]/.test(x) part of the code is not asking to return a match, but instead is asking only if the input passes the RegEx criteria. The output of .test() is only ever true or false. Therefore the output to this just this part would be [true, true, true], then the ternary operator receives this input and returns x for every index.
Now when the input is boolean, the code no longer returns an error, because it is not trying to match the input directly.