Mutations : about regular expression

can I use variable name inside “[” and “]”
example -
let x = “tree”;
let y = “brighten”;
let result = [x].test(y) // x is the variable name .
can I use [variable name] ?
please someone suggest me .

Instead of asking if it would work, why not test your code out to see if it works? You could paste your code directly in your browser’s console or you could use a site like or Codepen and use console.log statements to see what the value of the result variable is after assigning [x].test(y) to it.

To answer your question directly, if you wrote the following code, it would produce a type error on the last line, because when you surround x with [ ], you are creating an array with one element.

let x = "tree";
let y = "brighten";
let result = [x].test(y) 

In essence, you are creating an array with the string “tree” as the one element and since y is equal to “brighten”, the last line above would be the equivalent of writing the following:

let result = ["tree"].test("brighten");

Arrays do not have any built-in method named “test”, so that is why you get a Type Error which will say [x].test is not a function.

If x were a regular expression, then you could write the following without any errors.

let x = /tree/;
let y = "brighten"
let result = x.test(y);

The above code would check if the string “tree” is found in the string “brighten”. The test method used here returns a Boolean value of true or false. In this example, x.test(y) would return false, because “tree” is not found in “brighten”, so the result variable would be assigned the value false.