From f5b5f44d8c2de61b506b6e5b7c43bb5ddf08a028 Mon Sep 17 00:00:00 2001 From: div360 Date: Thu, 9 Apr 2026 18:38:59 +0530 Subject: [PATCH] updating deepClone function to include case where arrays inside objects were being converted to plain objects during cloning --- README.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/README.md b/README.md index 3bc019c..d4b307c 100644 --- a/README.md +++ b/README.md @@ -1172,7 +1172,7 @@ var newObject = deepClone(obj); ```javascript function deepClone(object){ - var newObject = {}; + var newObject = Array.isArray(object) ? [] : {}; for(var key in object){ if(typeof object[key] === 'object' && object[key] !== null ){ newObject[key] = deepClone(object[key]); @@ -1201,6 +1201,8 @@ var personalDetail = { ``` So when we do deep clone then we should copy every property (including the nested object). +Without `Array.isArray()` check, `[1, 2, 3]` was silently cloned as `{ "0": 1, "1": 2, "2": 3 }` since both arrays and objects return `"object"` for `typeof`,fixed by initializing `newObject` as `[]` when the input is an array + ## Question 30. Best way to detect `undefined` object property in JavaScript.