Clean β’ Professional
Answer:
Example:
let obj = { a: 1, b: { c: 2 } };
let shallow = { ...obj };
let deep = JSON.parse(JSON.stringify(obj));
shallow.b.c = 3;
console.log(obj.b.c); // 3 (shallow affects original)
console.log(deep.b.c); // 2 (deep is independent)
Answer: The prototype chain is a mechanism for property lookup where an object inherits properties from its prototype, recursively up to null.
Example:
let animal = { eats: true };
let dog = Object.create(animal);
console.log(dog.eats); // true (inherited via prototype)
Answer: Generators (using function*) can pause and resume execution, yielding values one at a time.
Example:
function* generator() {
yield 1;
yield 2;
}
let gen = generator();
console.log(gen.next().value); // 1
console.log(gen.next().value); // 2
Promise.all(), Promise.race(), and Promise.any()Answer:
Promise.all(): Resolves when all promises resolve; rejects on first failure.Promise.race(): Resolves/rejects as soon as one promise settles.Promise.any(): Resolves when any promise resolves; rejects if all fail.Example:
let p1 = Promise.resolve("One");
let p2 = Promise.reject("Error");
Promise.all([p1, p2]).catch(err => console.log(err)); // "Error"
Answer:
Example:
let weakMap = new WeakMap();
let key = {};
weakMap.set(key, "value");
console.log(weakMap.get(key)); // "value"
Answer: Simplifies asynchronous code; errors handled using try...catch.
Example:
async function fetchData() {
try {
let response = await fetch("<https://api.example.com/data>");
return await response.json();
} catch (error) {
console.error("Error:", error);
}
}
Answer: Attaches a single listener to a parent to handle child events, improving performance and handling dynamic elements.
Example:
document.getElementById("parent").addEventListener("click", (e) => {
if (e.target.tagName === "BUTTON") console.log("Button clicked");
});
bind() method?Answer: Creates a new function with a fixed this context and optional arguments.
Example:
let obj = { name: "Alice" };
function greet() { console.log(this.name); }
let boundGreet = greet.bind(obj);
boundGreet(); // "Alice"
Answer: Modules organize code using import and export for reusability and encapsulation.
Example:
// math.js
export function add(a, b) { return a + b; }
// main.js
import { add } from './math.js';
console.log(add(2, 3)); // 5
Answer: Pauses execution in a debugging tool to inspect variables and call stack.
Example:
function test() {
let x = 10;
debugger; // Pauses here
console.log(x);
}
Object.seal() and Object.preventExtensions()Answer:
Object.seal(): Cannot add/remove properties but can modify existing.Object.preventExtensions(): Cannot add new properties; existing can be modified/deleted.Example:
let obj = { a: 1 };
Object.seal(obj);
obj.b = 2; // Ignored
obj.a = 3; // Allowed
Answer: Always returns same output for same input; has no side effects.
Example:
function add(a, b) { return a + b; } // Pure
Answer: Promise-based modern HTTP requests, simpler and more flexible than XMLHttpRequest.
Example:
fetch("<https://api.example.com/data>")
.then(res => res.json())
.then(data => console.log(data));
Answer: Renders 2D graphics dynamically inside a <canvas> element.
Example:
let canvas = document.getElementById("myCanvas");
let ctx = canvas.getContext("2d");
ctx.fillRect(10, 10, 50, 50);
Answer: Reads/writes to the system clipboard (copy-paste functionality).
Example:
navigator.clipboard.writeText("Copied!").then(() => console.log("Text copied"));
Answer: Array-like objects for handling binary data with fixed-size elements (e.g., Int32Array, Float64Array).
Example:
let arr = new Int32Array([1, 2, 3]);
console.log(arr[0]); // 1
Answer: Run scripts in background threads, enabling parallel execution without blocking the main thread.
Example:
// worker.js
self.onmessage = () => self.postMessage("Done");
// main.js
let worker = new Worker("worker.js");
worker.onmessage = (e) => console.log(e.data); // "Done"
Answer: Retrieves the userβs location (with permission) as latitude/longitude.
Example:
navigator.geolocation.getCurrentPosition(pos => {
console.log(pos.coords.latitude, pos.coords.longitude);
});
Answer: Transforms a multi-argument function into a sequence of single-argument functions.
Example:
function curryAdd(a) { return b => a + b; }
console.log(curryAdd(2)(3)); // 5
Answer: Caches function results to avoid redundant computations.
Example:
function memoize(fn) {
let cache = {};
return function(...args) {
let key = JSON.stringify(args);
if (cache[key]) return cache[key];
return (cache[key] = fn(...args));
};
}
Answer:
Example:
document.getElementById("parent").addEventListener("click", () => {
console.log("Parent captured");
}, true); // Capturing phase
Answer: Unique, immutable primitives used as object keys to avoid naming collisions.
Example:
let sym = Symbol("id");
let obj = { [sym]: 123 };
console.log(obj[sym]); // 123
structuredClone()?Answer: Creates a deep copy of objects, preserving nested structures.
Example:
let obj = { a: { b: 1 } };
let copy = structuredClone(obj);
copy.a.b = 2;
console.log(obj.a.b); // 1
Object.create()Answer: Creates a new object with a specified prototype for inheritance without constructors.
Example:
let proto = { greet: () => "Hello" };
let obj = Object.create(proto);
console.log(obj.greet()); // "Hello"
Answer: Functions executed immediately to create private scopes and avoid polluting the global namespace.
Example:
(function() {
let x = 10;
console.log(x); // 10
})();
Answer: Always returns a Promise, resolving to the return value or rejecting on error.
Example:
async function test() { return "Success"; }
test().then(val => console.log(val)); // "Success"
Answer: Wraps an object to intercept/customize operations like property access or assignment.
Example:
let target = { name: "John" };
let proxy = new Proxy(target, {
get: (obj, prop) => obj[prop] || "Not found"
});
console.log(proxy.age); // "Not found"
Answer: Prefixed with #, restricting access within the class, enhancing encapsulation.
Example:
class Person {
#name = "John";
getName() { return this.#name; }
}
let p = new Person();
console.log(p.getName()); // "John"
Answer: Provides methods for interceptable operations, often used with Proxy.
Example:
let obj = { a: 1 };
console.log(Reflect.get(obj, "a")); // 1
Answer: Experimental syntax for annotating/modifying classes or methods, used for metaprogramming.
Example (TypeScript):
function log(target, key) { console.log(`${key} was called`); }
class MyClass {
@log
myMethod() {}
}Β