Lodash _.times() Method

Beginner
⏱️ 7 min read
📚 Updated: Jul 2026
🎯 6 Examples + 3 Try It
Util utilities

What You’ll Learn

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.

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.

📝 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]

⚡ Quick Reference

TaskCode patternResult
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

🧰 Parameters

Arguments to _.times() and how they shape the output:

n Count

How many times to invoke the iteratee. Coerced with toInteger. Values less than 1 yield [].

_.times(3, fn)
iteratee Optional

Function called per iteration with index 0..n-1. Defaults to _.identity.

(index) => value
index Arg

Only argument passed to iteratee—zero-based, increasing by 1 each call.

0, 1, 2, ...
return Array

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.

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.

javascript
console.log(_.times(3, i => i * 2));

// [0, 2, 4]
Try It Yourself

How It Works

Indexes are 0, 1, 2. The iteratee runs three times; Lodash pushes each return value into the final array.

Example 2 — Default iteratee (identity)

Omit the callback and Lodash uses _.identity—handy when you just need indexes.

javascript
console.log(_.times(3));

console.log(_.times(5));

// [0, 1, 2]

// [0, 1, 2, 3, 4]

How It Works

_.times(n) is similar to _.range(n) when you only need 0-based indexes—times runs a function; range builds numbers directly.

Example 3 — Build a list of objects

Generate sequential IDs or placeholder rows in one expression.

javascript
const items = _.times(4, i => ({

  id: i + 1,

  name: `Item ${i + 1}`

}));



console.log(items);

// [{ id: 1, name: "Item 1" }, …]
Try It Yourself

How It Works

Each object is created fresh on every call—unlike reusing one shared object in a manual loop.

📈 Practical Patterns

Stub helpers, edge cases, and side effects.

Example 4 — Stub iteratee for placeholder arrays

Pass a stub function reference (no parentheses) so each iteration returns a new empty array.

javascript
const rows = _.times(3, _.stubArray);



console.log(rows);

console.log(rows[0] === rows[1]);

// [[], [], []]

// false
Try It Yourself

How It Works

_.stubArray is invoked per iteration—each slot gets its own []. See also _.stubArray().

Example 5 — Zero or negative n

Lodash returns [] without calling the iteratee—no manual guard needed.

javascript
console.log(_.times(0, () => "never"));

console.log(_.times(-2, () => "never"));

// []

// []

How It Works

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]

When to use which

Need only integers? _.range(). Need computed values per step? _.times. Need break or async? Use a for loop.

🧠 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.

📝 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.

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.

💡 Best Practices

✅ Do

  • 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

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
🔄 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.

Practice _.times() in the Live Editor

Map indexes to values, build object lists, and try stub iteratees.

Open Try It editor →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

6 people found this page helpful