Implement shallowClone() in JavaScript
Expected behavior
Your shallowClone(value) implementation should:
Accept only objects and arrays as root inputs. Arrays return a new array reference with the same length, holes, top-level items, and custom own enumerable properties. Objects return a new object reference with the same own enumerable properties. Top-level primitive property and item values are copied by value inside the cloned container. Nested objects and arrays remain shared references. Updating a top-level property or array slot on the clone does not mutate the original container. Mutating a nested object or nested array through the clone is visible through the original. null and primitive root inputs throw TypeError. The base solution copies own enumerable string and symbol properties. Prototype chains and property descriptors are not preserved.
Arguments
value: Object | Array —The object or array to clone.
Returns
Object | Array — Solution idea
Interview answer: the base prompt is to create a new top-level container while preserving nested references. Guard null and primitive values first. For arrays, allocate new Array(value.length) and copy with Object.assign so holes and length survive while custom own enumerable string and symbol properties are included. For objects, use Object.assign({}, value). Both branches ignore inherited prototype properties. Deep cloning, structuredClone(), JSON cloning, prototypes, descriptors, Maps, Sets, Dates, and circular references are follow-ups, not part of the minimal shallowClone(value) contract.
// Array shallow clone
const original = [1, { count: 2 }];
const copy = shallowClone(original);
copy === original; // false
copy[1] === original[1]; // true
copy[0] = 99;
original[0]; // 1
copy[1].count = 3;
original[1].count; // 3
// Object shallow clone
const user = { name: 'Ada', meta: { active: true } };
const cloned = shallowClone(user);
cloned === user; // false
cloned.meta === user.meta; // truePublic interview reports
These public, self-reported interview accounts informed this practice version. The exercise is modelled on reported rounds, not copied from them, and the reports are not verified official questions or endorsements.
- GitHub: repository with a file labelled TeslaRound1, 2025
The repository says it holds solutions to questions asked in a Tesla interview. Exercise 1 of its TeslaRound1 file copies a nested employee object shallowly and deeply.
- GoodJob: Shopee frontend engineer written test and panels, Taipei, January 2021
The 90-minute written test asked for shallow copy versus deep copy; a 2020 campus account asked the same with the ways to deep-copy. This drill is a practice version of the shallow side, not the reported wording.
Reported in a public Tesla interview account. Tesla frontend interview questions
Reported in a public Shopee interview account. Shopee frontend interview questions
Solution
Overview
Interview answer: the base prompt is to create a new top-level container while preserving nested references. Guard null and primitive values first. For arrays, allocate new Array(value.length) and copy with Object.assign so holes and length survive while custom own enumerable string and symbol properties are included. For objects, use Object.assign({}, value). Both branches ignore inherited prototype properties. Deep cloning, structuredClone(), JSON cloning, prototypes, descriptors, Maps, Sets, Dates, and circular references are follow-ups, not part of the minimal shallowClone(value) contract.
Shallow clone vs deep clone: A shallow clone creates a new top-level object or array but keeps nested references shared. A deep clone recursively creates new nested objects and arrays. This challenge is intentionally shallow; deep clone behavior belongs in the related deep clone challenge.
Approach: Branch on array vs object
Guard unsupported root values before cloning: null and primitives should throw a TypeError. For an array, allocate new Array(value.length) so trailing holes and length are retained, then use Object.assign to copy its present indexes plus custom own enumerable string and symbol properties. Otherwise clone the object with Object.assign({}, value). Object.assign ignores inherited prototype properties, runs in O(n) time over own enumerable properties, uses O(n) space for the new top-level container, and preserves nested references by design.
export default function shallowClone(value) {
if (value === null || typeof value !== 'object') {
throw new TypeError('Expected object or array');
}
if (Array.isArray(value)) {
return Object.assign(new Array(value.length), value);
}
return Object.assign({}, value);
}
export default function shallowClone<T extends Record<string, any> | any[]>(value: T): T {
if (value === null || typeof value !== 'object') {
throw new TypeError('Expected object or array');
}
if (Array.isArray(value)) {
return Object.assign(new Array(value.length), value) as T;
}
return Object.assign({}, value) as T;
}
Notes & Pitfalls
This is a shallow clone: nested objects and arrays are still shared by reference. nullis an object in JS, so guardvalue === nullbefore the object branch.Object.assigncopies own enumerable string and symbol properties, but it does not preserve descriptors or prototypes.Avoid for...infor the base solution because it can walk inherited prototype properties.
[]returns a new empty array (different reference).{}returns a new empty object (different reference).Nested objects remain the same reference in the clone. Sparse arrays keep their holes, length, and custom enumerable string and symbol properties.
Array copying with Object.assign(new Array(value.length), value).Object copying with Object.assign({}, value).Guard-first input validation before branching.
Common mistakes on this challenge
Guard null and primitive root values first
The base contract accepts only object and array containers, and typeof nullneeds a separate check.Start with if (value === null || typeof value !== "object") throw new TypeError(...).Place the guard before the array and object clone branches. Verify null,undefined, numbers, strings, and booleans all throwTypeError.
Return a new top-level container
A shallow clone must be equal in contents but not the same array or object reference. For arrays, return Object.assign(new Array(value.length), value)so the clone is new while holes, length, and custom enumerable properties are preserved.For objects, return Object.assign({}, value)so top-level writes to the clone do not mutate the original container.Do not return valuedirectly and do not mutate the input while copying.
Keep nested references shared
This prompt is intentionally shallow, so nested objects and arrays should not be recursively cloned. Copy only the top-level array or object container. Avoid recursion, structuredClone(), and JSON serialization for this base prompt.Check that copy.nested === original.nestedremains true after cloning.
Copy own enumerable properties only
Object.assigncopies own enumerable string and symbol properties while ignoring inherited prototype properties.Use Object.assign({}, value)or object spread for the object branch.For arrays, assign into new Array(value.length)so present indexes and custom enumerable string/symbol properties are copied without filling holes.Avoid Object.keys(value)alone if symbol keys need to be copied.Avoid for...inbecause it can include inherited prototype properties.
Clone one level and preserve shallow semantics
Shallow clone means new top-level container, own enumerable properties copied, and nested references shared. Guard invalid root values before cloning. Use Object.assign(new Array(value.length), value)for arrays andObject.assign({}, value)for objects.Do not recurse or use deep-clone helpers for this prompt.
Common interview follow-ups:
How would structuredClone() change the behavior for nested references? When would you preserve prototypes or descriptors? How would Maps, Sets, Dates, class instances, or circular references change the contract? When is Object.assign({}, value) preferable to object spread, or vice versa?
Resources
Related links
Guides
Preparing for interviews? Use Frontend Coding Challenges first, then move into a concrete Study Plan before targeted Company Prep.
Built in public
The code behind FrontendAtlas lives on GitHub. A star helps other frontend engineers find it.