-1

At first I was confused about a return value from the javascript RegExp.prototype.test() method.

Sample code

var reg = new RegExp(/[a-z]/)
var arr = ['test']

console.log(reg.test(arr[1]))

The above code will log out true to the console when I was expecting a false value.

Then I realized that undefined is converted to the string "undefined" and since the regex matches any lowercase character in the alphabet it returns true

Why does this conversion happen?

doublea
  • 447
  • 1
  • 4
  • 11
  • 2
    [`3. Let string be ? ToString(S).`](https://tc39.es/ecma262/#sec-regexp.prototype.test), [`Undefined [...] Return "undefined"`](https://tc39.es/ecma262/#sec-tostring). Generally, javascript is a language, that tries a lot of implicit conversions. Whether that's a good or bad thing is a different topic, but here, it expects a string, so it implicitly converts to string. – ASDFGerte Jul 15 '20 at 17:16
  • General JavaScript lesson: If you get types wrong don't expect sensible behavior. Function wants a string, you'd better pass a string. – John Kugelman Jul 15 '20 at 17:18
  • @WiktorStribiżew its not a duplicate because OP understands whats happening in the code, OP's question is _Why does this conversion happen?_ – Yousaf Jul 15 '20 at 19:27
  • The argument of `RegExp` constructor must be a string, not a regex: `var reg = new RegExp('[a-z]')` or use : `var reg = /[a-z]/;` – Toto Jul 15 '20 at 20:03

1 Answers1

1

RegExp.prototype.test() expects a string, when you pass some value that is not a string, javascript tries to coerce that value to a string value.

Why does this conversion happen?

Implicit conversion of one type of value into value of another type is a feature of javascript and it is known as Type Coercion. Javascript implicitly coerces values when the provided value is different than the expected value.

Examples of type coercion

console.log(2 > '1');       // true - '1' is coerced to 1
console.log(2 + '1');       // 21   - 2 is coerced to '2'
console.log(true > '0');    // true -  true coerced to 1 and '0' coerced to 0
console.log(false == '0');  // true - false coerced to 0 and '0' coerced to 0
Yousaf
  • 27,861
  • 6
  • 44
  • 69