Every And Some Validate With Short Circuit
every and some validate arrays with short-circuit evaluation, so predicate calls stop at the first failing or passing element.
Code
// every:全部通过才为 true,遇到第一个失败立即短路
const scores = [82, 91, 75, 88];
console.log('all pass 60:', scores.every((s) => s >= 60));
console.log('all pass 80:', scores.every((s) => s >= 80));
// some:任一通过即为 true,遇到第一个通过立即短路
console.log('any over 90:', scores.some((s) => s > 90));
console.log('any under 60:', scores.some((s) => s < 60));
// 短路(short-circuit)意味着 validate 谓词的调用次数可能远小于数组长度
let someCalls = 0;
console.log('some > 80:', scores.some((s) => { someCalls++; return s > 80; }));
console.log('some stopped after', someCalls, 'calls');
let everyCalls = 0;
console.log('every >= 80:', scores.every((s) => { everyCalls++; return s >= 80; }));
console.log('every stopped after', everyCalls, 'calls');Output
Captured from a sandboxed run of this snippet in the build pipeline.
all pass 60: true
all pass 80: false
any over 90: true
any under 60: false
some > 80: true
some stopped after 1 calls
every >= 80: false
every stopped after 3 callsHow it works
Top-level bindings scores, someCalls, everyCalls hold the demo state — nothing sits inside a function scope.
Applying it
The run emits 8 labeled sections — all pass 60:, all pass 80:, any over 90:, any under 60:, some > 80:, some stopped after, every >= 80:, every stopped after — one per step.
Statements that matter
const scores = [82, 91, 75, 88];
let everyCalls = 0;
let someCalls = 0;
Interactive Tools for This Topic
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Credit Card Brand DetectorIdentify the card network from a number's prefix and length, validate the Luhn checksum, and show a masked form and the issuer identification number.
FAQ
- Can I paste this into a project as-is?
- Yes. Paste it in and run; no package manager step is needed. Its state lives in module-level bindings: `scores`, `someCalls`, `everyCalls`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.