diff --git a/README.md b/README.md index 7bdd6eaf..6ee42915 100644 --- a/README.md +++ b/README.md @@ -12520,6 +12520,37 @@ This question is really showcasing how JavaScript mixes array reduction with low

+### 88.What is the output of the following snippet? +***javascript +console.log("A"); + +setTimeout(() => { + console.log("B"); +}, 0); + +Promise.resolve().then(() => { + console.log("C"); +}); + +console.log("D"); + +*** + +- 1. A D B C +- 2. A D C B +- 3. A C D B +- 4. A B C D + +
Answer +

+### Answer : 2 + +The output is A D C B because JavaScript executes all synchronous code first, so “A” and “D” are printed immediately. After that, the event loop handles asynchronous tasks, where Promise.then() is placed in the microtask queue and setTimeout(...,0) goes to the macrotask queue. Since microtasks always execute before macrotasks—regardless of the timeout value—the promise callback prints “C” next, and finally the timeout callback prints “B”, resulting in the final order: A D C B. + +

+
+ + **[⬆ Back to Top](#table-of-contents)** ## Disclaimer diff --git a/coding-exercise/deepclone.js b/coding-exercise/deepclone.js new file mode 100644 index 00000000..e084de45 --- /dev/null +++ b/coding-exercise/deepclone.js @@ -0,0 +1,28 @@ +function deepClone(value, hash = new WeakMap()) { + // Handle primitives + if (value === null || typeof value !== "object") return value; + + // Handle circular references + if (hash.has(value)) return hash.get(value); + + // Handle Date + if (value instanceof Date) return new Date(value); + + // Handle RegExp + if (value instanceof RegExp) return new RegExp(value); + + // Handle Arrays or Objects + const clone = Array.isArray(value) ? [] : {}; + + // Store reference in WeakMap (for circular structures) + hash.set(value, clone); + + // Recursively clone properties + for (let key in value) { + if (value.hasOwnProperty(key)) { + clone[key] = deepClone(value[key], hash); + } + } + + return clone; +}