DEV Community

Discussion on: Super ultimate guide to Regex in 2021 (how to use in JavaScript)

Collapse
 
ghaerdi profile image
Gil Rudolf Härdi • Edited

Let's see something interesting but weird:

I have a function that filter a food list and returns a fruit list.
The expected result is: ["apple", "banana", "watermelon"] but the next code don't push watermelon in the array.

const foodList = ["apple", "soap", "banana", "watermelon", "pizza"];

function getFruits(foodList) {
  const fruitRGX = /apple|banana|watermelon/g;
  const fruitList = [];

  for (const food of foodList) {
    if (!fruitRGX.test(food)) continue;

    fruitList.push(food);
  }

  return fruitList;
}

const fruits = getFruits(foodList);
const expect = ["apple", "banana", "watermelon"];

console.log({ fruits, expect });
// output:
// {
//  fruits: [ "apple", "banana" ],
//  expect: [ "apple", "banana", "watermelon" ]
// }
Enter fullscreen mode Exit fullscreen mode

If I remove the g flag in the fruitRGX or I move the constant declaration inside the for loop then fruits is equal to expect.

Can someone explain why is happening?