By the end of this tutorial, you’ll use Lodash’s _.times() to run a function a fixed number of times and collect results—without manual index increment logic.
01
Core Syntax
_.times(n, fn)
02
Index 0..n−1
Iteratee arg.
03
Returns array
Of results.
04
Build lists
Objects, IDs.
05
Stub helpers
_.stubArray
06
vs range
Fn vs numbers.
Fundamentals
What Is _.times()?
_.times(n, iteratee) calls iteratee exactly n times, passing the zero-based index 0 through n - 1 each time. It returns an array of whatever the iteratee returns on each call—unlike _.range(), which builds a numeric sequence without running your function.
💡
Beginner tip — results, not just side effects
_.times(3, i => i * 2) yields [0, 2, 4]. If the iteratee only logs and returns nothing, you get [undefined, undefined, undefined].
Use times to build placeholder arrays, generate sequential IDs, batch-index work, or pass stub helpers like _.stubArray when each iteration should produce a fresh value.
Foundation
📝 Syntax
Invoke with a count and optional iteratee (defaults to _.identity):
javascript
_.times(n, [iteratee = _.identity])
Syntax Rules
n — how many times to invoke the iteratee (converted to integer).
Index arg — iteratee receives 0, 1, …, n - 1 only—no collection item.
Return array — collects each iteratee return value into a new array.
n < 1 — returns []; iteratee is never called.
Default iteratee — omit the function and get [0, 1, …, n - 1] via identity.
javascript
import times from "lodash/times";
times(3, (i) => i * 2);
// [0, 2, 4]
Cheat Sheet
⚡ Quick Reference
Task
Code pattern
Result
Index array via identity
_.times(5)
[0, 1, 2, 3, 4]
Map index to value
_.times(3, i => i * 2)
[0, 2, 4]
Build objects
_.times(n, i => ({ id: i }))
Array of objs
Stub callback
_.times(2, _.stubString)
['', '']
Zero iterations
_.times(0, fn)
[]
Numeric sequence only
_.range(n)
Use range
Returns
Array
Results
Index
0..n-1
Iteratee arg
n < 1
[]
No calls
Category
Util
Iterate
Reference
🧰 Parameters
Arguments to _.times() and how they shape the output:
nCount
How many times to invoke the iteratee. Coerced with toInteger. Values less than 1 yield [].
_.times(3, fn)
iterateeOptional
Function called per iteration with index 0..n-1. Defaults to _.identity.
(index) => value
indexArg
Only argument passed to iteratee—zero-based, increasing by 1 each call.
0, 1, 2, ...
returnArray
Array of each iteratee return value, in iteration order.
[r0, r1, r2]
Need only a number sequence without a custom function? See _.range()—often clearer for start/end/step math.
Hands-On
Examples Gallery
Practical _.times() patterns with copy-ready code, sample output, and interactive Try It Yourself labs.
📚 Getting Started
Run an iteratee n times and collect return values.
Example 1 — Map index to a value
Each iteration receives the index; return whatever you want in the result array.
When n < 1, the loop body never runs. This differs from a raw for loop where you must check bounds yourself.
🚀 Beyond the Basics
times vs range, for loops, and Array.from.
Example 6 — times vs range vs for vs Array.from
Same length, different APIs—pick the one that reads best.
javascript
// Lodash times — callback per index
console.log(_.times(3, i => i * 10));
// [0, 10, 20]
// Lodash range — numbers only
console.log(_.range(3));
// [0, 1, 2]
// Native Array.from — flexible mapper
console.log(Array.from({ length: 3 }, (_, i) => i * 10));
// [0, 10, 20]
📤 Console output:
[0, 10, 20]
[0, 1, 2]
[0, 10, 20]
When to use which
Need only integers? _.range(). Need computed values per step? _.times. Need break or async? Use a for loop.
Compare
📋 _.times vs related patterns
Topic
_.times()
_.range()
Array.from()
for loop
Returns
Array of iteratee results
Number array
Any mapped values
Side effects only
Iteratee
Required (default identity)
None built-in
Mapper callback
Loop body
Index arg
0 .. n − 1
N/A (values are numbers)
0 .. length − 1
Manual counter
n < 1
[], no calls
[]
[]
Skip body manually
Best for
Build objects, placeholders
Indexes, pages, ticks
Native one-liners
break/continue, async
Example
_.times(3, i => i * 2)
_.range(3)
Array.from({length:3}, (_,i)=>i*2)
for (let i=0; i<3; i++)
🧠 How _.times() Works
1
Validate n
If n < 1, return an empty array immediately—no iteratee calls.
Guard
2
Loop index 0 .. n − 1
For each index, invoke the iteratee (default _.identity) with that index.
Invoke
3
Collect return values
Push each return value onto a result array in iteration order.
Build
=
🛠
Result array
A dense list of whatever your iteratee returned—ready for map, render, or further Lodash chaining.
Important
📝 Notes
The iteratee receives only the index—not a collection element.
Default iteratee is _.identity, so _.times(n) yields [0, 1, …, n − 1].
When n < 1, you get [] and the iteratee is never called.
Side-effect-only callbacks still return an array (often of undefined values).
For pure number sequences without a custom function, _.range() is often clearer.
Next in the series: _.toPath()—split string paths into property segments.
Wrap Up
Conclusion
_.times() is Lodash’s counted loop helper: run a function n times, pass the index each time, and get back an array of results. It shines when each iteration produces data—objects, strings, or computed numbers.
Pair it with stub helpers for placeholder structures, or reach for _.range() when you only need a numeric sequence without invoking a callback.
Use _.times when you want an array of computed values in one expression
Leverage the index parameter for sequential IDs or labels
Extract complex iteratee logic into a named function for readability
Pass stub references (_.stubArray) when each slot needs a fresh default
Rely on Lodash’s n < 1 guard instead of redundant if-checks
❌ Don’t
Use _.times when you only need integers—_.range is simpler
Expect the iteratee to receive collection items—only the index is passed
Call stub functions with () when you mean to pass the function reference
Use _.times for async/await per iteration—use for…of or Promise.all
Allocate huge arrays with _.times(1_000_000, …) unless you truly need every slot in memory
Summary
Key Takeaways
Knowledge Unlocked
Five things to remember about _.times()
Use these points whenever you need a counted loop that returns data.
5
Core concepts
🔢01
n iterations
Index 0 .. n−1.
Core
🔄02
Return array
Collect results.
Output
✅03
Default identity
Indexes only.
Shorthand
📝04
n < 1 → []
No calls.
Edge
🛠05
vs range
Callback vs numbers.
Compare
❓ Frequently Asked Questions
_.times(n, iteratee) invokes iteratee n times with the index 0, 1, …, n − 1, and returns an array of each invocation’s return value. It is a compact alternative to a counted for loop when you want results collected.
One argument: the zero-based index of the current iteration (0 through n − 1). There is no collection element—only the index.
An array of whatever the iteratee returns each time. Side-effect-only iteratees often yield an array of undefined values; returning data (numbers, objects, strings) is the common pattern.
Lodash returns an empty array []—no iteratee calls. You do not need a manual guard for n <= 0 in most cases.
_.range builds a number sequence from start/end/step. _.times runs a function n times and collects return values. Use range for numeric arrays; times when each step produces a computed value.
Use _.times when you want a functional style and an array of results in one expression. Use a for loop when you need break/continue, async/await per iteration, or imperative control flow.
Did you know?
Omitting the iteratee makes _.times(n) behave like _.range(n)—both produce [0, 1, …, n − 1] because the default callback is _.identity.