Member-only story

Have you really avoided the hidden trap of JavaScript array method every?

Beck Moulton
4 min readOct 31, 2024

--

In the process of learning JavaScript,Array.prototype.everyThis method may be one of the tools you frequently use. According to the description of MDN, this method is used to test whether all elements in the array have passed the provided test function and return a Boolean value. At first glance, this method appears to be very simple and easy to use, but if not careful, you may encounter some hidden pitfalls.

Simple usage scenarios

The concept of “vacuum truth” originates from mathematics and refers to the assumption that a condition is satisfied when there are no possible validation objects (such as an empty array without elements). In other words, if there are no counterexamples, we assume that all conditions hold.

stayeveryIn the specific implementation of the method, callback functions are used to test the conditions of each array element. If the array is empty, the callback function will not execute at all because there are no elements to call it. In this case, JavaScript defaults to all "elements" meeting the conditions, thereforeeveryreturntrue

Re understandevery

We usually believe thateveryIt is checking whether each element in the array satisfies a certain condition. But in reality, a more…

--

--

Beck Moulton
Beck Moulton

Written by Beck Moulton

Focus on the back-end field, do actual combat technology sharing Buy me a Coffee if You Appreciate My Hard Work https://www.buymeacoffee.com/BeckMoulton

No responses yet