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.
["apple", "banana", "watermelon"]
watermelon
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" ] // }
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.
g
fruitRGX
fruits
expect
Can someone explain why is happening?
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
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 pushwatermelon
in the array.If I remove the
g
flag in thefruitRGX
or I move the constant declaration inside the for loop thenfruits
is equal toexpect
.Can someone explain why is happening?