Test method vs match method

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.

Image 1

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

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.

Image 3

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.

Image 4

Now when the input is boolean, the code no longer returns an error, because it is not trying to match the input directly.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Create your website at WordPress.com
Get started
%d bloggers like this: