Lodash _.clone() method
What you’ll learn
- How
_.clone(value)creates a new top-level array or object. - Why nested values are still shared after a shallow clone.
- How to detect when
_.cloneDeep()is a better fit. - How to test clone behavior quickly using Try-it examples.
Prerequisites
Know the difference between value copy and reference copy in JavaScript objects and arrays.
- You are comfortable with object and array references.
- You can run snippets in Node or in the browser Try-it editor.
Overview
_.clone gives you a new outer container while preserving inner references. It is useful for lightweight immutability where deep isolation is not required.
Shallow copy
Top-level object or array is new, but nested references are reused.
Fast and simple
Lower overhead than deep clone for many everyday update workflows.
Pair with cloneDeep
Switch to _.cloneDeep when nested mutation safety is required.
Syntax
_.clone(value) - value: object, array, or any clonable JavaScript value.
- Returns: a shallow clone of the input.
Plain object
The cloned object is a different top-level reference.
import clone from "lodash/clone";
var user = { id: 1, role: "admin" };
var copy = clone(user);
console.log(copy === user); // false Nested refs
Nested objects are shared in a shallow clone.
import clone from "lodash/clone";
var state = { settings: { theme: "light" } };
var copy = clone(state);
copy.settings.theme = "dark";
console.log(copy.settings === state.settings); // true Array entries
The array container is cloned, but object elements inside are still shared.
import clone from "lodash/clone";
var list = [{ n: 1 }, { n: 2 }];
var copy = clone(list);
copy[0].n = 99;
console.log(copy === list); // false
console.log(copy[0] === list[0]); // true 📋 _.clone vs _.cloneDeep
| Method | Depth | Best for |
|---|---|---|
_.clone(value) | Shallow | Fast top-level copies when nested mutation is not needed. |
_.cloneDeep(value) | Deep | Full nested isolation before edits. |
Pitfalls to avoid
Assuming deep copy
Shallow clones still share nested references; nested edits can leak into the original.
Mutating shared nested state
In state management flows, clone only solves top-level immutability. Deep paths still need care.
Overusing cloneDeep
Deep cloning everything can be expensive. Use it only when deep isolation is truly required.
❓ FAQ
Summary
- Purpose:
_.clonecreates a shallow copy of a value. - Caution: nested references remain shared.
- Next: continue to Lodash _.cloneDeep() for deep cloning.
_.clone is shallow, so nested objects and arrays remain shared references.
6 people found this page helpful
